diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3bacc83874cf3df6b41a6b7be9bab1adc3682ca1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67eb9c4ba1a0cf4f1c3a7ab191a476b43d185e99 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/heartbeat.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/heartbeat.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..957eeee1c55ecf07a9ca1518f2e06de6891ea759 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/heartbeat.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/patch.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/patch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..af682c1d4e23897bebd7ab31317e702916f6ae5e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/patch.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/plugin.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/plugin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..430eaae56fd50ee56c06d4fd975f84e06cc9350b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/plugin.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/tokens.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/tokens.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78f103ba324eb129b967868fb937a83fc2f29df0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/tokens.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adc77fcda08972c954967bca096681eb5ee36ed1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_anon_usage/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88db14d5d18abf29165d15eab19084ac8485666e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa1431a9909cd08e42b9e756b216f221cb4ecdc0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acc0c088ca094f1ca11f596afa980200f77d099f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/actions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/actions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3691804bd4d699ab7aa9108a07f63b62ebccbc05 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/actions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/adapters.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/adapters.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e24897c92f30288e59c491f4f9edf7eb8f06ddc4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/adapters.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/cli.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..42ba3bc6bd4d231b344264549603d6cd0a4173c9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/cli.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81719dc2a52c74c4b64355d7e7cdc3246fd0dbe8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/config.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f208e8c11ed0196d8c14626fc6e61de76c86311e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/device_flow.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/device_flow.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8034cdf1b15ddfc648f65a4640c9bfe09715773c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/device_flow.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..541aa093caf1980b0c4a4ac1757f8ad83d5d49fb Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/handlers.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/handlers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a20781777f1bb739e7175fcbfc7e8e3ee5321de Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/handlers.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/panel.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/panel.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad869328436272352f0bbb3115c2539064937a02 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/panel.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/repo.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/repo.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66c1dda9c2b443fc81632006ff18bf00b3026aef Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/repo.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/token.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f945f7aa492fcff4077826dc1769c8df50630ba5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/token.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2a79b3bb98a5febb6c473387dc203a984b2705 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__init__.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0a89e1c4e9fffcc79d70c4c8fa422ef8f6ced7f2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__init__.py @@ -0,0 +1,12 @@ +"""This module provides conda plugins. + +Since conda is not a strict dependency of `anaconda-auth`, the modules here should +NOT be imported outside of this module. This package is declared as the plugin entrypoint +inside `pyproject.toml` such that it will be imported and, if conda is installed, the +plugin definitions will be imported. However, if conda is not installed, no plugins are +imported into the runtime. + +As a result, we do not have to spread conditional imports everywhere, but we do need to +be careful that only the single top-level import of this subpackage is performed. + +""" diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14c7e23bdabc0a46616ed472d8ebcb7a70138b8f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/auth_handler.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/auth_handler.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95c04142d9382559e7846b64672cc8238a3c1d44 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/auth_handler.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_api.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..996cc80f82b25725b2ab97cde0033fd69e95aa9b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_api.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_token.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_token.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df1086d0b8fc69f39b31e8df62857afb304c7387 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/conda_token.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/condarc.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/condarc.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fefd5e288c5477813c398c17cdb48421aa64201f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/condarc.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/config.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb0316e375d70635843b819b768a8c7b513ba305 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/entrypoint.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/entrypoint.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..748f94b4e23795f01a204e2ed650e8099dfd00ed Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/entrypoint.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/plugins.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/plugins.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..294075137a61691d86d9a28ccad5f4fcb10d3ab4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/plugins.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/repo_config.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/repo_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..eadf8624974e55a0b177598b15519008a9457cdc Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/__pycache__/repo_config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/auth_handler.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/auth_handler.py new file mode 100644 index 0000000000000000000000000000000000000000..007c728ea4b4a770febe47558b9732628f87be79 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/auth_handler.py @@ -0,0 +1,165 @@ +"""Defines an auth handler to inject an Authorization header into each request. + +Tokens are assumed to be installed onto a user's system via a separate CLI command. + +""" + +from functools import lru_cache +from typing import Any +from typing import Optional +from urllib.parse import urlparse + +from conda import CondaError +from conda.plugins.types import ChannelAuthBase +from requests import PreparedRequest +from requests import Response + +from anaconda_auth._conda import repo_config +from anaconda_auth._conda.config import TOKEN_DOMAIN_MAP +from anaconda_auth.config import AnacondaAuthConfig +from anaconda_auth.exceptions import TokenNotFoundError +from anaconda_auth.token import TokenInfo + +URI_PREFIX = "/repo/" + + +class AnacondaAuthError(CondaError): + """ + A generic error to raise that is a subclass of CondaError so we don't trigger the unhandled exception traceback. + """ + + +class AnacondaAuthHandler(ChannelAuthBase): + @staticmethod + def _load_token_from_keyring(url: str) -> Optional[str]: + """Attempt to load an appropriate token from the keyring. + + We parse the requested URL, extract what may be an organization ID, and first + attempt to load the token for that specific organization. If that fails, we + then simply return the first token in the keyring (since this is in all likelihood + one of the default channels ('main', 'r', etc.). + + If no token can be found in the keyring, we return None, which means that + the token will attempt to be read from via conda-token instead. + + """ + parsed_url = urlparse(url) + channel_domain = parsed_url.netloc.lower() + if channel_domain in TOKEN_DOMAIN_MAP: + token_domain, is_unified, _ = TOKEN_DOMAIN_MAP[channel_domain] + else: + token_domain, is_unified = channel_domain, False + + try: + token_info = TokenInfo.load(token_domain) + except TokenNotFoundError: + # Fallback to conda-token if the token is not found in the keyring + return None + + # Check configuration to use unified api key, + # otherwise continue and attempt to utilize repo token + if api_key := token_info.api_key: + if is_unified: + return api_key + try: + config = AnacondaAuthConfig(domain=token_domain) + if config.use_unified_repo_api_key: + return api_key + except Exception: + pass + + path = parsed_url.path + if path.startswith(URI_PREFIX): + path = path[len(URI_PREFIX) :] + maybe_org, _, _ = path.partition("/") + + # First we attempt to return an organization-specific token + try: + return token_info.get_repo_token(maybe_org) + except TokenNotFoundError: + pass + + # Return the first one, assuming this is not an org-specific channel + try: + return token_info.repo_tokens[0].token + except IndexError: + pass + + return None + + @staticmethod + def _load_token_via_conda_token(url: str) -> Optional[str]: + domain = urlparse(url).netloc.lower() + # Try to load the token via conda-token if that is installed + if repo_config is not None: + tokens = repo_config.token_list() + for token_url, token in tokens.items(): + token_netloc = urlparse(token_url).netloc + if token_netloc.lower() == domain and token is not None: + return token + return None + + @lru_cache + def _load_token(self, url: str) -> Optional[str]: + """Load the appropriate token based on URL matching. + + First, attempts to load from the keyring. If that fails, we attempt + to load the legacy repo token via conda-token. + + Cached for performance. + + Args: + url: The URL for the request. + + Returns: + The token, if it can be loaded. None, otherwise. + + """ + + # First, we try to load the token from the keyring. If it is not found, we fall through + if token := self._load_token_from_keyring(url): + return token + elif token := self._load_token_via_conda_token(url): + return token + return None + + def handle_missing_token(self, response: Response, **_: Any) -> Response: + """Raise a nice error message if the authentication token is missing.""" + if response.status_code in {401, 403}: + raise AnacondaAuthError( + f"Token not found for {self.channel_name}. Please install token with " + "`anaconda token install`." + ) + return response + + def handle_invalid_token(self, response: Response, **_: Any) -> Response: + """Raise a nice error message if the authentication token is invalid (not missing).""" + if response.status_code in {401, 403}: + raise AnacondaAuthError( + f"Received authentication error ({response.status_code}) when " + f"accessing {self.channel_name}. " + "If your token is invalid or expired, please re-install with " + "`anaconda token install`." + ) + return response + + def __call__(self, request: PreparedRequest) -> PreparedRequest: + """Inject the token as an Authorization header on each request.""" + try: + token = self._load_token(request.url) + except Exception: + # TODO(mattkram): We need to be very resilient about exceptions here for now + token = None + + if not token: + request.register_hook("response", self.handle_missing_token) + return request + + request.register_hook("response", self.handle_invalid_token) + config = AnacondaAuthConfig() + if config.use_unified_repo_api_key: + request.headers["Authorization"] = f"Bearer {token}" + else: + request.headers["Authorization"] = f"token {token}" + + return request diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_api.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_api.py new file mode 100644 index 0000000000000000000000000000000000000000..b21525eaf8ec28f167a5c817f3dd992777a3defa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_api.py @@ -0,0 +1,27 @@ +# This is a minimal reimplementation of the deprecated conda.cli.python_api +# module. It uses the subprocess module to duplicate the fullest extent of +# the run_command functionality needed for tests. But most of the internal +# uses of run_command do not require this overhead and are better served +# working in process. So when subprocess is needed, we do this: +# from anaconda_auth._conda.conda_api import Commands, run_command +# and when it is not needed, we do this: +# from anaconda_auth._conda.conda_api import Commands +# from conda.cli.main import main as run_command + + +import subprocess + + +class Commands: + CLEAN = "clean" + CONFIG = "config" + INSTALL = "install" + LIST = "list" + REMOVE = "remove" + SEARCH = "search" + + +def run_command(*args, use_exception_handler=False): # type: ignore + args = ("python", "-m", "conda") + args + proc = subprocess.run(args, capture_output=True, text=True) + return proc.stdout, proc.stderr, proc.returncode diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_token.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_token.py new file mode 100644 index 0000000000000000000000000000000000000000..4b7be47ad455b60beff92e5e8a8af96b9349bd5c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/conda_token.py @@ -0,0 +1,152 @@ +""" +CLI for conda-token. +""" + +from __future__ import annotations + +import os +import sys +from argparse import ArgumentParser +from argparse import Namespace + +from anaconda_auth import __version__ +from anaconda_auth._conda import repo_config + + +def token_list(args: Namespace) -> int: + """Default function for list subparser.""" + tokens = { + k: v for k, v in repo_config.token_list().items() if k == repo_config.REPO_URL + } + if not tokens: + print( + f"No tokens have been configured for {repo_config.REPO_URL}", + file=sys.stderr, + ) + return 1 + + for url, token in tokens.items(): + print(url, token) + + return 0 + + +def token_set(args: Namespace) -> int: + try: + repo_config.validate_token(args.token, no_ssl_verify=args.no_ssl_verify) + except repo_config.CondaTokenError as e: + print(e, file=sys.stderr) + return 1 + + repo_config.token_set( + args.token, + args.system, + args.env, + args.file, + args.include_archive_channels, + args.no_ssl_verify, + args.enable_signature_verification, + force=args.force_config_condarc, + ) + print("Success! Your token was validated and Conda has been configured.") + return 0 + + +def token_remove(args: Namespace) -> int: + repo_config.token_remove() + return 0 + + +def condarc_path_args(parser: ArgumentParser) -> None: + """Add condarc path arguments.""" + config_file_location_group = parser.add_argument_group( + "Config File Location Selection", + f"Without one of these flags, the user config file at '{repo_config.escaped_user_rc_path}' is used.", + ) + location = config_file_location_group.add_mutually_exclusive_group() + location.add_argument( + "--system", + action="store_true", + help=f"Write to the system .condarc file at '{repo_config.escaped_user_rc_path}'.", + ) + location.add_argument( + "--env", + action="store_true", + help=( + f"Write to the active conda environment .condarc file ({os.getenv('CONDA_PREFIX', '').replace('%', '%%')}). " + f"If no environment is active, write to the user config file ({repo_config.escaped_user_rc_path})." + ), + ) + location.add_argument("--file", action="store", help="Write to the given file.") + + +def cli(argv: list[str] | None = None) -> int: + parser = ArgumentParser( + "conda-token", + usage="conda token", + description="Configure token access for Anaconda Commercial Edition", + ) + + parser.add_argument( + "-V", + "--version", + action="version", + help="Show the conda-token version number and exit.", + version=f"conda-token {__version__}", + ) + + subparser = parser.add_subparsers(help="Token commands") + + subparser_list = subparser.add_parser("list", help="List token if configured.") + subparser_list.set_defaults(func=token_list) + + subparser_remove = subparser.add_parser( + "remove", help="Remove token and revert default_channels." + ) + condarc_path_args(subparser_remove) + subparser_remove.set_defaults(func=token_remove) + + subparser_set = subparser.add_parser( + "set", help="Set your token and configure default_channels." + ) + subparser_set.add_argument("token", help="Your token.") + subparser_set.add_argument( + "--include-archive-channels", + choices=repo_config.ARCHIVE_CHANNELS, + help="Add archived channels to default_channels. " + "\nAvailable channels are mro, mro-archive, free, and pro.", + nargs="+", + default=None, + metavar="CHANNEL_NAME", + ) + subparser_set.add_argument( + "--no-ssl-verify", + help="Force disabling SSL verification. " + "By default conda-token will respect your " + "ssl_verify flag in your Conda settings. " + "Using this flag will add ssl_verify: false " + "to your .condarc file. If not already set.", + action="store_true", + ) + subparser_set.add_argument( + "--enable-signature-verification", + action="store_true", + help="Enable Conda package signature verification. Default is off.", + ) + subparser_set.add_argument( + "--force-config-condarc", + action="store_true", + help="Force configuration of .condarc", + ) + condarc_path_args(subparser_set) + subparser_set.set_defaults(func=token_set) + + if len(sys.argv) == 1: + sys.argv.append("--help") + + args = parser.parse_args(argv) + return args.func(args) + + +if __name__ == "__main__": + cli(sys.argv[1:]) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/condarc.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/condarc.py new file mode 100644 index 0000000000000000000000000000000000000000..3b4680eb2f36c091eee74e59f35ec8b9263ffdc8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/condarc.py @@ -0,0 +1,93 @@ +from __future__ import annotations + +from pathlib import Path +from typing import Any + +from ruamel.yaml import YAML +from ruamel.yaml import YAMLError + +from anaconda_cli_base import console + +DEFAULT_CONDARC_PATH = Path("~/.condarc").expanduser() + +yaml = YAML() + + +class CondaRCError(Exception): + pass + + +class CondaRC: + def __init__(self, condarc_path: Path | None = None): + """ + Initializes the CondaRC object by attempting to open and load the contents + of the condarc file found in the user's home directory. + """ + self.condarc_path = condarc_path or DEFAULT_CONDARC_PATH + self._loaded_yaml: dict[str, Any] = {} + self.load() + + @property + def _backup_condarc_path(self) -> Path: + return self.condarc_path.with_suffix(".bak") + + def load(self, path: Path | None = None) -> None: + path = path or self.condarc_path + try: + path.touch() + with path.open("r") as fp: + contents = fp.read() + except OSError as exc: + raise CondaRCError(f"Could not open condarc file: {exc}") + + try: + self._loaded_yaml = yaml.load(contents) or {} + except YAMLError as exc: + raise CondaRCError(f"Could not parse condarc: {exc}") + + def update_channel_settings( + self, channel: str, auth_type: str, username: str | None = None + ) -> None: + """ + Update the condarc file's "channel_settings" section + """ + if username is None: + updated_settings = {"channel": channel, "auth": auth_type} + else: + updated_settings = { + "channel": channel, + "auth": auth_type, + "username": username, + } + + channel_settings = self._loaded_yaml.get("channel_settings", []) or [] + + # Filter out the existing channel's entry if it's there + filter_settings = [ + settings + for settings in channel_settings + if settings.get("channel") != channel + ] + + # Add the updated settings map + filter_settings.append(updated_settings) + + self._loaded_yaml["channel_settings"] = filter_settings + + def restore(self) -> None: + console.print(f"Restoring config from {self._backup_condarc_path}") + self.load(self._backup_condarc_path) + self.save() + + def backup(self) -> None: + console.print(f"Backing up config to {self._backup_condarc_path}") + self.save(self._backup_condarc_path) + + def save(self, path: Path | None = None) -> None: + """Save the condarc file""" + path = path or self.condarc_path + try: + with path.open("w") as fp: + yaml.dump(self._loaded_yaml, fp) + except OSError as exc: + raise CondaRCError(f"Could not save file: {exc}") diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/config.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0d941858c0ba065b45de87d7daaeff2aa28b7f9f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/config.py @@ -0,0 +1,152 @@ +"""Configuration manager for the conda plugin. + +This file is used as a central location to manage global configuration +settings and deliver them to the locations where they are needed, including +other modules and YAML configuration files. It is designed to be callable as +a standalone script or as a module. It can install a conda configuration file +in the prefix, and to verify its existence and expected behavioral impact. +These functions are both used by the conda recipe itself. + +It is imperative that this module not include any other anaconda_auth imports +so that it can be run during the conda build process +""" + +import sys +from pathlib import Path +from typing import Any +from typing import Dict +from typing import List +from typing import NamedTuple +from typing import Set +from typing import Union + +__all__ = [] + + +PREFIX_CONDARC_PATH = Path(sys.prefix) / "condarc.d" / "anaconda-auth.yml" + + +# This list is now serving THREE purposes. The keys are used in the conda +# plugin module to determine which hosts should be hardcoded to use +# anaconda-auth for authentication. The values are used to provide the +# keyring domain where the legacy token will be stored, as well as +# whether or not the destination should receive a proper API key. +# Finally, the list is used to generate the master anaconda-auth.yml +# configuration for conda. +class TokenDomainSetting(NamedTuple): + token_domain: str + default_use_unified_api_key: bool = True + autoconfigure_conda_channel_settings: bool = False + + +TOKEN_DOMAIN_MAP = { + "repo.continuum.io": TokenDomainSetting("anaconda.com"), + "repo.anaconda.com": TokenDomainSetting("anaconda.com"), + "repo.anaconda.cloud": TokenDomainSetting("anaconda.com", False, True), +} + + +def _dictify(channel_settings: List[Dict[str, str]]) -> Dict[str, str]: + """ + Extract the authentication information for each channel + for better comparison with expectations. + """ + return {c["channel"]: c.get("auth", "") for c in channel_settings} + + +def _assert_settings( + context: Any, expected: Dict[str, str], filtered: bool = False +) -> None: + """ + Compare just the channel authentication information for each + channel with the expectation, with order independence + """ + found = _dictify(context.channel_settings) + if filtered: + found = {k: v for k, v in expected.items() if k in expected} + assert found == expected, f"{found=}, {expected=}" + + +def _build_channel_settings( + include_defaults: bool = True, include_sites: bool = True +) -> List[Dict[str, str]]: + hosts: Set[str] = set() + if include_defaults: + hosts.update( + repo_domain + for repo_domain, settings in TOKEN_DOMAIN_MAP.items() + if settings.autoconfigure_conda_channel_settings + ) + if include_sites: + # We are delaying this import so this file can be run standalone + from anaconda_auth.config import AnacondaAuthSitesConfig + + hosts.update(s.domain for s in AnacondaAuthSitesConfig().sites.root.values()) + return [{"channel": f"https://{host}/*", "auth": "anaconda-auth"} for host in hosts] + + +def _build_channel_yaml( + include_defaults: bool = True, include_sites: bool = True +) -> str: + settings = _build_channel_settings(include_defaults, include_sites) + # Hand-construct the YAML so we can avoid a library dependency, and + # easily include the warning comment. + lines = [ + "# DO NOT EDIT THIS FILE.", + "# This file was generated automatically for anaconda-auth.", + ] + lines.append("channel_settings:") + for record in settings: + pfx = "- " + for key, value in record.items(): + lines.append(f'{pfx}{key}: "{value}"') + pfx = " " + if not settings: + lines[-1] += " []" + lines.append("") + return "\n".join(lines) + + +def _write_channel_settings( + fpath: Union[Path, str], + include_defaults: bool = True, + include_sites: bool = True, + overwrite: bool = False, +) -> None: + with Path(fpath).open(mode="w" if overwrite else "x") as fp: + fp.write(_build_channel_yaml(include_defaults, include_sites)) + + +def _write_condarc_d_settings(overwrite: bool = False) -> None: + PREFIX_CONDARC_PATH.parent.mkdir(parents=True, exist_ok=True) + _write_channel_settings( + PREFIX_CONDARC_PATH, include_sites=False, overwrite=overwrite + ) + + +def _verify_channel_settings(filtered: bool = True) -> None: + from conda.base.context import context + + context.__init__() + expected = _build_channel_settings(include_sites=False) + _assert_settings(context, _dictify(expected), filtered=filtered) + + +if __name__ == "__main__": + import sys + + invalid = [ + x for x in sys.argv[1:] if x not in ("--install", "--verify", "--overwrite") + ] + if len(sys.argv) == 1 or invalid: + print( + f"Usage: {sys.argv[0]} [--install] [--verify] [--overwrite]", + file=sys.stderr, + ) + if invalid: + print(f"Invalid option(s): {' '.join(invalid)}", file=sys.stderr) + sys.exit(1) + if "--install" in sys.argv: + _write_condarc_d_settings(overwrite="--overwrite" in sys.argv) + if "--verify" in sys.argv: + _verify_channel_settings() diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/entrypoint.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/entrypoint.py new file mode 100644 index 0000000000000000000000000000000000000000..65545d3c844a5ba55b914c916189a1ddc81eecc1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/entrypoint.py @@ -0,0 +1,8 @@ +# The plugin entrypoints are loaded via this module as specified in pyproject.toml +# We do this to be very conservative and catch potential import errors without surfacing to users. +# Plugins were first introduced in conda=22.11.0 +# The ChannelAuthBase class was introduced in conda=23.7.0 +try: + from anaconda_auth._conda.plugins import * # noqa: F403 +except ImportError: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/plugins.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..73d0dc3854a9c1e8911958ee74e51794bda721ad --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/plugins.py @@ -0,0 +1,52 @@ +"""Definitions for conda plugins. + +This file should not be imported directly, but instead the parent package will +conditionally import it in case conda is not installed in the user's environment. + +""" + +from typing import Iterable +from typing import Optional + +from conda import plugins +from conda.plugins.types import CondaAuthHandler +from conda.plugins.types import CondaSubcommand + +from anaconda_auth._conda.auth_handler import AnacondaAuthHandler +from anaconda_auth._conda.conda_token import cli + +__all__ = ["conda_subcommands", "conda_auth_handlers"] + + +def _cli_wrapper(argv: Optional[list[str]] = None) -> int: # type: ignore + # If argv is empty tuple, we need to set it back to None + return cli(argv=argv or None) + + +@plugins.hookimpl +def conda_subcommands() -> Iterable[CondaSubcommand]: + """Defines subcommands into conda itself (not `anaconda` CLI).""" + yield CondaSubcommand( + name="token", + summary="Set repository access token and configure default_channels", + action=_cli_wrapper, # type: ignore + ) + + +@plugins.hookimpl +def conda_auth_handlers() -> Iterable[CondaAuthHandler]: + """Defines the auth handler that can be used for specific channels. + + The following shows an example for how to configure a specific channel inside .condarc: + + ```yaml + channel_settings: + - channel: https://repo.anaconda.cloud/* + auth: anaconda-auth + ``` + + """ + yield CondaAuthHandler( + name="anaconda-auth", + handler=AnacondaAuthHandler, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/repo_config.py b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/repo_config.py new file mode 100644 index 0000000000000000000000000000000000000000..158fcc4e644155ef9bb328211c3f2a2446ad0c10 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/anaconda_auth/_conda/repo_config.py @@ -0,0 +1,549 @@ +""" +Configure Conda to use Anaconda Commercial Edition. +""" + +from __future__ import annotations + +import contextlib +import io +import json +import os +import sys +import warnings +from os.path import abspath +from os.path import expanduser +from os.path import join +from typing import Any +from urllib.parse import urljoin + +import conda +import conda.gateways.logging # noqa: F401 +from conda.base import context as context_module +from conda.cli import main as conda_main +from conda.exceptions import CondaKeyError +from conda.gateways.anaconda_client import read_binstar_tokens +from conda.gateways.anaconda_client import remove_binstar_token +from conda.gateways.anaconda_client import set_binstar_token +from conda.gateways.connection.session import CondaSession +from conda.models.channel import Channel +from packaging import version +from rich.prompt import Confirm + +from anaconda_auth._conda.conda_api import Commands +from anaconda_auth._conda.condarc import CondaRC +from anaconda_auth._conda.config import _build_channel_settings +from anaconda_cli_base import console + +CONDA_VERSION = version.parse(conda.__version__) + +REPO_URL = os.getenv("CONDA_TOKEN_REPO_URL", "https://repo.anaconda.cloud/repo/") +MAIN_CHANNEL = "main" +ACTIVE_CHANNELS = ["r", "msys2"] +ARCHIVE_CHANNELS = ["free", "mro-archive", "pro"] + +user_rc_path = abspath(expanduser("~/.condarc")) +escaped_user_rc_path = user_rc_path.replace("%", "%%") +escaped_sys_rc_path = abspath(join(sys.prefix, ".condarc")).replace("%", "%%") + + +def run_command(*args: Any, **kwargs: Any) -> int: + with warnings.catch_warnings(): + # Ignore PendingDeprecationWarning from any other plugins invoked when calling conda + warnings.simplefilter("ignore", PendingDeprecationWarning) + return conda_main(*args, **kwargs) + + +class CondaTokenError(RuntimeError): + pass + + +class CondaVersionWarning(UserWarning): + pass + + +def _get_condarc_args( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> list[str]: + """Construct conda CLI args related to condarc location.""" + config_args = [] + + if condarc_system: + config_args.append("--system") + elif condarc_env: + config_args.append("--env") + elif condarc_file: + config_args.append(f"--file={condarc_file}") + + return config_args + + +def can_restore_free_channel() -> bool: + # restore_free_channel was removed in conda 25.9.0 + return CONDA_VERSION >= version.parse("4.7.0") and CONDA_VERSION < version.parse( + "25.9.0" + ) + + +def clean_index() -> None: + """Runs conda clean -i. + + It is important to remove index cache when + changing the condarc to ensure that the downloaded + repodata is correct. + """ + run_command(Commands.CLEAN, "-i", "-y", "-q") + + +def validate_token(token: str, no_ssl_verify: bool = False) -> None: + """Checks that token can be used with the repository.""" + + # Force ssl_verify: false + if no_ssl_verify: + context_module.context.ssl_verify = False # type: ignore + + # Use CondaSession to be compatible with ssl_verify: truststore + # https://conda.io/projects/conda/en/latest/user-guide/configuration/settings.html#ssl-verify-ssl-verification + # Clear metaclass cache to create new session checking ssl_verify + if hasattr(CondaSession, "cache_clear"): + # not present in conda < January 2024 + CondaSession.cache_clear() + else: + # what cache_clear() does + try: + CondaSession._thread_local.sessions.clear() # type: ignore + except AttributeError: + # AttributeError: thread's session cache has not been initialized + pass + + session = CondaSession() + + # Ensure the index cache is cleaned first + clean_index() + + channel = Channel(urljoin(REPO_URL, "main/noarch/repodata.json")) + channel.token = token + token_url = str(channel.url(with_credentials=True)) + + r = session.head(token_url, verify=session.verify) + if r.status_code != 200: + raise CondaTokenError( + "The token could not be validated. Please check that you have typed it correctly." + ) + + +def configure_plugin(should_set_default_channels: bool = False) -> None: + """Configure the user's .condarc file with the anaconda-auth plugin. + + We install the auth-handler plugin by writing the "channel_settings" key and associate + all premium repo channels with this auth handler. + + """ + settings = _build_channel_settings(include_defaults=False) + if not settings: + return + condarc = CondaRC() + condarc.backup() + for s in settings: + condarc.update_channel_settings(s["channel"], s["auth"], username=None) + condarc.save() + + +def enable_extra_safety_checks( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Enable package signature verification. + + This will set extra_safety_checks: True and + signing_metadata_url_base in the CondaRC file. + """ + if CONDA_VERSION < version.parse("4.10.1"): + warnings.warn( + "You need upgrade to at least Conda version 4.10.1 to enable package signature verification.", + CondaVersionWarning, + ) + return + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + + safety_check_args = ["--set", "extra_safety_checks", "true"] + safety_check_args.extend(condarc_file_args) + run_command(Commands.CONFIG, *safety_check_args) + + metadata_url_args = ["--set", "signing_metadata_url_base", REPO_URL.rstrip("/")] + metadata_url_args.extend(condarc_file_args) + run_command(Commands.CONFIG, *metadata_url_args) + + +def disable_extra_safety_checks( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Disable package signature verification. + + This will set extra_safety_checks: false and remove + signing_metadata_url_base in the CondaRC file. + """ + + if CONDA_VERSION < version.parse("4.10.1"): + return + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + + safety_check_args = ["--set", "extra_safety_checks", "false"] + safety_check_args.extend(condarc_file_args) + try: + run_command(Commands.CONFIG, *safety_check_args) + except CondaKeyError: + pass + + metadata_url_args = ["--remove-key", "signing_metadata_url_base"] + metadata_url_args.extend(condarc_file_args) + try: + run_command(Commands.CONFIG, *metadata_url_args) + except CondaKeyError: + pass + + +def _set_add_anaconda_token( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Run conda config --set add_anaconda_token true. + + Setting this parameter to true ensures that the token + is used when making requests to the repository. + """ + config_args = ["--set", "add_anaconda_token", "true"] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + run_command(Commands.CONFIG, *config_args) + + +def _set_ssl_verify_false( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Run conda config --set ssl_verify false. + + Setting this parameter to false disables all + SSL verification for conda activities + """ + config_args = ["--set", "ssl_verify", "false"] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + run_command(Commands.CONFIG, *config_args) + + +def _unset_restore_free_channel( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Runs conda config --set restore_free_channel false. + + The free channel is provided by Commercial Edition as + and should be added directly.""" + config_args = ["--set", "restore_free_channel", "false"] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + run_command(Commands.CONFIG, *config_args, use_exception_handler=True) + + +def _set_channel( + channel: str, + prepend: bool = True, + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Adds a named Commercial Edition channel to default_channels.""" + channel_url = urljoin(REPO_URL, channel) + + config_args = [ + "--prepend" if prepend else "--append", + "default_channels", + channel_url, + ] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + run_command(Commands.CONFIG, *config_args) + + +def _get_from_condarc( + key: str, + default: Any = None, + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> Any: + """Retrieve the existing default_channels from the user's `.condarc` file. + + If the user does not have a "default_channels" section, an empty list is returned. + + """ + config_args = ["--get", key, "--json"] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + # Capture the JSON output from stdout + string_io = io.StringIO() + with contextlib.redirect_stdout(string_io): + run_command(Commands.CONFIG, *config_args) + + try: + result = json.loads(string_io.getvalue()) + except json.JSONDecodeError: + result = {} + + return result.get("get", {}).get(key, default) + + +def _get_default_channels( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> list[str]: + """Retrieve the existing default_channels from the user's `.condarc` file. + + If the user does not have a "default_channels" section, an empty list is returned. + + """ + return _get_from_condarc( + "default_channels", + default=[], + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + + +def _remove_default_channels( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, +) -> None: + """Runs conda config --remove-key default_channels + + It is best to remove the default_channels in case they + are not set at the default values before configuring + Commercial Edition. + """ + config_args = ["--remove-key", "default_channels"] + + condarc_file_args = _get_condarc_args( + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + config_args.extend(condarc_file_args) + + # We suppress a CondaKeyError below to prevent logging an internal conda error + # to the terminal. + err_io = io.StringIO() + with contextlib.redirect_stderr(err_io): + try: + run_command(Commands.CONFIG, *config_args) + except CondaKeyError: + pass + + err_string = err_io.getvalue() + if "CondaKeyError" not in err_string.strip(): + print(err_string, file=sys.stderr) + + +def _prompt_to_set_default_channels() -> bool: + """Prompt the user for whether they would like to set their default channels.""" + existing_default_channels = _get_default_channels() + if existing_default_channels: + console.print("Existing default channels found:") + for c in existing_default_channels: + console.print(f"- {c}") + console.print( + "This action will override the existing default_channels setting." + ) + else: + console.print("Prepared to set default channels in .condarc.") + + return Confirm.ask("Proceed?", default=False) + + +def configure_default_channels( + condarc_system: bool = False, + condarc_env: bool = False, + condarc_file: str | None = None, + include_archive_channels: list[str] | None = None, + force: bool = False, +) -> None: + """Configure the default_channels to utilize only Commercial Edition. + + + This function performs the following actions + 1. unset default_channels if it exists in the condarc + 2. unset restore_free_channel if it exists in the condarc + 3. Add the main, r, and msys2 channels to default_channels + 4. Optionally add any of the archive channels: + free, pro, mro, mro-archive + """ + console.print("Configuring your [cyan].condarc[/cyan] file") + + existing_default_channels = _get_default_channels() + + existing_default_channels_short_names = [ + c.removeprefix(REPO_URL) for c in existing_default_channels + ] + if set(existing_default_channels_short_names) == set( + [MAIN_CHANNEL] + ACTIVE_CHANNELS + ): + console.print("Default channels already configured, nothing to do.") + return + + if not (force or _prompt_to_set_default_channels()): + return + + _remove_default_channels(condarc_system, condarc_env, condarc_file) + + if can_restore_free_channel() and _get_from_condarc( + "restore_free_channel", + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ): + _unset_restore_free_channel(condarc_system, condarc_env, condarc_file) + + _set_channel( + MAIN_CHANNEL, + prepend=True, + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + + for c in ACTIVE_CHANNELS: + _set_channel( + c, + prepend=False, + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + + if include_archive_channels is None: + return + + for c in include_archive_channels: + if c in ARCHIVE_CHANNELS: + _set_channel( + c, + prepend=False, + condarc_system=condarc_system, + condarc_env=condarc_env, + condarc_file=condarc_file, + ) + else: + raise ValueError( + f"The archive channel {c} is not one of {', '.join(ARCHIVE_CHANNELS)}" + ) + + +def token_list() -> dict[str, str]: + """Return a dictionary of tokens for all configured repository urls. + + Note that this function will return tokens configured for non-Commercial Edition + urls.""" + return read_binstar_tokens() + + +def token_remove( + system: bool = False, env: bool = False, file: str | None = None +) -> None: + """Completely remove the Commercial Edition token and default_channels. + + This function performs three actions. + 1. Remove the token + 2. Remove the custom default_channels in the condarc + 3. Disable package signature verification + 4. Run conda clean -i + """ + remove_binstar_token(REPO_URL) + _remove_default_channels(system, env, file) + disable_extra_safety_checks(system, env, file) + clean_index() + + +def token_set( + token: str, + system: bool = False, + env: bool = False, + file: str | None = None, + include_archive_channels: list[str] | None = None, + no_ssl_verify: bool = False, + enable_signature_verification: bool = False, + force: bool = False, +) -> None: + """Set the Commercial Edition token and configure default_channels. + + + This function performs 4 actions. + 1. Remove previous Commercial Edition token if present. + 2. Add token. + 3. Configure default_channels in the condarc file. + 4. Optionally enable Conda package signature verification + 5. Run conda clean -i + """ + remove_binstar_token(REPO_URL) + + set_binstar_token(REPO_URL, token) + _set_add_anaconda_token(system, env, file) + + if no_ssl_verify: + _set_ssl_verify_false(system, env, file) + + if enable_signature_verification: + enable_extra_safety_checks(system, env, file) + + configure_default_channels(system, env, file, include_archive_channels, force=force) + clean_index() diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a53fb0e12c4de84240cb2b9aa82f4593f845faf Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fae1c4036c77dc6503d4ca3862792d6657823848 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/cli.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..43c97983ad87d5b25e7dfa435e0b3fcae4dcb5f2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/__pycache__/cli.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbb43b785db83b1639f8cb9c0b228ab10741eeb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""The "cpu" package permits to query and compare different +CPU microarchitectures. +""" +from .detect import brand_string, host +from .microarchitecture import ( + TARGETS, + InvalidCompilerVersion, + Microarchitecture, + UnsupportedMicroarchitecture, + generic_microarchitecture, + version_components, +) + +__all__ = [ + "brand_string", + "host", + "TARGETS", + "InvalidCompilerVersion", + "Microarchitecture", + "UnsupportedMicroarchitecture", + "generic_microarchitecture", + "version_components", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..60e19778e84b7a2afbabedb70f26e3a9d89c0b8e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/alias.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/alias.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..57cc7e324184e6e49e5add0880c086125f33c3a5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/alias.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/detect.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/detect.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6d4df6467c6afde601ea9044492567404096604b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/detect.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/microarchitecture.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/microarchitecture.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1cc238eae653e545fe46eb5b61ea5a282f21ac5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/microarchitecture.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/schema.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/schema.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cccf59fcc04da851ac272403a81884807c75c5e3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/__pycache__/schema.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py new file mode 100644 index 0000000000000000000000000000000000000000..783a67d3ea9563f05f23ab6cba45ffc7b261aff1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/alias.py @@ -0,0 +1,87 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Aliases for microarchitecture features.""" +from .schema import TARGETS_JSON, LazyDictionary + +_FEATURE_ALIAS_PREDICATE = {} + + +class FeatureAliasTest: + """A test that must be passed for a feature alias to succeed. + + Args: + rules (dict): dictionary of rules to be met. Each key must be a + valid alias predicate + """ + + # pylint: disable=too-few-public-methods + def __init__(self, rules): + self.rules = rules + self.predicates = [] + for name, args in rules.items(): + self.predicates.append(_FEATURE_ALIAS_PREDICATE[name](args)) + + def __call__(self, microarchitecture): + return all(feature_test(microarchitecture) for feature_test in self.predicates) + + +def _feature_aliases(): + """Returns the dictionary of all defined feature aliases.""" + json_data = TARGETS_JSON["feature_aliases"] + aliases = {} + for alias, rules in json_data.items(): + aliases[alias] = FeatureAliasTest(rules) + return aliases + + +FEATURE_ALIASES = LazyDictionary(_feature_aliases) + + +def alias_predicate(func): + """Decorator to register a predicate that can be used to evaluate + feature aliases. + """ + name = func.__name__ + + # Check we didn't register anything else with the same name + if name in _FEATURE_ALIAS_PREDICATE: + msg = f'the alias predicate "{name}" already exists' + raise KeyError(msg) + + _FEATURE_ALIAS_PREDICATE[name] = func + + return func + + +@alias_predicate +def reason(_): + """This predicate returns always True and it's there to allow writing + a documentation string in the JSON file to explain why an alias is needed. + """ + return lambda x: True + + +@alias_predicate +def any_of(list_of_features): + """Returns a predicate that is True if any of the feature in the + list is in the microarchitecture being tested, False otherwise. + """ + + def _impl(microarchitecture): + return any(x in microarchitecture for x in list_of_features) + + return _impl + + +@alias_predicate +def families(list_of_families): + """Returns a predicate that is True if the architecture family of + the microarchitecture being tested is in the list, False otherwise. + """ + + def _impl(microarchitecture): + return str(microarchitecture.family) in list_of_families + + return _impl diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py new file mode 100644 index 0000000000000000000000000000000000000000..f9f095f78a6c05fb42dbe21b0e2515e76fdcd5a7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/detect.py @@ -0,0 +1,459 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Detection of CPU microarchitectures""" +import collections +import os +import platform +import re +import struct +import subprocess +import warnings +from typing import Dict, List, Optional, Set, Tuple, Union + +from ..vendor.cpuid.cpuid import CPUID +from .microarchitecture import TARGETS, Microarchitecture, generic_microarchitecture +from .schema import CPUID_JSON, TARGETS_JSON + +#: Mapping from operating systems to chain of commands +#: to obtain a dictionary of raw info on the current cpu +INFO_FACTORY = collections.defaultdict(list) + +#: Mapping from micro-architecture families (x86_64, ppc64le, etc.) to +#: functions checking the compatibility of the host with a given target +COMPATIBILITY_CHECKS = {} + +# Constants for commonly used architectures +X86_64 = "x86_64" +AARCH64 = "aarch64" +PPC64LE = "ppc64le" +PPC64 = "ppc64" +RISCV64 = "riscv64" + + +def detection(operating_system: str): + """Decorator to mark functions that are meant to return partial information on the current cpu. + + Args: + operating_system: operating system where this function can be used. + """ + + def decorator(factory): + INFO_FACTORY[operating_system].append(factory) + return factory + + return decorator + + +def partial_uarch( + name: str = "", + vendor: str = "", + features: Optional[Set[str]] = None, + generation: int = 0, + cpu_part: str = "", +) -> Microarchitecture: + """Construct a partial microarchitecture, from information gathered during system scan.""" + return Microarchitecture( + name=name, + parents=[], + vendor=vendor, + features=features or set(), + compilers={}, + generation=generation, + cpu_part=cpu_part, + ) + + +@detection(operating_system="Linux") +def proc_cpuinfo() -> Microarchitecture: + """Returns a partial Microarchitecture, obtained from scanning ``/proc/cpuinfo``""" + data = {} + with open("/proc/cpuinfo") as file: # pylint: disable=unspecified-encoding + for line in file: + key, separator, value = line.partition(":") + + # If there's no separator and info was already populated + # according to what's written here: + # + # http://www.linfo.org/proc_cpuinfo.html + # + # we are on a blank line separating two cpus. Exit early as + # we want to read just the first entry in /proc/cpuinfo + if separator != ":" and data: + break + + data[key.strip()] = value.strip() + + architecture = _machine() + if architecture == X86_64: + return partial_uarch( + vendor=data.get("vendor_id", "generic"), features=_feature_set(data, key="flags") + ) + + if architecture == AARCH64: + return partial_uarch( + vendor=_canonicalize_aarch64_vendor(data), + features=_feature_set(data, key="Features"), + cpu_part=data.get("CPU part", ""), + ) + + if architecture in (PPC64LE, PPC64): + generation_match = re.search(r"POWER(\d+)", data.get("cpu", "")) + try: + generation = int(generation_match.group(1)) + except AttributeError: + # There might be no match under emulated environments. For instance + # emulating a ppc64le with QEMU and Docker still reports the host + # /proc/cpuinfo and not a Power + generation = 0 + return partial_uarch(generation=generation) + + if architecture == RISCV64: + if data.get("uarch") == "sifive,u74-mc": + data["uarch"] = "u74mc" + return partial_uarch(name=data.get("uarch", RISCV64)) + + return generic_microarchitecture(architecture) + + +class CpuidInfoCollector: + """Collects the information we need on the host CPU from cpuid""" + + # pylint: disable=too-few-public-methods + def __init__(self): + self.cpuid = CPUID() + + registers = self.cpuid.registers_for(**CPUID_JSON["vendor"]["input"]) + self.highest_basic_support = registers.eax + self.vendor = struct.pack("III", registers.ebx, registers.edx, registers.ecx).decode( + "utf-8" + ) + + registers = self.cpuid.registers_for(**CPUID_JSON["highest_extension_support"]["input"]) + self.highest_extension_support = registers.eax + + self.features = self._features() + + def _features(self): + result = set() + + def check_features(data): + registers = self.cpuid.registers_for(**data["input"]) + for feature_check in data["bits"]: + current = getattr(registers, feature_check["register"]) + if self._is_bit_set(current, feature_check["bit"]): + result.add(feature_check["name"]) + + for call_data in CPUID_JSON["flags"]: + if call_data["input"]["eax"] > self.highest_basic_support: + continue + check_features(call_data) + + for call_data in CPUID_JSON["extension-flags"]: + if call_data["input"]["eax"] > self.highest_extension_support: + continue + check_features(call_data) + + return result + + def _is_bit_set(self, register: int, bit: int) -> bool: + mask = 1 << bit + return register & mask > 0 + + def brand_string(self) -> Optional[str]: + """Returns the brand string, if available.""" + if self.highest_extension_support < 0x80000004: + return None + + r1 = self.cpuid.registers_for(eax=0x80000002, ecx=0) + r2 = self.cpuid.registers_for(eax=0x80000003, ecx=0) + r3 = self.cpuid.registers_for(eax=0x80000004, ecx=0) + result = struct.pack( + "IIIIIIIIIIII", + r1.eax, + r1.ebx, + r1.ecx, + r1.edx, + r2.eax, + r2.ebx, + r2.ecx, + r2.edx, + r3.eax, + r3.ebx, + r3.ecx, + r3.edx, + ).decode("utf-8") + return result.strip("\x00") + + +@detection(operating_system="Windows") +def cpuid_info(): + """Returns a partial Microarchitecture, obtained from running the cpuid instruction""" + architecture = _machine() + if architecture == X86_64: + data = CpuidInfoCollector() + return partial_uarch(vendor=data.vendor, features=data.features) + + return generic_microarchitecture(architecture) + + +def _check_output(args, env): + with subprocess.Popen(args, stdout=subprocess.PIPE, env=env) as proc: + output = proc.communicate()[0] + return str(output.decode("utf-8")) + + +WINDOWS_MAPPING = { + "AMD64": X86_64, + "ARM64": AARCH64, +} + + +def _machine(): + """Return the machine architecture we are on""" + operating_system = platform.system() + + # If we are not on Darwin or Windows, trust what Python tells us + if operating_system not in ("Darwin", "Windows"): + return platform.machine() + + # Normalize windows specific names + if operating_system == "Windows": + platform_machine = platform.machine() + return WINDOWS_MAPPING.get(platform_machine, platform_machine) + + # On Darwin it might happen that we are on M1, but using an interpreter + # built for x86_64. In that case "platform.machine() == 'x86_64'", so we + # need to fix that. + # + # See: https://bugs.python.org/issue42704 + output = _check_output( + ["sysctl", "-n", "machdep.cpu.brand_string"], env=_ensure_bin_usrbin_in_path() + ).strip() + + if "Apple" in output: + # Note that a native Python interpreter on Apple M1 would return + # "arm64" instead of "aarch64". Here we normalize to the latter. + return AARCH64 + + return X86_64 + + +@detection(operating_system="Darwin") +def sysctl_info() -> Microarchitecture: + """Returns a raw info dictionary parsing the output of sysctl.""" + child_environment = _ensure_bin_usrbin_in_path() + + def sysctl(*args: str) -> str: + return _check_output(["sysctl"] + list(args), env=child_environment).strip() + + if _machine() == X86_64: + features = ( + f'{sysctl("-n", "machdep.cpu.features").lower()} ' + f'{sysctl("-n", "machdep.cpu.leaf7_features").lower()}' + ) + features = set(features.split()) + + # Flags detected on Darwin turned to their linux counterpart + for darwin_flag, linux_flag in TARGETS_JSON["conversions"]["darwin_flags"].items(): + if darwin_flag in features: + features.update(linux_flag.split()) + + return partial_uarch(vendor=sysctl("-n", "machdep.cpu.vendor"), features=features) + + model = "unknown" + model_str = sysctl("-n", "machdep.cpu.brand_string").lower() + if "m2" in model_str: + model = "m2" + elif "m1" in model_str: + model = "m1" + elif "apple" in model_str: + model = "m1" + + return partial_uarch(name=model, vendor="Apple") + + +def _ensure_bin_usrbin_in_path(): + # Make sure that /sbin and /usr/sbin are in PATH as sysctl is usually found there + child_environment = dict(os.environ.items()) + search_paths = child_environment.get("PATH", "").split(os.pathsep) + for additional_path in ("/sbin", "/usr/sbin"): + if additional_path not in search_paths: + search_paths.append(additional_path) + child_environment["PATH"] = os.pathsep.join(search_paths) + return child_environment + + +def _canonicalize_aarch64_vendor(data: Dict[str, str]) -> str: + """Adjust the vendor field to make it human-readable""" + if "CPU implementer" not in data: + return "generic" + + # Mapping numeric codes to vendor (ARM). This list is a merge from + # different sources: + # + # https://github.com/karelzak/util-linux/blob/master/sys-utils/lscpu-arm.c + # https://developer.arm.com/docs/ddi0487/latest/arm-architecture-reference-manual-armv8-for-armv8-a-architecture-profile + # https://github.com/gcc-mirror/gcc/blob/master/gcc/config/aarch64/aarch64-cores.def + # https://patchwork.kernel.org/patch/10524949/ + arm_vendors = TARGETS_JSON["conversions"]["arm_vendors"] + arm_code = data["CPU implementer"] + return arm_vendors.get(arm_code, arm_code) + + +def _feature_set(data: Dict[str, str], key: str) -> Set[str]: + return set(data.get(key, "").split()) + + +def detected_info() -> Microarchitecture: + """Returns a partial Microarchitecture with information on the CPU of the current host. + + This function calls all the viable factories one after the other until there's one that is + able to produce the requested information. Falls-back to a generic microarchitecture, if none + of the calls succeed. + """ + # pylint: disable=broad-except + for factory in INFO_FACTORY[platform.system()]: + try: + return factory() + except Exception as exc: + warnings.warn(str(exc)) + + return generic_microarchitecture(_machine()) + + +def compatible_microarchitectures(info: Microarchitecture) -> List[Microarchitecture]: + """Returns an unordered list of known micro-architectures that are compatible with the + partial Microarchitecture passed as input. + """ + architecture_family = _machine() + # If a tester is not registered, assume no known target is compatible with the host + tester = COMPATIBILITY_CHECKS.get(architecture_family, lambda x, y: False) + return [x for x in TARGETS.values() if tester(info, x)] or [ + generic_microarchitecture(architecture_family) + ] + + +def host(): + """Detects the host micro-architecture and returns it.""" + # Retrieve information on the host's cpu + info = detected_info() + + # Get a list of possible candidates for this micro-architecture + candidates = compatible_microarchitectures(info) + + # Sorting criteria for candidates + def sorting_fn(item): + return len(item.ancestors), len(item.features) + + # Get the best generic micro-architecture + generic_candidates = [c for c in candidates if c.vendor == "generic"] + best_generic = max(generic_candidates, key=sorting_fn) + + # Relevant for AArch64. Filter on "cpu_part" if we have any match + if info.cpu_part != "" and any(c for c in candidates if info.cpu_part == c.cpu_part): + candidates = [c for c in candidates if info.cpu_part == c.cpu_part] + + # Filter the candidates to be descendant of the best generic candidate. + # This is to avoid that the lack of a niche feature that can be disabled + # from e.g. BIOS prevents detection of a reasonably performant architecture + candidates = [c for c in candidates if c > best_generic] + + # If we don't have candidates, return the best generic micro-architecture + if not candidates: + return best_generic + + # Reverse sort of the depth for the inheritance tree among only targets we + # can use. This gets the newest target we satisfy. + return max(candidates, key=sorting_fn) + + +def compatibility_check(architecture_family: Union[str, Tuple[str, ...]]): + """Decorator to register a function as a proper compatibility check. + + A compatibility check function takes a partial Microarchitecture object as a first argument, + and an arbitrary target Microarchitecture as the second argument. It returns True if the + target is compatible with first argument, False otherwise. + + Args: + architecture_family: architecture family for which this test can be used + """ + # Turn the argument into something iterable + if isinstance(architecture_family, str): + architecture_family = (architecture_family,) + + def decorator(func): + COMPATIBILITY_CHECKS.update({family: func for family in architecture_family}) + return func + + return decorator + + +@compatibility_check(architecture_family=(PPC64LE, PPC64)) +def compatibility_check_for_power(info, target): + """Compatibility check for PPC64 and PPC64LE architectures.""" + # We can use a target if it descends from our machine type and our + # generation (9 for POWER9, etc) is at least its generation. + arch_root = TARGETS[_machine()] + return ( + target == arch_root or arch_root in target.ancestors + ) and target.generation <= info.generation + + +@compatibility_check(architecture_family=X86_64) +def compatibility_check_for_x86_64(info, target): + """Compatibility check for x86_64 architectures.""" + # We can use a target if it descends from our machine type, is from our + # vendor, and we have all of its features + arch_root = TARGETS[X86_64] + return ( + (target == arch_root or arch_root in target.ancestors) + and target.vendor in (info.vendor, "generic") + and target.features.issubset(info.features) + ) + + +@compatibility_check(architecture_family=AARCH64) +def compatibility_check_for_aarch64(info, target): + """Compatibility check for AARCH64 architectures.""" + # At the moment, it's not clear how to detect compatibility with + # a specific version of the architecture + if target.vendor == "generic" and target.name != AARCH64: + return False + + arch_root = TARGETS[AARCH64] + arch_root_and_vendor = arch_root == target.family and target.vendor in ( + info.vendor, + "generic", + ) + + # On macOS it seems impossible to get all the CPU features + # with syctl info, but for ARM we can get the exact model + if platform.system() == "Darwin": + model = TARGETS[info.name] + return arch_root_and_vendor and (target == model or target in model.ancestors) + + return arch_root_and_vendor and target.features.issubset(info.features) + + +@compatibility_check(architecture_family=RISCV64) +def compatibility_check_for_riscv64(info, target): + """Compatibility check for riscv64 architectures.""" + arch_root = TARGETS[RISCV64] + return (target == arch_root or arch_root in target.ancestors) and ( + target.name == info.name or target.vendor == "generic" + ) + + +def brand_string() -> Optional[str]: + """Returns the brand string of the host, if detected, or None.""" + if platform.system() == "Darwin": + return _check_output( + ["sysctl", "-n", "machdep.cpu.brand_string"], env=_ensure_bin_usrbin_in_path() + ).strip() + + if host().family == X86_64: + return CpuidInfoCollector().brand_string() + + return None diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py new file mode 100644 index 0000000000000000000000000000000000000000..bb85b9f37c0966b3a7eb30b0a811d4db83a74eed --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/microarchitecture.py @@ -0,0 +1,416 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Types and functions to manage information on CPU microarchitectures.""" +import functools +import platform +import re +import warnings + +import archspec +import archspec.cpu.alias +import archspec.cpu.schema + +from .alias import FEATURE_ALIASES +from .schema import LazyDictionary + + +def coerce_target_names(func): + """Decorator that automatically converts a known target name to a proper + Microarchitecture object. + """ + + @functools.wraps(func) + def _impl(self, other): + if isinstance(other, str): + if other not in TARGETS: + msg = '"{0}" is not a valid target name' + raise ValueError(msg.format(other)) + other = TARGETS[other] + + return func(self, other) + + return _impl + + +class Microarchitecture: + """Represents a specific CPU micro-architecture. + + Args: + name (str): name of the micro-architecture (e.g. skylake). + parents (list): list of parents micro-architectures, if any. + Parenthood is considered by cpu features and not + chronologically. As such each micro-architecture is + compatible with its ancestors. For example "skylake", + which has "broadwell" as a parent, supports running binaries + optimized for "broadwell". + vendor (str): vendor of the micro-architecture + features (set of str): supported CPU flags. Note that the semantic + of the flags in this field might vary among architectures, if + at all present. For instance x86_64 processors will list all + the flags supported by a given CPU while Arm processors will + list instead only the flags that have been added on top of the + base model for the current micro-architecture. + compilers (dict): compiler support to generate tuned code for this + micro-architecture. This dictionary has as keys names of + supported compilers, while values are list of dictionaries + with fields: + + * name: name of the micro-architecture according to the + compiler. This is the name passed to the ``-march`` option + or similar. Not needed if the name is the same as that + passed in as argument above. + * versions: versions that support this micro-architecture. + + generation (int): generation of the micro-architecture, if relevant. + cpu_part (str): cpu part of the architecture, if relevant. + """ + + # pylint: disable=too-many-arguments,too-many-instance-attributes + #: Aliases for micro-architecture's features + feature_aliases = FEATURE_ALIASES + + def __init__(self, name, parents, vendor, features, compilers, generation=0, cpu_part=""): + self.name = name + self.parents = parents + self.vendor = vendor + self.features = features + self.compilers = compilers + # Only relevant for PowerPC + self.generation = generation + # Only relevant for AArch64 + self.cpu_part = cpu_part + + # Cache the "ancestor" computation + self._ancestors = None + # Cache the "generic" computation + self._generic = None + # Cache the "family" computation + self._family = None + + @property + def ancestors(self): + """All the ancestors of this microarchitecture.""" + if self._ancestors is None: + value = self.parents[:] + for parent in self.parents: + value.extend(a for a in parent.ancestors if a not in value) + self._ancestors = value + return self._ancestors + + def _to_set(self): + """Returns a set of the nodes in this microarchitecture DAG.""" + # This function is used to implement subset semantics with + # comparison operators + return set([str(self)] + [str(x) for x in self.ancestors]) + + @coerce_target_names + def __eq__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return ( + self.name == other.name + and self.vendor == other.vendor + and self.features == other.features + and self.parents == other.parents # avoid ancestors here + and self.compilers == other.compilers + and self.generation == other.generation + and self.cpu_part == other.cpu_part + ) + + def __hash__(self): + return hash(self.name) + + @coerce_target_names + def __ne__(self, other): + return not self == other + + @coerce_target_names + def __lt__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return self._to_set() < other._to_set() + + @coerce_target_names + def __le__(self, other): + return (self == other) or (self < other) + + @coerce_target_names + def __gt__(self, other): + if not isinstance(other, Microarchitecture): + return NotImplemented + + return self._to_set() > other._to_set() + + @coerce_target_names + def __ge__(self, other): + return (self == other) or (self > other) + + def __repr__(self): + cls_name = self.__class__.__name__ + fmt = ( + cls_name + "({0.name!r}, {0.parents!r}, {0.vendor!r}, " + "{0.features!r}, {0.compilers!r}, generation={0.generation!r}, " + "cpu_part={0.cpu_part!r})" + ) + return fmt.format(self) + + def __str__(self): + return self.name + + def __contains__(self, feature): + # Feature must be of a string type, so be defensive about that + if not isinstance(feature, str): + msg = "only objects of string types are accepted [got {0}]" + raise TypeError(msg.format(str(type(feature)))) + + # Here we look first in the raw features, and fall-back to + # feature aliases if not match was found + if feature in self.features: + return True + + # Check if the alias is defined, if not it will return False + match_alias = Microarchitecture.feature_aliases.get(feature, lambda x: False) + return match_alias(self) + + @property + def family(self): + """Returns the architecture family a given target belongs to""" + if self._family is None: + roots = [x for x in [self] + self.ancestors if not x.ancestors] + msg = "a target is expected to belong to just one architecture family" + msg += f"[found {', '.join(str(x) for x in roots)}]" + assert len(roots) == 1, msg + self._family = roots.pop() + + return self._family + + @property + def generic(self): + """Returns the best generic architecture that is compatible with self""" + if self._generic is None: + generics = [x for x in [self] + self.ancestors if x.vendor == "generic"] + self._generic = max(generics, key=lambda x: len(x.ancestors)) + return self._generic + + def to_dict(self): + """Returns a dictionary representation of this object.""" + return { + "name": str(self.name), + "vendor": str(self.vendor), + "features": sorted(str(x) for x in self.features), + "generation": self.generation, + "parents": [str(x) for x in self.parents], + "compilers": self.compilers, + "cpupart": self.cpu_part, + } + + @staticmethod + def from_dict(data) -> "Microarchitecture": + """Construct a microarchitecture from a dictionary representation.""" + return Microarchitecture( + name=data["name"], + parents=[TARGETS[x] for x in data["parents"]], + vendor=data["vendor"], + features=set(data["features"]), + compilers=data.get("compilers", {}), + generation=data.get("generation", 0), + cpu_part=data.get("cpupart", ""), + ) + + def optimization_flags(self, compiler, version): + """Returns a string containing the optimization flags that needs + to be used to produce code optimized for this micro-architecture. + + The version is expected to be a string of dot separated digits. + + If there is no information on the compiler passed as argument the + function returns an empty string. If it is known that the compiler + version we want to use does not support this architecture the function + raises an exception. + + Args: + compiler (str): name of the compiler to be used + version (str): version of the compiler to be used + + Raises: + UnsupportedMicroarchitecture: if the requested compiler does not support + this micro-architecture. + ValueError: if the version doesn't match the expected format + """ + # If we don't have information on compiler at all return an empty string + if compiler not in self.family.compilers: + return "" + + # If we have information but it stops before this + # microarchitecture, fall back to the best known target + if compiler not in self.compilers: + best_target = [x for x in self.ancestors if compiler in x.compilers][0] + msg = ( + "'{0}' compiler is known to optimize up to the '{1}'" + " microarchitecture in the '{2}' architecture family" + ) + msg = msg.format(compiler, best_target, best_target.family) + raise UnsupportedMicroarchitecture(msg) + + # Check that the version matches the expected format + if not re.match(r"^(?:\d+\.)*\d+$", version): + msg = ( + "invalid format for the compiler version argument. " + "Only dot separated digits are allowed." + ) + raise InvalidCompilerVersion(msg) + + # If we have information on this compiler we need to check the + # version being used + compiler_info = self.compilers[compiler] + + def satisfies_constraint(entry, version): + min_version, max_version = entry["versions"].split(":") + + # Check version suffixes + min_version, _ = version_components(min_version) + max_version, _ = version_components(max_version) + version, _ = version_components(version) + + # Assume compiler versions fit into semver + def tuplify(ver): + return tuple(int(y) for y in ver.split(".")) + + version = tuplify(version) + if min_version: + min_version = tuplify(min_version) + if min_version > version: + return False + + if max_version: + max_version = tuplify(max_version) + if max_version < version: + return False + + return True + + for compiler_entry in compiler_info: + if satisfies_constraint(compiler_entry, version): + flags_fmt = compiler_entry["flags"] + # If there's no field name, use the name of the + # micro-architecture + compiler_entry.setdefault("name", self.name) + + # Check if we need to emit a warning + warning_message = compiler_entry.get("warnings", None) + if warning_message: + warnings.warn(warning_message) + + flags = flags_fmt.format(**compiler_entry) + return flags + + msg = "cannot produce optimized binary for micro-architecture '{0}' with {1}@{2}" + if compiler_info: + versions = [x["versions"] for x in compiler_info] + msg += f' [supported compiler versions are {", ".join(versions)}]' + else: + msg += " [no supported compiler versions]" + msg = msg.format(self.name, compiler, version) + raise UnsupportedMicroarchitecture(msg) + + +def generic_microarchitecture(name): + """Returns a generic micro-architecture with no vendor and no features. + + Args: + name (str): name of the micro-architecture + """ + return Microarchitecture(name, parents=[], vendor="generic", features=set(), compilers={}) + + +def version_components(version): + """Decomposes the version passed as input in version number and + suffix and returns them. + + If the version number or the suffix are not present, an empty + string is returned. + + Args: + version (str): version to be decomposed into its components + """ + match = re.match(r"([\d.]*)(-?)(.*)", str(version)) + if not match: + return "", "" + + version_number = match.group(1) + suffix = match.group(3) + + return version_number, suffix + + +def _known_microarchitectures(): + """Returns a dictionary of the known micro-architectures. If the + current host platform is unknown adds it too as a generic target. + """ + + def fill_target_from_dict(name, data, targets): + """Recursively fills targets by adding the micro-architecture + passed as argument and all its ancestors. + + Args: + name (str): micro-architecture to be added to targets. + data (dict): raw data loaded from JSON. + targets (dict): dictionary that maps micro-architecture names + to ``Microarchitecture`` objects + """ + values = data[name] + + # Get direct parents of target + parent_names = values["from"] + for parent in parent_names: + # Recursively fill parents so they exist before we add them + if parent in targets: + continue + fill_target_from_dict(parent, data, targets) + parents = [targets.get(parent) for parent in parent_names] + + vendor = values["vendor"] + features = set(values["features"]) + compilers = values.get("compilers", {}) + generation = values.get("generation", 0) + cpu_part = values.get("cpupart", "") + + targets[name] = Microarchitecture( + name, parents, vendor, features, compilers, generation=generation, cpu_part=cpu_part + ) + + known_targets = {} + data = archspec.cpu.schema.TARGETS_JSON["microarchitectures"] + for name in data: + if name in known_targets: + # name was already brought in as ancestor to a target + continue + fill_target_from_dict(name, data, known_targets) + + # Add the host platform if not present + host_platform = platform.machine() + known_targets.setdefault(host_platform, generic_microarchitecture(host_platform)) + + return known_targets + + +#: Dictionary of known micro-architectures +TARGETS = LazyDictionary(_known_microarchitectures) + + +class ArchspecError(Exception): + """Base class for errors within archspec""" + + +class UnsupportedMicroarchitecture(ArchspecError, ValueError): + """Raised if a compiler version does not support optimization for a given + micro-architecture. + """ + + +class InvalidCompilerVersion(ArchspecError, ValueError): + """Raised when an invalid format is used for compiler versions in archspec.""" diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..0ffc2231650b6952d3b9ad2fe6674632100d6607 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/cpu/schema.py @@ -0,0 +1,112 @@ +# Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +# Archspec Project Developers. See the top-level COPYRIGHT file for details. +# +# SPDX-License-Identifier: (Apache-2.0 OR MIT) +"""Global objects with the content of the microarchitecture +JSON file and its schema +""" +import collections.abc +import json +import os +import pathlib +from typing import Tuple + + +class LazyDictionary(collections.abc.MutableMapping): + """Lazy dictionary that gets constructed on first access to any object key + + Args: + factory (callable): factory function to construct the dictionary + """ + + def __init__(self, factory, *args, **kwargs): + self.factory = factory + self.args = args + self.kwargs = kwargs + self._data = None + + @property + def data(self): + """Returns the lazily constructed dictionary""" + if self._data is None: + self._data = self.factory(*self.args, **self.kwargs) + return self._data + + def __getitem__(self, key): + return self.data[key] + + def __setitem__(self, key, value): + self.data[key] = value + + def __delitem__(self, key): + del self.data[key] + + def __iter__(self): + return iter(self.data) + + def __len__(self): + return len(self.data) + + +#: Environment variable that might point to a directory with a user defined JSON file +DIR_FROM_ENVIRONMENT = "ARCHSPEC_CPU_DIR" + +#: Environment variable that might point to a directory with extensions to JSON files +EXTENSION_DIR_FROM_ENVIRONMENT = "ARCHSPEC_EXTENSION_CPU_DIR" + + +def _json_file(filename: str, allow_custom: bool = False) -> Tuple[pathlib.Path, pathlib.Path]: + """Given a filename, returns the absolute path for the main JSON file, and an + optional absolute path for an extension JSON file. + + Args: + filename: filename for the JSON file + allow_custom: if True, allows overriding the location where the file resides + """ + json_dir = pathlib.Path(__file__).parent / ".." / "json" / "cpu" + if allow_custom and DIR_FROM_ENVIRONMENT in os.environ: + json_dir = pathlib.Path(os.environ[DIR_FROM_ENVIRONMENT]) + json_dir = json_dir.absolute() + json_file = json_dir / filename + + extension_file = None + if allow_custom and EXTENSION_DIR_FROM_ENVIRONMENT in os.environ: + extension_dir = pathlib.Path(os.environ[EXTENSION_DIR_FROM_ENVIRONMENT]) + extension_dir.absolute() + extension_file = extension_dir / filename + + return json_file, extension_file + + +def _load(json_file: pathlib.Path, extension_file: pathlib.Path): + with open(json_file, "r", encoding="utf-8") as file: + data = json.load(file) + + if not extension_file or not extension_file.exists(): + return data + + with open(extension_file, "r", encoding="utf-8") as file: + extension_data = json.load(file) + + top_level_sections = list(data.keys()) + for key in top_level_sections: + if key not in extension_data: + continue + + data[key].update(extension_data[key]) + + return data + + +#: In memory representation of the data in microarchitectures.json, +#: loaded on first access +TARGETS_JSON = LazyDictionary(_load, *_json_file("microarchitectures.json", allow_custom=True)) + +#: JSON schema for microarchitectures.json, loaded on first access +TARGETS_JSON_SCHEMA = LazyDictionary(_load, *_json_file("microarchitectures_schema.json")) + +#: Information on how to call 'cpuid' to get information on the HOST CPU +CPUID_JSON = LazyDictionary(_load, *_json_file("cpuid.json", allow_custom=True)) + +#: JSON schema for cpuid.json, loaded on first access +CPUID_JSON_SCHEMA = LazyDictionary(_load, *_json_file("cpuid_schema.json")) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT b/data/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT new file mode 100644 index 0000000000000000000000000000000000000000..4164e98de77169c98f258c4ac8eff4daf9f78f4e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/COPYRIGHT @@ -0,0 +1,22 @@ +Intellectual Property Notice +------------------------------ + +Archspec is licensed under the Apache License, Version 2.0 (LICENSE-APACHE +or http://www.apache.org/licenses/LICENSE-2.0) or the MIT license, +(LICENSE-MIT or http://opensource.org/licenses/MIT), at your option. + +Copyrights and patents in the Archspec project are retained by contributors. +No copyright assignment is required to contribute to Archspec. + + +SPDX usage +------------ + +Individual files contain SPDX tags instead of the full license text. +This enables machine processing of license information based on the SPDX +License Identifiers that are available here: https://spdx.org/licenses/ + +Files that are dual-licensed as Apache-2.0 OR MIT contain the following +text in the license header: + + SPDX-License-Identifier: (Apache-2.0 OR MIT) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE b/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE new file mode 100644 index 0000000000000000000000000000000000000000..d645695673349e3947e8e5ae42332d0ac3164cd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-APACHE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT b/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT new file mode 100644 index 0000000000000000000000000000000000000000..03be635ad5df4567a85180c7a03a54ee96e1ee98 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/LICENSE-MIT @@ -0,0 +1,20 @@ +Copyright 2019-2020 Lawrence Livermore National Security, LLC and other +Archspec Project Developers. See the top-level COPYRIGHT file for details. + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the "Software"), +to deal in the Software without restriction, including without limitation +the rights to use, copy, modify, merge, publish, distribute, sublicense, +and/or sell copies of the Software, and to permit persons to whom the +Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE b/data/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..3737d5a86ddc20bfd04ce225fff2d34407df06f9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/NOTICE @@ -0,0 +1,21 @@ +This work was produced under the auspices of the U.S. Department of +Energy by Lawrence Livermore National Laboratory under Contract +DE-AC52-07NA27344. + +This work was prepared as an account of work sponsored by an agency of +the United States Government. Neither the United States Government nor +Lawrence Livermore National Security, LLC, nor any of their employees +makes any warranty, expressed or implied, or assumes any legal liability +or responsibility for the accuracy, completeness, or usefulness of any +information, apparatus, product, or process disclosed, or represents that +its use would not infringe privately owned rights. + +Reference herein to any specific commercial product, process, or service +by trade name, trademark, manufacturer, or otherwise does not necessarily +constitute or imply its endorsement, recommendation, or favoring by the +United States Government or Lawrence Livermore National Security, LLC. + +The views and opinions of authors expressed herein do not necessarily +state or reflect those of the United States Government or Lawrence +Livermore National Security, LLC, and shall not be used for advertising +or product endorsement purposes. diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/README.md b/data/miniconda3/lib/python3.13/site-packages/archspec/json/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78c424a86fa348b1b48001b649df8530fa3da2ac --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/README.md @@ -0,0 +1,36 @@ +[![](https://github.com/archspec/archspec-json/workflows/JSON%20Validation/badge.svg)](https://github.com/archspec/archspec-json/actions) + +# Archspec-json + +The [archspec-json](https://github.com/archspec/archspec-json) repository is part of the +[Archspec](https://github.com/archspec) project. It contains data on various architectural +aspects of a platform stored in JSON format and is meant to be used as a base to develop +language specific APIs. + +Currently the repository contains the following JSON files: +```console +cpu/ +├── cpuid.json # Contains information on CPUID calls to retrieve vendor and features on x86_64 +├── cpuid_schema.json # Schema for the file above +├── microarchitectures.json # Contains information on CPU microarchitectures +└── microarchitectures_schema.json # Schema for the file above + ``` + + +## License + +Archspec is distributed under the terms of both the MIT license and the +Apache License (Version 2.0). Users may choose either license, at their +option. + +All new contributions must be made under both the MIT and Apache-2.0 +licenses. + +See [LICENSE-MIT](https://github.com/archspec/archspec-json/blob/master/LICENSE-MIT), +[LICENSE-APACHE](https://github.com/archspec/archspec-json/blob/master/LICENSE-APACHE), +[COPYRIGHT](https://github.com/archspec/archspec-json/blob/master/COPYRIGHT), and +[NOTICE](https://github.com/archspec/archspec-json/blob/master/NOTICE) for details. + +SPDX-License-Identifier: (Apache-2.0 OR MIT) + +LLNL-CODE-811653 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json new file mode 100644 index 0000000000000000000000000000000000000000..594e435383ad50c0cd6f71f965b27b54343f502a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid.json @@ -0,0 +1,1050 @@ +{ + "vendor": { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0:_Highest_Function_Parameter_and_Manufacturer_ID", + "input": { + "eax": 0, + "ecx": 0 + } + }, + "highest_extension_support": { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=80000000h:_Get_Highest_Extended_Function_Implemented", + "input": { + "eax": 2147483648, + "ecx": 0 + } + }, + "flags": [ + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=1:_Processor_Info_and_Feature_Bits", + "input": { + "eax": 1, + "ecx": 0 + }, + "bits": [ + { + "name": "fpu", + "register": "edx", + "bit": 0 + }, + { + "name": "vme", + "register": "edx", + "bit": 1 + }, + { + "name": "de", + "register": "edx", + "bit": 2 + }, + { + "name": "pse", + "register": "edx", + "bit": 3 + }, + { + "name": "tsc", + "register": "edx", + "bit": 4 + }, + { + "name": "msr", + "register": "edx", + "bit": 5 + }, + { + "name": "pae", + "register": "edx", + "bit": 6 + }, + { + "name": "mce", + "register": "edx", + "bit": 7 + }, + { + "name": "cx8", + "register": "edx", + "bit": 8 + }, + { + "name": "apic", + "register": "edx", + "bit": 9 + }, + { + "name": "sep", + "register": "edx", + "bit": 11 + }, + { + "name": "mtrr", + "register": "edx", + "bit": 12 + }, + { + "name": "pge", + "register": "edx", + "bit": 13 + }, + { + "name": "mca", + "register": "edx", + "bit": 14 + }, + { + "name": "cmov", + "register": "edx", + "bit": 15 + }, + { + "name": "pat", + "register": "edx", + "bit": 16 + }, + { + "name": "pse36", + "register": "edx", + "bit": 17 + }, + { + "name": "pn", + "register": "edx", + "bit": 18 + }, + { + "name": "clflush", + "register": "edx", + "bit": 19 + }, + { + "name": "dts", + "register": "edx", + "bit": 21 + }, + { + "name": "acpi", + "register": "edx", + "bit": 22 + }, + { + "name": "mmx", + "register": "edx", + "bit": 23 + }, + { + "name": "fxsr", + "register": "edx", + "bit": 24 + }, + { + "name": "sse", + "register": "edx", + "bit": 25 + }, + { + "name": "sse2", + "register": "edx", + "bit": 26 + }, + { + "name": "ss", + "register": "edx", + "bit": 27 + }, + { + "name": "ht", + "register": "edx", + "bit": 28 + }, + { + "name": "tm", + "register": "edx", + "bit": 29 + }, + { + "name": "ia64", + "register": "edx", + "bit": 30 + }, + { + "name": "pbe", + "register": "edx", + "bit": 31 + }, + { + "name": "pni", + "register": "ecx", + "bit": 0 + }, + { + "name": "pclmulqdq", + "register": "ecx", + "bit": 1 + }, + { + "name": "dtes64", + "register": "ecx", + "bit": 2 + }, + { + "name": "monitor", + "register": "ecx", + "bit": 3 + }, + { + "name": "ds_cpl", + "register": "ecx", + "bit": 4 + }, + { + "name": "vmx", + "register": "ecx", + "bit": 5 + }, + { + "name": "smx", + "register": "ecx", + "bit": 6 + }, + { + "name": "est", + "register": "ecx", + "bit": 7 + }, + { + "name": "tm2", + "register": "ecx", + "bit": 8 + }, + { + "name": "ssse3", + "register": "ecx", + "bit": 9 + }, + { + "name": "cid", + "register": "ecx", + "bit": 10 + }, + { + "name": "fma", + "register": "ecx", + "bit": 12 + }, + { + "name": "cx16", + "register": "ecx", + "bit": 13 + }, + { + "name": "xtpr", + "register": "ecx", + "bit": 14 + }, + { + "name": "pdcm", + "register": "ecx", + "bit": 15 + }, + { + "name": "pcid", + "register": "ecx", + "bit": 17 + }, + { + "name": "dca", + "register": "ecx", + "bit": 18 + }, + { + "name": "sse4_1", + "register": "ecx", + "bit": 19 + }, + { + "name": "sse4_2", + "register": "ecx", + "bit": 20 + }, + { + "name": "x2apic", + "register": "ecx", + "bit": 21 + }, + { + "name": "movbe", + "register": "ecx", + "bit": 22 + }, + { + "name": "popcnt", + "register": "ecx", + "bit": 23 + }, + { + "name": "tscdeadline", + "register": "ecx", + "bit": 24 + }, + { + "name": "aes", + "register": "ecx", + "bit": 25 + }, + { + "name": "xsave", + "register": "ecx", + "bit": 26 + }, + { + "name": "osxsave", + "register": "ecx", + "bit": 27 + }, + { + "name": "avx", + "register": "ecx", + "bit": 28 + }, + { + "name": "f16c", + "register": "ecx", + "bit": 29 + }, + { + "name": "rdrand", + "register": "ecx", + "bit": 30 + }, + { + "name": "hypervisor", + "register": "ecx", + "bit": 31 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features", + "input": { + "eax": 7, + "ecx": 0 + }, + "bits": [ + { + "name": "fsgsbase", + "register": "ebx", + "bit": 0 + }, + { + "name": "sgx", + "register": "ebx", + "bit": 2 + }, + { + "name": "bmi1", + "register": "ebx", + "bit": 3 + }, + { + "name": "hle", + "register": "ebx", + "bit": 4 + }, + { + "name": "avx2", + "register": "ebx", + "bit": 5 + }, + { + "name": "fdp-excptn-only", + "register": "ebx", + "bit": 6 + }, + { + "name": "smep", + "register": "ebx", + "bit": 7 + }, + { + "name": "bmi2", + "register": "ebx", + "bit": 8 + }, + { + "name": "erms", + "register": "ebx", + "bit": 9 + }, + { + "name": "invpcid", + "register": "ebx", + "bit": 10 + }, + { + "name": "rtm", + "register": "ebx", + "bit": 11 + }, + { + "name": "pqm", + "register": "ebx", + "bit": 12 + }, + { + "name": "mpx", + "register": "ebx", + "bit": 14 + }, + { + "name": "pqe", + "register": "ebx", + "bit": 15 + }, + { + "name": "avx512f", + "register": "ebx", + "bit": 16 + }, + { + "name": "avx512dq", + "register": "ebx", + "bit": 17 + }, + { + "name": "rdseed", + "register": "ebx", + "bit": 18 + }, + { + "name": "adx", + "register": "ebx", + "bit": 19 + }, + { + "name": "smap", + "register": "ebx", + "bit": 20 + }, + { + "name": "avx512ifma", + "register": "ebx", + "bit": 21 + }, + { + "name": "pcommit", + "register": "ebx", + "bit": 22 + }, + { + "name": "clflushopt", + "register": "ebx", + "bit": 23 + }, + { + "name": "clwb", + "register": "ebx", + "bit": 24 + }, + { + "name": "intel_pt", + "register": "ebx", + "bit": 25 + }, + { + "name": "avx512pf", + "register": "ebx", + "bit": 26 + }, + { + "name": "avx512er", + "register": "ebx", + "bit": 27 + }, + { + "name": "avx512cd", + "register": "ebx", + "bit": 28 + }, + { + "name": "sha_ni", + "register": "ebx", + "bit": 29 + }, + { + "name": "avx512bw", + "register": "ebx", + "bit": 30 + }, + { + "name": "avx512vl", + "register": "ebx", + "bit": 31 + }, + { + "name": "prefetchwt1", + "register": "ecx", + "bit": 0 + }, + { + "name": "avx512vbmi", + "register": "ecx", + "bit": 1 + }, + { + "name": "umip", + "register": "ecx", + "bit": 2 + }, + { + "name": "pku", + "register": "ecx", + "bit": 3 + }, + { + "name": "ospke", + "register": "ecx", + "bit": 4 + }, + { + "name": "waitpkg", + "register": "ecx", + "bit": 5 + }, + { + "name": "avx512_vbmi2", + "register": "ecx", + "bit": 6 + }, + { + "name": "cet_ss", + "register": "ecx", + "bit": 7 + }, + { + "name": "gfni", + "register": "ecx", + "bit": 8 + }, + { + "name": "vaes", + "register": "ecx", + "bit": 9 + }, + { + "name": "vpclmulqdq", + "register": "ecx", + "bit": 10 + }, + { + "name": "avx512_vnni", + "register": "ecx", + "bit": 11 + }, + { + "name": "avx512_bitalg", + "register": "ecx", + "bit": 12 + }, + { + "name": "tme", + "register": "ecx", + "bit": 13 + }, + { + "name": "avx512_vpopcntdq", + "register": "ecx", + "bit": 14 + }, + { + "name": "rdpid", + "register": "ecx", + "bit": 22 + }, + { + "name": "cldemote", + "register": "ecx", + "bit": 25 + }, + { + "name": "movdiri", + "register": "ecx", + "bit": 27 + }, + { + "name": "movdir64b", + "register": "ecx", + "bit": 28 + }, + { + "name": "enqcmd", + "register": "ecx", + "bit": 29 + }, + { + "name": "sgx_lc", + "register": "ecx", + "bit": 30 + }, + { + "name": "pks", + "register": "ecx", + "bit": 31 + }, + { + "name": "fsrm", + "register": "edx", + "bit": 4 + }, + { + "name": "avx512_vp2intersect", + "register": "edx", + "bit": 8 + }, + { + "name": "md_clear", + "register": "edx", + "bit": 10 + }, + { + "name": "serialize", + "register": "edx", + "bit": 14 + }, + { + "name": "tsxldtrk", + "register": "edx", + "bit": 16 + }, + { + "name": "amx_bf16", + "register": "edx", + "bit": 22 + }, + { + "name": "avx512_fp16", + "register": "edx", + "bit": 23 + }, + { + "name": "amx_tile", + "register": "edx", + "bit": 24 + }, + { + "name": "amx_int8", + "register": "edx", + "bit": 25 + }, + { + "name": "ssbd", + "register": "edx", + "bit": 31 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=7,_ECX=0:_Extended_Features", + "input": { + "eax": 7, + "ecx": 1 + }, + "bits": [ + { + "name": "sha512", + "register": "eax", + "bit": 0 + }, + { + "name": "sm3", + "register": "eax", + "bit": 1 + }, + { + "name": "sm4", + "register": "eax", + "bit": 2 + }, + { + "name": "rao_int", + "register": "eax", + "bit": 3 + }, + { + "name": "avx_vnni", + "register": "eax", + "bit": 4 + }, + { + "name": "avx512_bf16", + "register": "eax", + "bit": 5 + }, + { + "name": "cmpccxadd", + "register": "eax", + "bit": 7 + }, + { + "name": "arch_perfmon_ext", + "register": "eax", + "bit": 8 + }, + { + "name": "fzrm", + "register": "eax", + "bit": 10 + }, + { + "name": "fsrs", + "register": "eax", + "bit": 11 + }, + { + "name": "fsrc", + "register": "eax", + "bit": 12 + }, + { + "name": "lkgs", + "register": "eax", + "bit": 18 + }, + { + "name": "amx_fp16", + "register": "eax", + "bit": 21 + }, + { + "name": "avx_ifma", + "register": "eax", + "bit": 23 + }, + { + "name": "lam", + "register": "eax", + "bit": 26 + } + ] + }, + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0Dh:_XSAVE_features_and_state-components", + "input": { + "eax": 13, + "ecx": 1 + }, + "bits": [ + { + "name": "xsaveopt", + "register": "eax", + "bit": 0 + }, + { + "name": "xsavec", + "register": "eax", + "bit": 1 + }, + { + "name": "xgetbv1", + "register": "eax", + "bit": 2 + }, + { + "name": "xsaves", + "register": "eax", + "bit": 3 + }, + { + "name": "xfd", + "register": "eax", + "bit": 4 + } + ] + } + ], + "extension-flags": [ + { + "description": "https://en.wikipedia.org/wiki/CPUID#EAX=0Dh:_XSAVE_features_and_state-components", + "input": { + "eax": 2147483649, + "ecx": 0 + }, + "bits": [ + { + "name": "fpu", + "register": "edx", + "bit": 0 + }, + { + "name": "vme", + "register": "edx", + "bit": 1 + }, + { + "name": "de", + "register": "edx", + "bit": 2 + }, + { + "name": "pse", + "register": "edx", + "bit": 3 + }, + { + "name": "tsc", + "register": "edx", + "bit": 4 + }, + { + "name": "msr", + "register": "edx", + "bit": 5 + }, + { + "name": "pae", + "register": "edx", + "bit": 6 + }, + { + "name": "mce", + "register": "edx", + "bit": 7 + }, + { + "name": "cx8", + "register": "edx", + "bit": 8 + }, + { + "name": "apic", + "register": "edx", + "bit": 9 + }, + { + "name": "syscall", + "register": "edx", + "bit": 10 + }, + { + "name": "syscall", + "register": "edx", + "bit": 11 + }, + { + "name": "mtrr", + "register": "edx", + "bit": 12 + }, + { + "name": "pge", + "register": "edx", + "bit": 13 + }, + { + "name": "mca", + "register": "edx", + "bit": 14 + }, + { + "name": "cmov", + "register": "edx", + "bit": 15 + }, + { + "name": "pat", + "register": "edx", + "bit": 16 + }, + { + "name": "pse36", + "register": "edx", + "bit": 17 + }, + { + "name": "mp", + "register": "edx", + "bit": 19 + }, + { + "name": "nx", + "register": "edx", + "bit": 20 + }, + { + "name": "mmxext", + "register": "edx", + "bit": 22 + }, + { + "name": "mmx", + "register": "edx", + "bit": 23 + }, + { + "name": "fxsr", + "register": "edx", + "bit": 24 + }, + { + "name": "fxsr_opt", + "register": "edx", + "bit": 25 + }, + { + "name": "pdpe1gp", + "register": "edx", + "bit": 26 + }, + { + "name": "rdtscp", + "register": "edx", + "bit": 27 + }, + { + "name": "lm", + "register": "edx", + "bit": 29 + }, + { + "name": "3dnowext", + "register": "edx", + "bit": 30 + }, + { + "name": "3dnow", + "register": "edx", + "bit": 31 + }, + { + "name": "lahf_lm", + "register": "ecx", + "bit": 0 + }, + { + "name": "cmp_legacy", + "register": "ecx", + "bit": 1 + }, + { + "name": "svm", + "register": "ecx", + "bit": 2 + }, + { + "name": "extapic", + "register": "ecx", + "bit": 3 + }, + { + "name": "cr8_legacy", + "register": "ecx", + "bit": 4 + }, + { + "name": "abm", + "register": "ecx", + "bit": 5 + }, + { + "name": "sse4a", + "register": "ecx", + "bit": 6 + }, + { + "name": "misalignsse", + "register": "ecx", + "bit": 7 + }, + { + "name": "3dnowprefetch", + "register": "ecx", + "bit": 8 + }, + { + "name": "osvw", + "register": "ecx", + "bit": 9 + }, + { + "name": "ibs", + "register": "ecx", + "bit": 10 + }, + { + "name": "xop", + "register": "ecx", + "bit": 11 + }, + { + "name": "skinit", + "register": "ecx", + "bit": 12 + }, + { + "name": "wdt", + "register": "ecx", + "bit": 13 + }, + { + "name": "lwp", + "register": "ecx", + "bit": 15 + }, + { + "name": "fma4", + "register": "ecx", + "bit": 16 + }, + { + "name": "tce", + "register": "ecx", + "bit": 17 + }, + { + "name": "nodeid_msr", + "register": "ecx", + "bit": 19 + }, + { + "name": "tbm", + "register": "ecx", + "bit": 21 + }, + { + "name": "topoext", + "register": "ecx", + "bit": 22 + }, + { + "name": "perfctr_core", + "register": "ecx", + "bit": 23 + }, + { + "name": "perfctr_nb", + "register": "ecx", + "bit": 24 + }, + { + "name": "dbx", + "register": "ecx", + "bit": 26 + }, + { + "name": "perftsc", + "register": "ecx", + "bit": 27 + }, + { + "name": "pci_l2i", + "register": "ecx", + "bit": 28 + }, + { + "name": "mwaitx", + "register": "ecx", + "bit": 29 + } + ] + } + ] +} diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8dc5b982eac66a8230a107962882a11d4982240a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/cpuid_schema.json @@ -0,0 +1,134 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Schema for microarchitecture definitions and feature aliases", + "type": "object", + "additionalProperties": false, + "properties": { + "vendor": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + } + } + }, + "highest_extension_support": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + } + } + }, + "flags": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + }, + "bits": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "register": { + "type": "string" + }, + "bit": { + "type": "integer" + } + } + } + } + } + } + }, + "extension-flags": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "description": { + "type": "string" + }, + "input": { + "type": "object", + "additionalProperties": false, + "properties": { + "eax": { + "type": "integer" + }, + "ecx": { + "type": "integer" + } + } + }, + "bits": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "properties": { + "name": { + "type": "string" + }, + "register": { + "type": "string" + }, + "bit": { + "type": "integer" + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json new file mode 100644 index 0000000000000000000000000000000000000000..9275422ef4da53a21daf0b774f9d6ecb622c1d3e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures.json @@ -0,0 +1,3644 @@ +{ + "microarchitectures": { + "x86": { + "from": [], + "vendor": "generic", + "features": [] + }, + "i686": { + "from": ["x86"], + "vendor": "GenuineIntel", + "features": [] + }, + "pentium2": { + "from": ["i686"], + "vendor": "GenuineIntel", + "features": [ + "mmx" + ] + }, + "pentium3": { + "from": ["pentium2"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse" + ] + }, + "pentium4": { + "from": ["pentium3"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2" + ] + }, + "prescott": { + "from": ["pentium4"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "sse3" + ] + }, + "x86_64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.2.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": ":4.1.2", + "name": "x86-64", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name}" + } + ], + "clang": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "intel": [ + { + "versions": ":", + "name": "pentium4", + "flags": "-march={name} -mtune=generic" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "x86-64", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "x86_64_v2": { + "from": ["x86_64"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "4.6:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune=generic -mpopcnt" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v2", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "x86_64_v3": { + "from": ["x86_64_v2"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "avx", + "avx2", + "bmi1", + "bmi2", + "f16c", + "fma", + "abm", + "movbe", + "xsave" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "4.8:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "core-avx2", + "flags": "-march={name} -mtune={name} -fma -mf16c" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v3", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc" : [ + { + "versions": ":", + "name": "px", + "flags": "-tp {name} -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mxsave" + } + ] + } + }, + "x86_64_v4": { + "from": ["x86_64_v3"], + "vendor": "generic", + "features": [ + "cx16", + "lahf_lm", + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "avx", + "avx2", + "bmi1", + "bmi2", + "f16c", + "fma", + "abm", + "movbe", + "xsave", + "avx512f", + "avx512bw", + "avx512cd", + "avx512dq", + "avx512vl" + ], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "6.0:11.0", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + }, + { + "versions": "3.9:11.1", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "name": "x86-64", + "flags": "-march={name} -mtune=generic -mcx16 -msahf -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mmovbe -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + } + ], + "dpcpp": [ + { + "versions": "2021.2.0:", + "name": "x86-64-v4", + "flags": "-march={name} -mtune=generic" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "px", + "flags": "-tp {name} -mpopcnt -msse3 -msse4.1 -msse4.2 -mssse3 -mavx -mavx2 -mbmi -mbmi2 -mf16c -mfma -mlzcnt -mxsave -mavx512f -mavx512bw -mavx512cd -mavx512dq -mavx512vl" + } + ] + } + }, + "nocona": { + "from": ["x86_64"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "sse3" + ], + "compilers": { + "gcc": [ + { + "versions": "4.0.4:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "core2": { + "from": ["nocona"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3" + ], + "compilers": { + "gcc": [ + { + "versions": "4.3.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "nehalem": { + "from": ["core2", "x86_64_v2"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "westmere": { + "from": ["nehalem"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "corei7", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "sandybridge": { + "from": ["westmere"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "corei7-avx", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "corei7-avx", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "ivybridge": { + "from": ["sandybridge"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.6:4.8.5", + "name": "core-avx-i", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "core-avx-i", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "haswell": { + "from": ["ivybridge", "x86_64_v3"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:17.9.0", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "broadwell": { + "from": ["haswell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx" + ], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "haswell", + "flags": "-tp {name}" + } + ] + } + }, + "skylake": { + "from": ["broadwell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt" + ], + "compilers": { + "gcc": [ + { + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "haswell", + "flags": "-tp {name}" + } + ] + } + }, + "mic_knl": { + "from": ["broadwell"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "avx2", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "avx512f", + "avx512pf", + "avx512er", + "avx512cd" + ], + "compilers": { + "gcc": [ + { + "versions": "5.1:", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "knl", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":2021.2", + "name": "knl", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "skylake_avx512": { + "from": ["skylake", "x86_64_v4"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "clwb", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd" + ], + "compilers": { + "gcc": [ + { + "name": "skylake-avx512", + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "skylake-avx512", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "cannonlake": { + "from": ["skylake"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "cascadelake": { + "from": ["skylake_avx512"], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "clwb", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512_vnni" + ], + "compilers": { + "gcc": [ + { + "versions": "9.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "11.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "19.0.1:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "icelake": { + "from": [ + "cascadelake", + "cannonlake" + ], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha_ni", + "clwb", + "rdpid", + "gfni", + "avx512_vbmi2", + "avx512_vpopcntdq", + "avx512_bitalg", + "avx512_vnni", + "vpclmulqdq", + "vaes" + ], + "compilers": { + "gcc": [ + { + "name": "icelake-client", + "versions": "8.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "7.0:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "6.0:6.9", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "apple-clang": [ + { + "versions": "10.0.1:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + }, + { + "versions": "10.0.0:10.0.99", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "18.0:", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "name": "icelake-client", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "skylake", + "flags": "-tp {name}" + } + ] + } + }, + "sapphirerapids": { + "from": [ + "icelake" + ], + "vendor": "GenuineIntel", + "features": [ + "mmx", + "sse", + "sse2", + "ssse3", + "sse4_1", + "sse4_2", + "popcnt", + "aes", + "pclmulqdq", + "avx", + "rdrand", + "f16c", + "movbe", + "fma", + "avx2", + "bmi1", + "bmi2", + "rdseed", + "adx", + "clflushopt", + "xsavec", + "xsaveopt", + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd", + "avx512vbmi", + "avx512ifma", + "sha_ni", + "clwb", + "rdpid", + "gfni", + "avx512_vbmi2", + "avx512_vpopcntdq", + "avx512_bitalg", + "avx512_vnni", + "vpclmulqdq", + "vaes", + "avx512_bf16", + "cldemote", + "movdir64b", + "movdiri", + "serialize", + "waitpkg" + ], + "compilers": { + "gcc": [ + { + "versions": "11.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": "2021.2:", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "k10": { + "from": ["x86_64"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "cx16", + "3dnow", + "3dnowext" + ], + "compilers": { + "gcc": [ + { + "name": "amdfam10", + "versions": "4.3:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "amdfam10", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "amdfam10", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse2" + } + ], + "nvhpc": [] + } + }, + "bulldozer": { + "from": ["x86_64_v2"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2" + ], + "compilers": { + "gcc": [ + { + "name": "bdver1", + "versions": "4.7:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver1", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver1", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "piledriver": { + "from": ["bulldozer"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver2", + "versions": "4.7:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver2", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver2", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse3" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "steamroller": { + "from": ["piledriver"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "fsgsbase", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver3", + "versions": "4.8:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver3", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver3", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "flags": "-msse4.2" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "piledriver", + "flags": "-tp {name}" + } + ] + } + }, + "excavator": { + "from": ["steamroller", "x86_64_v3"], + "vendor": "AuthenticAMD", + "features": [ + "mmx", + "sse", + "sse2", + "sse4a", + "abm", + "avx", + "xop", + "fma4", + "aes", + "pclmulqdq", + "cx16", + "ssse3", + "sse4_1", + "sse4_2", + "bmi1", + "f16c", + "fma", + "fsgsbase", + "bmi2", + "avx2", + "movbe", + "tbm" + ], + "compilers": { + "gcc": [ + { + "name": "bdver4", + "versions": "4.9:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "name": "bdver4", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "bdver4", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "piledriver", + "flags": "-tp {name}" + } + ] + } + }, + "zen": { + "from": ["x86_64_v3"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt" + ], + "compilers": { + "gcc": [ + { + "name": "znver1", + "versions": "6.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "4.0:", + "name": "znver1", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "znver1", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "flags": "-tp {name}" + } + ] + } + }, + "zen2": { + "from": ["zen"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb" + ], + "compilers": { + "gcc": [ + { + "name": "znver2", + "versions": "9.0:", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "9.0:", + "name": "znver2", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "2.2:", + "name": "znver2", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "20.5:", + "flags": "-tp {name}" + } + ] + } + }, + "zen3": { + "from": ["zen2"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb", + "vaes", + "vpclmulqdq", + "pku" + ], + "compilers": { + "gcc": [ + { + "versions": "10.3:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "3.0:", + "name": "znver3", + "flags": "-march={name} -mtune={name}" + } + ], + "intel": [ + { + "versions": "16.0:", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "oneapi": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "dpcpp": [ + { + "versions": ":", + "warnings": "Intel's compilers may or may not optimize to the same degree for non-Intel microprocessors for optimizations that are not unique to Intel microprocessors", + "name": "core-avx2", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "21.11:", + "flags": "-tp {name}" + } + ] + } + }, + "zen4": { + "from": ["zen3", "x86_64_v4"], + "vendor": "AuthenticAMD", + "features": [ + "bmi1", + "bmi2", + "f16c", + "fma", + "fsgsbase", + "avx", + "avx2", + "rdseed", + "clzero", + "aes", + "pclmulqdq", + "cx16", + "movbe", + "mmx", + "sse", + "sse2", + "sse4a", + "ssse3", + "sse4_1", + "sse4_2", + "abm", + "xsavec", + "xsaveopt", + "clflushopt", + "popcnt", + "clwb", + "vaes", + "vpclmulqdq", + "pku", + "gfni", + "flush_l1d", + "avx512f", + "avx512dq", + "avx512ifma", + "avx512cd", + "avx512bw", + "avx512vl", + "avx512_bf16", + "avx512vbmi", + "avx512_vbmi2", + "avx512_vnni", + "avx512_bitalg", + "avx512_vpopcntdq" + ], + "compilers": { + "gcc": [ + { + "versions": "10.3:12.2", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg" + }, + { + "versions": "12.3:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "12.0:15.9", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg" + }, + { + "versions": "16.0:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "3.0:3.9", + "name": "znver3", + "flags": "-march={name} -mtune={name} -mavx512f -mavx512dq -mavx512ifma -mavx512cd -mavx512bw -mavx512vl -mavx512vbmi -mavx512vbmi2 -mavx512vnni -mavx512bitalg", + "warnings": "Zen4 processors are not fully supported by AOCC versions < 4.0. For optimal performance please upgrade to a newer version of AOCC" + }, + { + "versions": "4.0:", + "name": "znver4", + "flags": "-march={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": "21.11:23.8", + "name": "zen3", + "flags": "-tp {name}", + "warnings": "zen4 is not fully supported by nvhpc versions < 23.9, falling back to zen3" + }, + { + "versions": "23.9:", + "flags": "-tp {name}" + } + ] + } + }, + "zen5": { + "from": ["zen4"], + "vendor": "AuthenticAMD", + "features": [ + "abm", + "aes", + "avx", + "avx2", + "avx512_bf16", + "avx512_bitalg", + "avx512bw", + "avx512cd", + "avx512dq", + "avx512f", + "avx512ifma", + "avx512vbmi", + "avx512_vbmi2", + "avx512vl", + "avx512_vnni", + "avx512_vp2intersect", + "avx512_vpopcntdq", + "avx_vnni", + "bmi1", + "bmi2", + "clflushopt", + "clwb", + "clzero", + "cppc", + "cx16", + "f16c", + "flush_l1d", + "fma", + "fsgsbase", + "gfni", + "ibrs_enhanced", + "mmx", + "movbe", + "movdir64b", + "movdiri", + "pclmulqdq", + "popcnt", + "rdseed", + "sse", + "sse2", + "sse4_1", + "sse4_2", + "sse4a", + "ssse3", + "tsc_adjust", + "vaes", + "vpclmulqdq", + "xsavec", + "xsaveopt" + ], + "compilers": { + "gcc": [ + { + "versions": "14.1:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ], + "aocc": [ + { + "versions": "5.0:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "19.1:", + "name": "znver5", + "flags": "-march={name} -mtune={name}" + } + ] + } + }, + "ppc64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "name": "powerpc64", + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power7": { + "from": ["ppc64"], + "vendor": "IBM", + "generation": 7, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.4:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power8": { + "from": ["power7"], + "vendor": "IBM", + "generation": 8, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "flags": "-mcpu={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "warnings": "Using GCC 4.8 to optimize for Power 8 might not work if you are not on Red Hat Enterprise Linux 7, where a custom backport of the feature has been done. Upstream support from GCC starts in version 4.9", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power9": { + "from": ["power8"], + "vendor": "IBM", + "generation": 9, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "power10": { + "from": ["power9"], + "vendor": "IBM", + "generation": 10, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "11.1:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "11.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "ppc64le": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "name": "powerpc64le", + "versions": "4.8:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [] + } + }, + "power8le": { + "from": ["ppc64le"], + "vendor": "IBM", + "generation": 8, + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.9:", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + }, + { + "versions": "4.8:4.8.5", + "warnings": "Using GCC 4.8 to optimize for Power 8 might not work if you are not on Red Hat Enterprise Linux 7, where a custom backport of the feature has been done. Upstream support from GCC starts in version 4.9", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "family": "ppc64le", + "name": "power8", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "pwr8", + "flags": "-tp {name}" + } + ] + } + }, + "power9le": { + "from": ["power8le"], + "vendor": "IBM", + "generation": 9, + "features": [], + "compilers": { + "gcc": [ + { + "name": "power9", + "versions": "6.0:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "3.9:", + "family": "ppc64le", + "name": "power9", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "nvhpc": [ + { + "versions": ":", + "name": "pwr9", + "flags": "-tp {name}" + } + ] + } + }, + "power10le": { + "from": ["power9le"], + "vendor": "IBM", + "generation": 10, + "features": [], + "compilers": { + "gcc": [ + { + "name": "power10", + "versions": "11.1:", + "flags": "-mcpu={name} -mtune={name}" + } + ], + "clang": [ + { + "versions": "11.0:", + "family": "ppc64le", + "name": "power10", + "flags": "-mcpu={name} -mtune={name}" + } + ] + } + }, + "aarch64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "4.8.0:", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8-a -mtune=generic" + } + ], + "nvhpc": [] + } + }, + "armv8.1a": { + "from": ["aarch64"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "5:", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.1-a -mtune=generic" + } + ] + } + }, + "armv8.2a": { + "from": ["armv8.1a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6:", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "clang": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.2-a -mtune=generic" + } + ] + } + }, + "armv8.3a": { + "from": ["armv8.2a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "6:", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "6:", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.3-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.3-a -mtune=generic" + } + ] + } + }, + "armv8.4a": { + "from": ["armv8.3a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "8:", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "8:", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.4-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.4-a -mtune=generic" + } + ] + } + }, + "armv8.5a": { + "from": ["armv8.4a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "9:", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "11:", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv8.5-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv8.5-a -mtune=generic" + } + ] + } + }, + "armv9.0a": { + "from": ["armv8.5a"], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "12:", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "clang": [ + { + "versions": "14:", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "apple-clang": [ + { + "versions": ":", + "flags": "-march=armv9-a -mtune=generic" + } + ], + "arm": [ + { + "versions": ":", + "flags": "-march=armv9-a -mtune=generic" + } + ] + } + }, + "thunderx2": { + "from": ["armv8.1a"], + "vendor": "Cavium", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "cpuid", + "asimdrdm" + ], + "compilers": { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "7:", + "flags": "-mcpu=thunderx2t99" + } + ], + "clang": [ + { + "versions": "3.9:4.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "5:", + "flags": "-mcpu=thunderx2t99" + } + ] + }, + "cpupart": "0x0af" + }, + "a64fx": { + "from": ["armv8.2a"], + "vendor": "Fujitsu", + "features": [ + "fp", + "asimd", + "evtstrm", + "sha1", + "sha2", + "crc32", + "atomics", + "cpuid", + "asimdrdm", + "fphp", + "asimdhp", + "fcma", + "dcpop", + "sve" + ], + "compilers": { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags": "-march=armv8.1-a+crc+crypto" + }, + { + "versions": "7:7.9", + "flags": "-march=armv8.2-a+crc+crypto+fp16" + }, + { + "versions": "8:10.2", + "flags": "-march=armv8.2-a+crc+sha2+fp16+sve -msve-vector-bits=512" + }, + { + "versions": "10.3:", + "flags": "-mcpu=a64fx -msve-vector-bits=512" + } + ], + "clang": [ + { + "versions": "3.9:4.9", + "flags": "-march=armv8.2-a+crc+sha2+fp16" + }, + { + "versions": "5:10", + "flags": "-march=armv8.2-a+crc+sha2+fp16+sve" + }, + { + "versions": "11:", + "flags": "-mcpu=a64fx" + } + ], + "arm": [ + { + "versions": "20:", + "flags": "-march=armv8.2-a+crc+crypto+fp16+sve" + } + ] + }, + "cpupart": "0x001" + }, + "cortex_a72": { + "from": ["aarch64"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "cpuid" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags" : "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags" : "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:", + "flags" : "-mcpu=cortex-a72" + } + ], + "clang" : [ + { + "versions": "3.9:", + "flags" : "-mcpu=cortex-a72" + } + ] + }, + "cpupart": "0xd08" + }, + "neoverse_n1": { + "from": ["cortex_a72", "armv8.2a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "lrcpc", + "dcpop", + "asimddp" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7:7.9", + "flags" : "-march=armv8.2-a+fp16 -mtune=cortex-a72" + }, + { + "versions": "8.0:8.0", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "8.1:8.9", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "9.0:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "clang" : [ + { + "versions": "3.9:4.9", + "flags" : "-march=armv8.2-a+fp16+crc+crypto" + }, + { + "versions": "5:", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "10:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "arm" : [ + { + "versions": "20:21.9", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "22:", + "flags" : "-mcpu=neoverse-n1" + } + ], + "nvhpc" : [ + { + "versions": "22.5:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd0c" + }, + "neoverse_v1": { + "from": ["neoverse_n1", "armv8.4a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "dcpodp", + "svei8mm", + "svebf16", + "i8mm", + "bf16", + "dgh", + "rng" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:4.8.9", + "flags": "-march=armv8-a" + }, + { + "versions": "4.9:5.9", + "flags": "-march=armv8-a+crc+crypto" + }, + { + "versions": "6:6.9", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7:7.9", + "flags" : "-march=armv8.2-a+crypto+fp16 -mtune=cortex-a72" + }, + { + "versions": "8.0:8.4", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "8.5:8.9", + "flags" : "-mcpu=neoverse-v1" + }, + { + "versions": "9.0:9.3", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "9.4:9.9", + "flags" : "-mcpu=neoverse-v1" + }, + { + "versions": "10.0:10.1", + "flags" : "-march=armv8.2-a+fp16+dotprod+crypto -mtune=cortex-a72" + }, + { + "versions": "10.2:10.2.99", + "flags" : "-mcpu=zeus" + }, + { + "versions": "10.3:", + "flags" : "-mcpu=neoverse-v1" + } + + ], + "clang" : [ + { + "versions": "3.9:4.9", + "flags" : "-march=armv8.2-a+fp16+crc+crypto" + }, + { + "versions": "5:10", + "flags" : "-march=armv8.2-a+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "11:", + "flags" : "-march=armv8.4-a+sve+fp16+bf16+crypto+i8mm+rng" + }, + { + "versions": "12:", + "flags" : "-mcpu=neoverse-v1" + } + ], + "arm" : [ + { + "versions": "20:21.9", + "flags" : "-march=armv8.2-a+sve+fp16+rcpc+dotprod+crypto" + }, + { + "versions": "22:", + "flags" : "-mcpu=neoverse-v1" + } + ], + "nvhpc" : [ + { + "versions": "22.5:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd40" + }, + "neoverse_v2": { + "from": ["neoverse_n1", "armv9.0a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "uscat", + "ilrcpc", + "flagm", + "sb", + "dcpodp", + "sve2", + "flagm2", + "frint", + "svei8mm", + "svebf16", + "i8mm", + "bf16" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:5.99", + "flags": "-march=armv8-a" + }, + { + "versions": "6:6.99", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7.0:7.99", + "flags" : "-march=armv8.2-a -mtune=cortex-a72" + }, + { + "versions": "8.0:8.99", + "flags" : "-march=armv8.4-a+sve -mtune=cortex-a72" + }, + { + "versions": "9.0:9.99", + "flags" : "-march=armv8.5-a+sve -mtune=cortex-a76" + }, + { + "versions": "10.0:11.3.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16 -mtune=cortex-a77" + }, + { + "versions": "11.4:11.99", + "flags" : "-mcpu=neoverse-v2" + }, + { + "versions": "12.0:12.2.99", + "flags" : "-march=armv9-a+i8mm+bf16 -mtune=cortex-a710" + }, + { + "versions": "12.3:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "clang" : [ + { + "versions": "9.0:10.99", + "flags" : "-march=armv8.5-a+sve" + }, + { + "versions": "11.0:13.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16" + }, + { + "versions": "14.0:15.99", + "flags" : "-march=armv9-a+i8mm+bf16" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "arm" : [ + { + "versions": "23.04.0:", + "flags" : "-mcpu=neoverse-v2" + } + ], + "nvhpc" : [ + { + "versions": "23.3:", + "name": "neoverse-v2", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd4f" + }, + "neoverse_n2": { + "from": ["neoverse_n1", "armv9.0a"], + "vendor": "ARM", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "sve", + "asimdfhm", + "uscat", + "ilrcpc", + "flagm", + "sb", + "dcpodp", + "sve2", + "flagm2", + "frint", + "svei8mm", + "svebf16", + "i8mm", + "bf16" + ], + "compilers" : { + "gcc": [ + { + "versions": "4.8:5.99", + "flags": "-march=armv8-a" + }, + { + "versions": "6:6.99", + "flags" : "-march=armv8.1-a" + }, + { + "versions": "7.0:7.99", + "flags" : "-march=armv8.2-a -mtune=cortex-a72" + }, + { + "versions": "8.0:8.99", + "flags" : "-march=armv8.4-a+sve -mtune=cortex-a72" + }, + { + "versions": "9.0:9.99", + "flags" : "-march=armv8.5-a+sve -mtune=cortex-a76" + }, + { + "versions": "10.0:10.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16 -mtune=cortex-a77" + }, + { + "versions": "11.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "clang" : [ + { + "versions": "9.0:10.99", + "flags" : "-march=armv8.5-a+sve" + }, + { + "versions": "11.0:13.99", + "flags" : "-march=armv8.5-a+sve+sve2+i8mm+bf16" + }, + { + "versions": "14.0:15.99", + "flags" : "-march=armv9-a+i8mm+bf16" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "arm" : [ + { + "versions": "23.04.0:", + "flags" : "-mcpu=neoverse-n2" + } + ], + "nvhpc" : [ + { + "versions": "23.3:", + "name": "neoverse-n1", + "flags": "-tp {name}" + } + ] + }, + "cpupart": "0xd49" + }, + "m1": { + "from": ["armv8.4a"], + "vendor": "Apple", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "ssbs", + "sb", + "paca", + "pacg", + "dcpodp", + "flagm2", + "frint" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags" : "-march=armv8.4-a -mtune=generic" + } + ], + "clang" : [ + { + "versions": "9.0:12.0", + "flags" : "-march=armv8.4-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + } + ], + "apple-clang": [ + { + "versions": "11.0:12.5", + "flags" : "-march=armv8.4-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + } + ] + }, + "cpupart": "0x022" + }, + "m2": { + "from": ["m1", "armv8.5a"], + "vendor": "Apple", + "features": [ + "fp", + "asimd", + "evtstrm", + "aes", + "pmull", + "sha1", + "sha2", + "crc32", + "atomics", + "fphp", + "asimdhp", + "cpuid", + "asimdrdm", + "jscvt", + "fcma", + "lrcpc", + "dcpop", + "sha3", + "asimddp", + "sha512", + "asimdfhm", + "dit", + "uscat", + "ilrcpc", + "flagm", + "ssbs", + "sb", + "paca", + "pacg", + "dcpodp", + "flagm2", + "frint", + "ecv", + "bf16", + "i8mm", + "bti" + ], + "compilers": { + "gcc": [ + { + "versions": "8.0:", + "flags" : "-march=armv8.5-a -mtune=generic" + } + ], + "clang" : [ + { + "versions": "9.0:12.0", + "flags" : "-march=armv8.5-a" + }, + { + "versions": "13.0:", + "flags" : "-mcpu=apple-m1" + }, + { + "versions": "16.0:", + "flags" : "-mcpu=apple-m2" + } + ], + "apple-clang": [ + { + "versions": "11.0:12.5", + "flags" : "-march=armv8.5-a" + }, + { + "versions": "13.0:14.0.2", + "flags" : "-mcpu=apple-m1" + }, + { + "versions": "14.0.2:", + "flags" : "-mcpu=apple-m2" + } + ] + }, + "cpupart": "0x032" + }, + "arm": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "clang": [ + { + "versions": ":", + "family": "arm", + "flags": "-march={family} -mcpu=generic" + } + ] + } + }, + "ppc": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "ppcle": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "sparc": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "sparc64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + } + }, + "riscv64": { + "from": [], + "vendor": "generic", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "7.1:", + "flags" : "-march=rv64gc" + } + ], + "clang": [ + { + "versions": "9.0:", + "flags" : "-march=rv64gc" + } + ] + } + }, + "u74mc": { + "from": ["riscv64"], + "vendor": "SiFive", + "features": [], + "compilers": { + "gcc": [ + { + "versions": "10.2:", + "flags" : "-march=rv64gc -mtune=sifive-7-series" + } + ], + "clang" : [ + { + "versions": "12.0:", + "flags" : "-march=rv64gc -mtune=sifive-7-series" + } + ] + } + } + }, + "feature_aliases": { + "sse3": { + "reason": "ssse3 is a superset of sse3 and might be the only one listed", + "any_of": [ + "ssse3" + ] + }, + "avx512": { + "reason": "avx512 indicates generic support for any of the avx512 instruction sets", + "any_of": [ + "avx512f", + "avx512vl", + "avx512bw", + "avx512dq", + "avx512cd" + ] + }, + "altivec": { + "reason": "altivec is supported by Power PC architectures, but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "vsx": { + "reason": "VSX alitvec extensions are supported by PowerISA from v2.06 (Power7+), but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "fma": { + "reason": "FMA has been supported by PowerISA since Power1, but might not be listed in features", + "families": [ + "ppc64le", + "ppc64" + ] + }, + "sse4.1": { + "reason": "permits to refer to sse4_1 also as sse4.1", + "any_of": [ + "sse4_1" + ] + }, + "sse4.2": { + "reason": "permits to refer to sse4_2 also as sse4.2", + "any_of": [ + "sse4_2" + ] + }, + "neon": { + "reason": "NEON is required in all standard ARMv8 implementations", + "families": [ + "aarch64" + ] + } + }, + "conversions": { + "description": "Conversions that map some platform specific values to canonical values", + "arm_vendors": { + "0x41": "ARM", + "0x42": "Broadcom", + "0x43": "Cavium", + "0x44": "DEC", + "0x46": "Fujitsu", + "0x48": "HiSilicon", + "0x49": "Infineon Technologies AG", + "0x4d": "Motorola", + "0x4e": "Nvidia", + "0x50": "APM", + "0x51": "Qualcomm", + "0x53": "Samsung", + "0x56": "Marvell", + "0x61": "Apple", + "0x66": "Faraday", + "0x68": "HXT", + "0x69": "Intel" + }, + "darwin_flags": { + "sse4.1": "sse4_1", + "sse4.2": "sse4_2", + "avx1.0": "avx", + "clfsopt": "clflushopt", + "xsave": "xsavec xsaveopt" + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json new file mode 100644 index 0000000000000000000000000000000000000000..085e5b95772e6a71e72afb21678cb1efe731b4d1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/cpu/microarchitectures_schema.json @@ -0,0 +1,113 @@ +{ + "$schema": "http://json-schema.org/draft-07/schema#", + "title": "Schema for microarchitecture definitions and feature aliases", + "type": "object", + "additionalProperties": false, + "properties": { + "microarchitectures": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "type": "object", + "properties": { + "from": { + "$comment": "More than one parent", + "type": "array", + "items": { + "type": "string" + } + }, + "vendor": { + "type": "string" + }, + "features": { + "type": "array", + "items": { + "type": "string" + } + }, + "compilers": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "$comment": "Permit multiple entries since compilers change options across versions", + "type": "array", + "items": { + "type": "object", + "properties": { + "versions": { + "type": "string" + }, + "name": { + "type": "string" + }, + "flags": { + "type": "string" + } + }, + "required": [ + "versions", + "flags" + ] + } + } + } + }, + "cpupart": { + "type": "string" + } + }, + "required": [ + "from", + "vendor", + "features" + ] + } + } + }, + "feature_aliases": { + "type": "object", + "patternProperties": { + "([\\w]*)": { + "type": "object", + "properties": { + "reason": { + "$comment": "Comment containing the reason why an alias is there", + "type": "string" + }, + "any_of": { + "$comment": "The alias is true if any of the items is a feature of the target", + "type": "array", + "items": { + "type": "string" + } + }, + "families": { + "$comment": "The alias is true if the family of the target is in this list", + "type": "array", + "items": { + "type": "string" + } + } + }, + "additionalProperties": false + } + } + }, + "conversions": { + "type": "object", + "properties": { + "description": { + "type": "string" + }, + "arm_vendors": { + "type": "object" + }, + "darwin_flags": { + "type": "object" + } + }, + "additionalProperties": false + } + } +} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 new file mode 100644 index 0000000000000000000000000000000000000000..39da8a49fe06920f0a9ac714612ccc625551523b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/bgq-rhel6-power7 @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER7 (architected), altivec supported +clock : 3720.000000MHz +revision : 2.1 (pvr 003f 0201) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 new file mode 100644 index 0000000000000000000000000000000000000000..b033bcb90d939d207f6c1bec351843c4ef488634 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-bigsur-m1 @@ -0,0 +1,19 @@ +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple processor +hw.optional.floatingpoint: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.amx_version: 2 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell new file mode 100644 index 0000000000000000000000000000000000000000..45054c567634d236bacc45274d328e42998b6ff0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-haswell @@ -0,0 +1,5 @@ +machdep.cpu.vendor: GenuineIntel +machdep.cpu.model: 70 +machdep.cpu.brand_string: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX SMX EST TM2 SSSE3 FMA CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC MOVBE POPCNT AES PCID XSAVE OSXSAVE SEGLIM64 TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS TSC_THREAD_OFFSET BMI1 AVX2 SMEP BMI2 ERMS INVPCID FPU_CSDS MDCLEAR IBRS STIBP L1DF SSBD diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..6a52d6c19dbe4ef8023f102d795f3f5db996ecfd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-ivybridge @@ -0,0 +1,59 @@ +machdep.cpu.max_basic: 13 +machdep.cpu.max_ext: 2147483656 +machdep.cpu.vendor: GenuineIntel +machdep.cpu.brand_string: Intel(R) Core(TM) i5-3230M CPU @ 2.60GHz +machdep.cpu.family: 6 +machdep.cpu.model: 58 +machdep.cpu.extmodel: 3 +machdep.cpu.extfamily: 0 +machdep.cpu.stepping: 9 +machdep.cpu.feature_bits: 9203919201183202303 +machdep.cpu.leaf7_feature_bits: 641 0 +machdep.cpu.leaf7_feature_bits_edx: 2617246720 +machdep.cpu.extfeature_bits: 4967106816 +machdep.cpu.signature: 198313 +machdep.cpu.brand: 0 +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX EST TM2 SSSE3 CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC POPCNT AES PCID XSAVE OSXSAVE TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS SMEP ERMS MDCLEAR IBRS STIBP L1DF SSBD +machdep.cpu.extfeatures: SYSCALL XD EM64T LAHF RDTSCP TSCI +machdep.cpu.logical_per_package: 16 +machdep.cpu.cores_per_package: 8 +machdep.cpu.microcode_version: 33 +machdep.cpu.processor_flag: 4 +machdep.cpu.mwait.linesize_min: 64 +machdep.cpu.mwait.linesize_max: 64 +machdep.cpu.mwait.extensions: 3 +machdep.cpu.mwait.sub_Cstates: 135456 +machdep.cpu.thermal.sensor: 1 +machdep.cpu.thermal.dynamic_acceleration: 1 +machdep.cpu.thermal.invariant_APIC_timer: 1 +machdep.cpu.thermal.thresholds: 2 +machdep.cpu.thermal.ACNT_MCNT: 1 +machdep.cpu.thermal.core_power_limits: 1 +machdep.cpu.thermal.fine_grain_clock_mod: 1 +machdep.cpu.thermal.package_thermal_intr: 1 +machdep.cpu.thermal.hardware_feedback: 0 +machdep.cpu.thermal.energy_policy: 0 +machdep.cpu.xsave.extended_state: 7 832 832 0 +machdep.cpu.xsave.extended_state1: 1 0 0 0 +machdep.cpu.arch_perf.version: 3 +machdep.cpu.arch_perf.number: 4 +machdep.cpu.arch_perf.width: 48 +machdep.cpu.arch_perf.events_number: 7 +machdep.cpu.arch_perf.events: 0 +machdep.cpu.arch_perf.fixed_number: 3 +machdep.cpu.arch_perf.fixed_width: 48 +machdep.cpu.cache.linesize: 64 +machdep.cpu.cache.L2_associativity: 8 +machdep.cpu.cache.size: 256 +machdep.cpu.tlb.inst.small: 64 +machdep.cpu.tlb.inst.large: 8 +machdep.cpu.tlb.data.small: 64 +machdep.cpu.tlb.data.large: 32 +machdep.cpu.tlb.shared: 512 +machdep.cpu.address_bits.physical: 36 +machdep.cpu.address_bits.virtual: 48 +machdep.cpu.core_count: 2 +machdep.cpu.thread_count: 4 +machdep.cpu.tsc_ccc.numerator: 0 +machdep.cpu.tsc_ccc.denominator: 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake new file mode 100644 index 0000000000000000000000000000000000000000..67dc28a966fc4a8f83fc1d652c78217ed7f773ee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-mojave-skylake @@ -0,0 +1,5 @@ +machdep.cpu.vendor: GenuineIntel +machdep.cpu.features: FPU VME DE PSE TSC MSR PAE MCE CX8 APIC SEP MTRR PGE MCA CMOV PAT PSE36 CLFSH DS ACPI MMX FXSR SSE SSE2 SS HTT TM PBE SSE3 PCLMULQDQ DTES64 MON DSCPL VMX EST TM2 SSSE3 FMA CX16 TPR PDCM SSE4.1 SSE4.2 x2APIC MOVBE POPCNT AES PCID XSAVE OSXSAVE SEGLIM64 TSCTMR AVX1.0 RDRAND F16C +machdep.cpu.leaf7_features: RDWRFSGS TSC_THREAD_OFFSET SGX BMI1 HLE AVX2 SMEP BMI2 ERMS INVPCID RTM FPU_CSDS MPX RDSEED ADX SMAP CLFSOPT IPT MDCLEAR TSXFA IBRS STIBP L1DF SSBD +machdep.cpu.model: 94 +machdep.cpu.brand_string: Intel(R) Core(TM) i7-6700K CPU @ 4.00GHz diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 new file mode 100644 index 0000000000000000000000000000000000000000..de801d480b7694b52927e1a5e0c25bd436f5e2d9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m1 @@ -0,0 +1,117 @@ +hw.ncpu: 8 +hw.byteorder: 1234 +hw.memsize: 17179869184 +hw.activecpu: 8 +hw.features.allows_security_research: 0 +hw.optional.arm.FEAT_FlagM: 1 +hw.optional.arm.FEAT_FlagM2: 1 +hw.optional.arm.FEAT_FHM: 1 +hw.optional.arm.FEAT_DotProd: 1 +hw.optional.arm.FEAT_SHA3: 1 +hw.optional.arm.FEAT_RDM: 1 +hw.optional.arm.FEAT_LSE: 1 +hw.optional.arm.FEAT_SHA256: 1 +hw.optional.arm.FEAT_SHA512: 1 +hw.optional.arm.FEAT_SHA1: 1 +hw.optional.arm.FEAT_AES: 1 +hw.optional.arm.FEAT_PMULL: 1 +hw.optional.arm.FEAT_SPECRES: 0 +hw.optional.arm.FEAT_SB: 1 +hw.optional.arm.FEAT_FRINTTS: 1 +hw.optional.arm.FEAT_LRCPC: 1 +hw.optional.arm.FEAT_LRCPC2: 1 +hw.optional.arm.FEAT_FCMA: 1 +hw.optional.arm.FEAT_JSCVT: 1 +hw.optional.arm.FEAT_PAuth: 1 +hw.optional.arm.FEAT_PAuth2: 0 +hw.optional.arm.FEAT_FPAC: 0 +hw.optional.arm.FEAT_DPB: 1 +hw.optional.arm.FEAT_DPB2: 1 +hw.optional.arm.FEAT_BF16: 0 +hw.optional.arm.FEAT_I8MM: 0 +hw.optional.arm.FEAT_ECV: 1 +hw.optional.arm.FEAT_LSE2: 1 +hw.optional.arm.FEAT_CSV2: 1 +hw.optional.arm.FEAT_CSV3: 1 +hw.optional.arm.FEAT_FP16: 1 +hw.optional.arm.FEAT_SSBS: 1 +hw.optional.arm.FEAT_BTI: 0 +hw.optional.floatingpoint: 1 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.armv8_3_compnum: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_gpi: 1 +hw.optional.AdvSIMD: 1 +hw.optional.AdvSIMD_HPFPCvt: 1 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 +hw.perflevel0.physicalcpu: 6 +hw.perflevel0.physicalcpu_max: 6 +hw.perflevel0.logicalcpu: 6 +hw.perflevel0.logicalcpu_max: 6 +hw.perflevel0.l1icachesize: 196608 +hw.perflevel0.l1dcachesize: 131072 +hw.perflevel0.l2cachesize: 12582912 +hw.perflevel0.cpusperl2: 3 +hw.perflevel1.physicalcpu: 2 +hw.perflevel1.physicalcpu_max: 2 +hw.perflevel1.logicalcpu: 2 +hw.perflevel1.logicalcpu_max: 2 +hw.perflevel1.l1icachesize: 131072 +hw.perflevel1.l1dcachesize: 65536 +hw.perflevel1.l2cachesize: 4194304 +hw.perflevel1.cpusperl2: 2 +hw.physicalcpu: 8 +hw.physicalcpu_max: 8 +hw.logicalcpu: 8 +hw.logicalcpu_max: 8 +hw.cputype: 16777228 +hw.cpusubtype: 2 +hw.cpu64bit_capable: 1 +hw.cpufamily: 458787763 +hw.cpusubfamily: 4 +hw.cacheconfig: 8 1 2 0 0 0 0 0 0 0 +hw.cachesize: 3443720192 65536 4194304 0 0 0 0 0 0 0 +hw.pagesize: 16384 +hw.pagesize32: 16384 +hw.cachelinesize: 128 +hw.l1icachesize: 131072 +hw.l1dcachesize: 65536 +hw.l2cachesize: 4194304 +hw.tbfrequency: 24000000 +hw.packages: 1 +hw.osenvironment: +hw.ephemeral_storage: 0 +hw.use_recovery_securityd: 0 +hw.use_kernelmanagerd: 1 +hw.serialdebugmode: 0 +hw.nperflevels: 2 +hw.targettype: J314s +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple M1 Pro +machdep.wake_abstime: 267689415132 +machdep.time_since_reset: 309271811230 +machdep.wake_conttime: 283552239 +machdep.deferred_ipi_timeout: 64000 +machdep.lck_mtx_adaptive_spin_mode: 1 +machdep.virtual_address_size: 47 +machdep.report_phy_read_delay: 0 +machdep.report_phy_write_delay: 0 +machdep.trace_phy_read_delay: 0 +machdep.trace_phy_write_delay: 0 +machdep.report_phy_read_osbt: 0 +machdep.report_phy_write_osbt: 0 +machdep.phy_read_delay_panic: 0 +machdep.phy_writedelay_panic: 0 +machdep.user_idle_level: 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 new file mode 100644 index 0000000000000000000000000000000000000000..757a1fb79ea15a10ff45e2b56ff6645786385e4f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/darwin-monterey-m2 @@ -0,0 +1,117 @@ +hw.ncpu: 8 +hw.byteorder: 1234 +hw.memsize: 17179869184 +hw.activecpu: 8 +hw.perflevel0.physicalcpu: 4 +hw.perflevel0.physicalcpu_max: 4 +hw.perflevel0.logicalcpu: 4 +hw.perflevel0.logicalcpu_max: 4 +hw.perflevel0.l1icachesize: 196608 +hw.perflevel0.l1dcachesize: 131072 +hw.perflevel0.l2cachesize: 16777216 +hw.perflevel0.cpusperl2: 4 +hw.perflevel1.physicalcpu: 4 +hw.perflevel1.physicalcpu_max: 4 +hw.perflevel1.logicalcpu: 4 +hw.perflevel1.logicalcpu_max: 4 +hw.perflevel1.l1icachesize: 131072 +hw.perflevel1.l1dcachesize: 65536 +hw.perflevel1.l2cachesize: 4194304 +hw.perflevel1.cpusperl2: 4 +hw.optional.arm.FEAT_FlagM: 1 +hw.optional.arm.FEAT_FlagM2: 1 +hw.optional.arm.FEAT_FHM: 1 +hw.optional.arm.FEAT_DotProd: 1 +hw.optional.arm.FEAT_SHA3: 1 +hw.optional.arm.FEAT_RDM: 1 +hw.optional.arm.FEAT_LSE: 1 +hw.optional.arm.FEAT_SHA256: 1 +hw.optional.arm.FEAT_SHA512: 1 +hw.optional.arm.FEAT_SHA1: 1 +hw.optional.arm.FEAT_AES: 1 +hw.optional.arm.FEAT_PMULL: 1 +hw.optional.arm.FEAT_SPECRES: 0 +hw.optional.arm.FEAT_SB: 1 +hw.optional.arm.FEAT_FRINTTS: 1 +hw.optional.arm.FEAT_LRCPC: 1 +hw.optional.arm.FEAT_LRCPC2: 1 +hw.optional.arm.FEAT_FCMA: 1 +hw.optional.arm.FEAT_JSCVT: 1 +hw.optional.arm.FEAT_PAuth: 1 +hw.optional.arm.FEAT_PAuth2: 1 +hw.optional.arm.FEAT_FPAC: 1 +hw.optional.arm.FEAT_DPB: 1 +hw.optional.arm.FEAT_DPB2: 1 +hw.optional.arm.FEAT_BF16: 1 +hw.optional.arm.FEAT_I8MM: 1 +hw.optional.arm.FEAT_ECV: 1 +hw.optional.arm.FEAT_LSE2: 1 +hw.optional.arm.FEAT_CSV2: 1 +hw.optional.arm.FEAT_CSV3: 1 +hw.optional.arm.FEAT_FP16: 1 +hw.optional.arm.FEAT_SSBS: 1 +hw.optional.arm.FEAT_BTI: 1 +hw.optional.floatingpoint: 1 +hw.optional.neon: 1 +hw.optional.neon_hpfp: 1 +hw.optional.neon_fp16: 1 +hw.optional.armv8_1_atomics: 1 +hw.optional.armv8_2_fhm: 1 +hw.optional.armv8_2_sha512: 1 +hw.optional.armv8_2_sha3: 1 +hw.optional.armv8_3_compnum: 1 +hw.optional.watchpoint: 4 +hw.optional.breakpoint: 6 +hw.optional.armv8_crc32: 1 +hw.optional.armv8_gpi: 1 +hw.optional.AdvSIMD: 1 +hw.optional.AdvSIMD_HPFPCvt: 1 +hw.optional.ucnormal_mem: 1 +hw.optional.arm64: 1 +hw.features.allows_security_research: 0 +hw.physicalcpu: 8 +hw.physicalcpu_max: 8 +hw.logicalcpu: 8 +hw.logicalcpu_max: 8 +hw.cputype: 16777228 +hw.cpusubtype: 2 +hw.cpu64bit_capable: 1 +hw.cpufamily: -634136515 +hw.cpusubfamily: 2 +hw.cacheconfig: 8 1 4 0 0 0 0 0 0 0 +hw.cachesize: 3697410048 65536 4194304 0 0 0 0 0 0 0 +hw.pagesize: 16384 +hw.pagesize32: 16384 +hw.cachelinesize: 128 +hw.l1icachesize: 131072 +hw.l1dcachesize: 65536 +hw.l2cachesize: 4194304 +hw.tbfrequency: 24000000 +hw.packages: 1 +hw.osenvironment: +hw.ephemeral_storage: 0 +hw.use_recovery_securityd: 0 +hw.use_kernelmanagerd: 1 +hw.serialdebugmode: 0 +hw.nperflevels: 2 +hw.targettype: J413 +machdep.cpu.cores_per_package: 8 +machdep.cpu.core_count: 8 +machdep.cpu.logical_per_package: 8 +machdep.cpu.thread_count: 8 +machdep.cpu.brand_string: Apple M2 +machdep.user_idle_level: 0 +machdep.wake_abstime: 5418683402971 +machdep.time_since_reset: 6671416324 +machdep.wake_conttime: 22097060794869 +machdep.deferred_ipi_timeout: 64000 +machdep.lck_mtx_adaptive_spin_mode: 1 +machdep.virtual_address_size: 47 +machdep.report_phy_read_delay: 0 +machdep.report_phy_write_delay: 0 +machdep.trace_phy_read_delay: 0 +machdep.trace_phy_write_delay: 0 +machdep.report_phy_read_osbt: 0 +machdep.report_phy_write_osbt: 0 +machdep.phy_read_delay_panic: 0 +machdep.phy_writedelay_panic: 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 new file mode 100644 index 0000000000000000000000000000000000000000..f500e6f8077196a8270fc88932f4fcdb46233b5b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-cortex_a72 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 166.66 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 cpuid +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd08 +CPU revision : 3 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 new file mode 100644 index 0000000000000000000000000000000000000000..17f1615825d77b3aeea6fdbbb250ca22cc9598b1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_n1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 243.75 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm lrcpc dcpop asimddp ssbs +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x3 +CPU part : 0xd0c +CPU revision : 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 new file mode 100644 index 0000000000000000000000000000000000000000..01246f99da41a5619a3b89e51e97b8919e94996d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon-neoverse_v1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs paca pacg dcpodp svei8mm svebf16 i8mm bf16 dgh rng +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0xd40 +CPU revision : 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids new file mode 100644 index 0000000000000000000000000000000000000000..633a8457d478ddd697aaf0e547dd4636a779079b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-amazon2-sapphirerapids @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 143 +model name : Intel(R) Xeon(R) Platinum 8488C +stepping : 8 +microcode : 0x2b000461 +cpu MHz : 3101.940 +cache size : 107520 KB +physical id : 0 +siblings : 48 +core id : 0 +cpu cores : 48 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 31 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves avx512_bf16 wbnoinvd ida arat avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq rdpid cldemote movdiri movdir64b md_clear serialize flush_l1d arch_capabilities +bugs : spectre_v1 spectre_v2 spec_store_bypass swapgs +bogomips : 4800.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 new file mode 100644 index 0000000000000000000000000000000000000000..11f48d1832a52a49b47aa575a2d94a4d00b787f2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 48.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp flagm2 frint +CPU implementer : 0x61 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x022 +CPU revision : 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 new file mode 100644 index 0000000000000000000000000000000000000000..93d048bec7e4ccddc5f8189dc6b81eafaddd3767 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-asahi-m2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 48.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp flagm2 frint i8mm bf16 bti ecv +CPU implementer : 0x61 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x032 +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake new file mode 100644 index 0000000000000000000000000000000000000000..e409c3d07a18c826fd9c7742b3e199cccae30d8b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-cascadelake @@ -0,0 +1,20 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 85 +model name : Intel(R) Xeon(R) Platinum 8260M CPU @ 2.40GHz +stepping : 7 +microcode : 0x5000024 +cpu MHz : 2400.000 +cache size : 36608 KB +physical id : 0 +siblings : 48 +core id : 0 +cpu cores : 24 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 22 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 intel_ppin intel_pt ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le new file mode 100644 index 0000000000000000000000000000000000000000..f21ca85323dd6f47f1bc2b2ab2a1dc9ee5529e91 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-power8le @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER8NVL (raw), altivec supported +clock : 2061.000000MHz +revision : 1.0 (pvr 004c 0100) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 new file mode 100644 index 0000000000000000000000000000000000000000..2447306bac15024241fd123c23cf013dad31b659 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-centos7-thunderx2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 400.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics cpuid asimdrdm +CPU implementer : 0x43 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x0af +CPU revision : 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..599d0c6fe7a933c2e44f79dfe473c9542395732d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel6-piledriver @@ -0,0 +1,29 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD FX(tm)-8350 Eight-Core Processor +stepping : 0 +microcode : 0x6000832 +cpu MHz : 4013.832 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 16 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb arat cpb hw_pstate npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold vmmcall bmi1 +bugs : fxsave_leak sysret_ss_attrs +bogomips : 8030.15 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro + +# /proc/cpuinfo taken from https://www.redhat.com/archives/vfio-users/2015-August/msg00111.html \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..427cd85bf2eaa24b98e80e26813658659b7a04a5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-broadwell @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 79 +model name : Intel(R) Xeon(R) CPU E5-2690 v4 @ 2.60GHz +stepping : 1 +microcode : 0xb00002a +cpu MHz : 2600.000 +cache size : 35840 KB +physical id : 0 +siblings : 14 +core id : 0 +cpu cores : 14 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 20 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm rdt_a rdseed adx smap xsaveopt cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 5188.06 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell new file mode 100644 index 0000000000000000000000000000000000000000..7bb5aa958f8b9254990bbdc31a32434b187fe067 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-haswell @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 63 +model name : Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz +stepping : 2 +microcode : 0x3c +cpu MHz : 1757.910 +cache size : 30720 KB +physical id : 0 +siblings : 12 +core id : 0 +cpu cores : 12 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 15 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm epb invpcid_single tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 4987.97 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge new file mode 100644 index 0000000000000000000000000000000000000000..7d6cfe4daaed77956694e9c14bd43a3bd739d86f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-ivybridge @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 62 +model name : Intel(R) Xeon(R) CPU E5-2650 v2 @ 2.60GHz +stepping : 4 +microcode : 0x42c +cpu MHz : 1862.554 +cache size : 20480 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 8 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm epb tpr_shadow vnmi flexpriority ept vpid fsgsbase smep erms xsaveopt ibpb ibrs stibp dtherm ida arat pln pts spec_ctrl intel_stibp +bogomips : 5200.15 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 new file mode 100644 index 0000000000000000000000000000000000000000..e9ab1987ddab06277177db82f6a5b590b901f276 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-skylake_avx512 @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 85 +model name : Intel(R) Xeon(R) Gold 6132 CPU @ 2.60GHz +stepping : 4 +microcode : 0x200004d +cpu MHz : 2600.000 +cache size : 19712 KB +physical id : 0 +siblings : 14 +core id : 0 +cpu cores : 14 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 22 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch epb cat_l3 cdp_l3 invpcid_single intel_pt tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local ibpb ibrs stibp dtherm ida arat pln pts spec_ctrl intel_stibp ssbd +bogomips : 5200.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 new file mode 100644 index 0000000000000000000000000000000000000000..d6feeccceb82f45bb868e864d0fd7aada6c61548 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-x86_64_v3 @@ -0,0 +1,26 @@ +COMMENT : Created synthetically to mimic Haswell with AES disabled from BIOS +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 63 +model name : Intel(R) Xeon(R) CPU E5-2680 v3 @ 2.50GHz +stepping : 2 +microcode : 0x3c +cpu MHz : 1757.910 +cache size : 30720 KB +physical id : 0 +siblings : 12 +core id : 0 +cpu cores : 12 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 15 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc aperfmperf eagerfpu pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer xsave avx f16c rdrand lahf_lm abm epb invpcid_single tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm xsaveopt cqm_llc cqm_occup_llc ibpb ibrs stibp dtherm arat pln pts spec_ctrl intel_stibp +bogomips : 4987.97 +clflush size : 64 +cache_alignment : 64 +address sizes : 46 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen new file mode 100644 index 0000000000000000000000000000000000000000..014dec3359e30216065e7aabde5f5671bbf5a1b9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel7-zen @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 23 +model : 1 +model name : AMD EPYC 7301 16-Core Processor +stepping : 2 +microcode : 0x8001227 +cpu MHz : 2200.000 +cache size : 512 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm aperfmperf eagerfpu pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_l2 cpb hw_pstate retpoline_amd ssbd ibpb vmmcall fsgsbase bmi1 avx2 smep bmi2 rdseed adx smap clflushopt sha_ni xsaveopt xsavec xgetbv1 clzero irperf xsaveerptr arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif overflow_recov succor smca +bogomips : 4399.40 +TLB size : 2560 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 new file mode 100644 index 0000000000000000000000000000000000000000..57853e97eafcaba26d569cc96f81213e083893a3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-neoverse_v1 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs dcpodp svei8mm svebf16 i8mm bf16 dgh rng +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0xd40 +CPU revision : 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 new file mode 100644 index 0000000000000000000000000000000000000000..7e1a89b631b51a03e4eeb94783abc422e5af64f5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel8-power9 @@ -0,0 +1,4 @@ +processor : 0 +cpu : POWER9, altivec supported +clock : 3666.000000MHz +revision : 2.2 (pvr 004e 1202) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 new file mode 100644 index 0000000000000000000000000000000000000000..f47458f51374540fbe53cb5bf7d7d9b5717c341a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_n2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2100.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb dcpodp sve2 sveaes svepmull svebitperm svesha3 flagm2 frint svei8mm svebf16 i8mm bf16 dgh +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd49 +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..cd5024170f79f726dc9ca8ee8106b8d0d23ce40d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rhel9-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx new file mode 100644 index 0000000000000000000000000000000000000000..2484dbe3e77128c56eff71ab117b62b003889746 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8-a64fx @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 200.00 +Features : fp asimd evtstrm sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm fcma dcpop sve +CPU implementer : 0x46 +CPU architecture: 8 +CPU variant : 0x1 +CPU part : 0x001 +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 new file mode 100644 index 0000000000000000000000000000000000000000..aa1c08bd1d68596efd425aa396244116f3e5114e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky8.5-zen4 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 25 +model : 17 +model name : AMD EPYC 9654 96-Core Processor +stepping : 1 +microcode : 0xa10110d +cpu MHz : 2400.000 +cache size : 1024 KB +physical id : 0 +siblings : 96 +core id : 0 +cpu cores : 96 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d sme sev sev_es +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 4792.38 +TLB size : 3584 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 52 bits physical, 57 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 new file mode 100644 index 0000000000000000000000000000000000000000..31379fde97b062bf34dd0c0ad71969fbe45a6729 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-rocky9-zen5 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 26 +model : 68 +model name : AMD Ryzen 9 9950X 16-Core Processor +stepping : 0 +microcode : 0xb40401a +cpu MHz : 600.000 +cache size : 1024 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl xtopology nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local user_shstk avx_vnni avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold v_vmsave_vmload vgif v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq rdpid bus_lock_detect movdiri movdir64b overflow_recov succor smca fsrm avx512_vp2intersect flush_l1d amd_lbr_pmc_freeze +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 8600.84 +TLB size : 192 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 new file mode 100644 index 0000000000000000000000000000000000000000..1522b17480e1137f86d1819f17ea8aba0d9bd006 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-k10 @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 16 +model : 9 +model name : AMD Opteron(tm) Processor 6136 +stepping : 1 +microcode : 0x10000d9 +cpu MHz : 800.000 +cache size : 512 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 8 +apicid : 16 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 5 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm 3dnowext 3dnow constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm pni monitor cx16 popcnt lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt nodeid_msr hw_pstate retpoline_amd ibp_disable vmmcall npt lbrv svm_lock nrip_save pausefilter +bogomips : 4800.19 +TLB size : 1024 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm stc 100mhzsteps hwpstate diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..4c823f6e46baab2ee6f204340e76505b3957e0b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientific7-piledriver @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD Opteron(tm) Processor 6320 +stepping : 0 +microcode : 0x6000852 +cpu MHz : 1400.000 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 32 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc art rep_good nopl nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb cpb hw_pstate retpoline_amd ssbd ibpb vmmcall bmi1 arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold +bogomips : 5600.11 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer new file mode 100644 index 0000000000000000000000000000000000000000..c240cfc6ce94618217d588b98a983d6da438e671 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-bulldozer @@ -0,0 +1,25 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 21 +model : 1 +model name : AMD Opteron(TM) Processor 6212 +stepping : 2 +cpu MHz : 2600.188 +cache size : 2048 KB +physical id : 0 +siblings : 8 +core id : 0 +cpu cores : 4 +apicid : 32 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 cx16 sse4_1 sse4_2 popcnt aes xsave avx lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 nodeid_msr topoext perfctr_core perfctr_nb cpb ssbd retpoline ibpb npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold +bogomips : 5200.37 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver new file mode 100644 index 0000000000000000000000000000000000000000..a87afeee612e1a71e7431ab0531f8d9c7c5564d7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-scientificfermi6-piledriver @@ -0,0 +1,25 @@ +processor : 31 +vendor_id : AuthenticAMD +cpu family : 21 +model : 2 +model name : AMD Opteron(tm) Processor 6320 +stepping : 0 +cpu MHz : 2800.154 +cache size : 2048 KB +physical id : 3 +siblings : 8 +core id : 3 +cpu cores : 4 +apicid : 135 +initial apicid : 103 +fpu : yes +fpu_exception : yes +cpuid level : 13 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nonstop_tsc extd_apicid amd_dcm aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 popcnt aes xsave avx f16c lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs xop skinit wdt lwp fma4 tce nodeid_msr tbm topoext perfctr_core perfctr_nb cpb ssbd retpoline ibpb npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold bmi1 +bogomips : 5599.22 +TLB size : 1536 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm 100mhzsteps hwpstate cpb eff_freq_ro diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc new file mode 100644 index 0000000000000000000000000000000000000000..8c1d29002e6952044d026945e1ab81e11a01dee4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-sifive-u74mc @@ -0,0 +1,5 @@ +processor : 0 +hart : 4 +isa : rv64imafdc +mmu : sv39 +uarch : sifive,u74-mc diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..bbe287ebf14956e40272be4e06f20d26f5a00cab --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu18.04-broadwell @@ -0,0 +1,26 @@ +processor : 0 +vendor_id : GenuineIntel +cpu family : 6 +model : 61 +model name : Intel(R) Core(TM) i5-5200U CPU @ 2.20GHz +stepping : 4 +microcode : 0x2d +cpu MHz : 1944.124 +cache size : 3072 KB +physical id : 0 +siblings : 4 +core id : 0 +cpu cores : 2 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 20 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap intel_pt xsaveopt dtherm ida arat pln pts md_clear flush_l1d +bugs : cpu_meltdown spectre_v1 spectre_v2 spec_store_bypass l1tf mds +bogomips : 4389.80 +clflush size : 64 +cache_alignment : 64 +address sizes : 39 bits physical, 48 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 new file mode 100644 index 0000000000000000000000000000000000000000..9d1f572b7ad812cdf5fc3c00def508841d073300 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu20.04-zen3 @@ -0,0 +1,27 @@ +processor : 0 +vendor_id : AuthenticAMD +cpu family : 25 +model : 33 +model name : AMD Ryzen 9 5950X 16-Core Processor +stepping : 0 +microcode : 0xa201009 +cpu MHz : 2122.858 +cache size : 512 KB +physical id : 0 +siblings : 32 +core id : 0 +cpu cores : 16 +apicid : 0 +initial apicid : 0 +fpu : yes +fpu_exception : yes +cpuid level : 16 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr wbnoinvd arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif umip pku ospke vaes vpclmulqdq rdpid overflow_recov succor smca +bugs : sysret_ss_attrs spectre_v1 spectre_v2 spec_store_bypass +bogomips : 6786.81 +TLB size : 2560 4K pages +clflush size : 64 +cache_alignment : 64 +address sizes : 48 bits physical, 48 bits virtual +power management: ts ttp tm hwpstate cpb eff_freq_ro [13] [14] diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 new file mode 100644 index 0000000000000000000000000000000000000000..cf555d2f49d236ed990db2791763b0eff5e61357 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_n2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 flagm2 frint svei8mm svebf16 i8mm bf16 +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd49 +CPU revision : 0 \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..c3c8433415d7a08c60057c01a91bafceba4923e7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-ubuntu22.04-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 sm3 sm4 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 svesm4 flagm2 frint svei8mm svebf16 i8mm bf16 dgh bti +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 new file mode 100644 index 0000000000000000000000000000000000000000..09087ac4e8decaf91b3d38151a2b4f13cb342c63 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-neoverse_v2 @@ -0,0 +1,8 @@ +processor : 0 +BogoMIPS : 2000.00 +Features : fp asimd evtstrm aes pmull sha1 sha2 crc32 atomics fphp asimdhp cpuid asimdrdm jscvt fcma lrcpc dcpop sha3 asimddp sha512 sve asimdfhm dit uscat ilrcpc flagm ssbs sb paca pacg dcpodp sve2 sveaes svepmull svebitperm svesha3 flagm2 frint svei8mm svebf16 i8mm bf16 dgh rng bti +CPU implementer : 0x41 +CPU architecture: 8 +CPU variant : 0x0 +CPU part : 0xd4f +CPU revision : 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 new file mode 100644 index 0000000000000000000000000000000000000000..ad8b15f9b9039f3bbd1af29e1b392e06b5f429aa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-power10 @@ -0,0 +1,3 @@ +processor : 0 +cpu : POWER10, altivec supported +revision : 17.0 (pvr 0080 1100) \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids new file mode 100644 index 0000000000000000000000000000000000000000..c317b6b6b515c100ddebb14f31d2c3ce5aacc563 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/linux-unknown-sapphirerapids @@ -0,0 +1,27 @@ +processor : 2 +vendor_id : GenuineIntel +cpu family : 6 +model : 143 +model name : Intel(R) Xeon(R) Platinum 8480+ +stepping : 6 +microcode : 0x2b000181 +cpu MHz : 2000.000 +cache size : 107520 KB +physical id : 0 +siblings : 112 +core id : 2 +cpu cores : 56 +apicid : 4 +initial apicid : 4 +fpu : yes +fpu_exception : yes +cpuid level : 32 +wp : yes +flags : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 invpcid_single intel_ppin cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities +vmx flags : vnmi preemption_timer posted_intr invvpid ept_x_only ept_ad ept_1gb flexpriority apicv tsc_offset vtpr mtf vapic ept vpid unrestricted_guest vapic_reg vid ple shadow_vmcs pml ept_mode_based_exec tsc_scaling usr_wait_pause +bugs : spectre_v1 spectre_v2 spec_store_bypass swapgs eibrs_pbrsb +bogomips : 4000.00 +clflush size : 64 +cache_alignment : 64 +address sizes : 52 bits physical, 57 bits virtual +power management: diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell new file mode 100644 index 0000000000000000000000000000000000000000..f19f1d4a475a08736c60a6b5ff40f2a98ca420c2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-broadwell @@ -0,0 +1,10 @@ +0, 0, 20, 1970169159, 1818588270, 1231384169 +2147483648, 0, 2147483656, 0, 0, 0 +1, 0, 198356, 34605056, 2147154879, 3219913727 +7, 0, 0, 35399595, 0, 2617247232 +7, 1, 0, 0, 0, 0 +13, 1, 1, 0, 0, 0 +2147483649, 0, 0, 0, 289, 739248128 +2147483650, 0, 1702129225, 693250156, 1919894304, 1297360997 +2147483651, 0, 929636393, 808793389, 1126192432, 1075860816 +2147483652, 0, 875442720, 2051557168, 0, 0 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake new file mode 100644 index 0000000000000000000000000000000000000000..dcc0453e4f3418e4e5c965dddd8f2fa7edf5569c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/json/tests/targets/windows-cpuid-icelake @@ -0,0 +1,10 @@ +0, 0, 20, 1970169159, 1818588270, 1231384169 +2147483648, 0, 2147483656, 0, 0, 0 +1, 0, 526017, 68159488, 2147154943, 3219913727 +7, 0, 2, 4089423851, 415268830, 4228908816 +7, 1, 0, 0, 0, 262144 +13, 1, 15, 2440, 14592, 0 +2147483649, 0, 0, 0, 289, 739248128 +2147483650, 0, 1752445233, 1852131104, 1953384736, 1378380901 +2147483651, 0, 1866670121, 1411933554, 1763715405, 825306423 +2147483652, 0, 927413560, 857751584, 1194340398, 31304 diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..c9b568f7eac5edcb35307bb793869b2c20e5ae41 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/.gitignore @@ -0,0 +1,2 @@ +*.pyc +*.swp diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..af36480022f9ffcd2ea82399328e271788b55503 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2014 Anders Høst + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the "Software"), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c79e37d86ce7e77133dad5cae2ea6e4e02a7d0d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/README.md @@ -0,0 +1,76 @@ +cpuid.py +======== + +Now, this is silly! + +Pure Python library for accessing information about x86 processors +by querying the [CPUID](http://en.wikipedia.org/wiki/CPUID) +instruction. Well, not exactly pure Python... + +It works by allocating a small piece of virtual memory, copying +a raw x86 function to that memory, giving the memory execute +permissions and then calling the memory as a function. The injected +function executes the CPUID instruction and copies the result back +to a ctypes.Structure where is can be read by Python. + +It should work fine on both 32 and 64 bit versions of Windows and Linux +running x86 processors. Apple OS X and other BSD systems should also work, +not tested though... + + +Why? +---- +For poops and giggles. Plus, having access to a low-level feature +without having to compile a C wrapper is pretty neat. + + +Examples +-------- +Getting info with eax=0: + + import cpuid + + q = cpuid.CPUID() + eax, ebx, ecx, edx = q(0) + +Running the files: + + $ python example.py + Vendor ID : GenuineIntel + CPU name : Intel(R) Xeon(R) CPU W3550 @ 3.07GHz + + Vector instructions supported: + SSE : Yes + SSE2 : Yes + SSE3 : Yes + SSSE3 : Yes + SSE4.1 : Yes + SSE4.2 : Yes + SSE4a : -- + AVX : -- + AVX2 : -- + + $ python cpuid.py + CPUID A B C D + 00000000 0000000b 756e6547 6c65746e 49656e69 + 00000001 000106a5 00100800 009ce3bd bfebfbff + 00000002 55035a01 00f0b2e4 00000000 09ca212c + 00000003 00000000 00000000 00000000 00000000 + 00000004 00000000 00000000 00000000 00000000 + 00000005 00000040 00000040 00000003 00001120 + 00000006 00000003 00000002 00000001 00000000 + 00000007 00000000 00000000 00000000 00000000 + 00000008 00000000 00000000 00000000 00000000 + 00000009 00000000 00000000 00000000 00000000 + 0000000a 07300403 00000044 00000000 00000603 + 0000000b 00000000 00000000 00000095 00000000 + 80000000 80000008 00000000 00000000 00000000 + 80000001 00000000 00000000 00000001 28100800 + 80000002 65746e49 2952286c 6f655820 2952286e + 80000003 55504320 20202020 20202020 57202020 + 80000004 30353533 20402020 37302e33 007a4847 + 80000005 00000000 00000000 00000000 00000000 + 80000006 00000000 00000000 01006040 00000000 + 80000007 00000000 00000000 00000000 00000100 + 80000008 00003024 00000000 00000000 00000000 + diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/cpuid.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/cpuid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7469f1a47cbfc66bba0c9a47069e78c3c49a96b3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/cpuid.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/example.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/example.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18827f17cab36843d56dc2a9483a9b2c4b8f2635 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/__pycache__/example.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py new file mode 100644 index 0000000000000000000000000000000000000000..79c15d16d1ab7e4149de287823e22eeaf2218e19 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/cpuid.py @@ -0,0 +1,172 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2024 Anders Høst +# + +from __future__ import print_function + +import platform +import os +import ctypes +from ctypes import c_uint32, c_long, c_ulong, c_size_t, c_void_p, POINTER, CFUNCTYPE + +# Posix x86_64: +# Three first call registers : RDI, RSI, RDX +# Volatile registers : RAX, RCX, RDX, RSI, RDI, R8-11 + +# Windows x86_64: +# Three first call registers : RCX, RDX, R8 +# Volatile registers : RAX, RCX, RDX, R8-11 + +# cdecl 32 bit: +# Three first call registers : Stack (%esp) +# Volatile registers : EAX, ECX, EDX + +_POSIX_64_OPC = [ + 0x53, # push %rbx + 0x89, 0xf0, # mov %esi,%eax + 0x89, 0xd1, # mov %edx,%ecx + 0x0f, 0xa2, # cpuid + 0x89, 0x07, # mov %eax,(%rdi) + 0x89, 0x5f, 0x04, # mov %ebx,0x4(%rdi) + 0x89, 0x4f, 0x08, # mov %ecx,0x8(%rdi) + 0x89, 0x57, 0x0c, # mov %edx,0xc(%rdi) + 0x5b, # pop %rbx + 0xc3 # retq +] + +_WINDOWS_64_OPC = [ + 0x53, # push %rbx + 0x89, 0xd0, # mov %edx,%eax + 0x49, 0x89, 0xc9, # mov %rcx,%r9 + 0x44, 0x89, 0xc1, # mov %r8d,%ecx + 0x0f, 0xa2, # cpuid + 0x41, 0x89, 0x01, # mov %eax,(%r9) + 0x41, 0x89, 0x59, 0x04, # mov %ebx,0x4(%r9) + 0x41, 0x89, 0x49, 0x08, # mov %ecx,0x8(%r9) + 0x41, 0x89, 0x51, 0x0c, # mov %edx,0xc(%r9) + 0x5b, # pop %rbx + 0xc3 # retq +] + +_CDECL_32_OPC = [ + 0x53, # push %ebx + 0x57, # push %edi + 0x8b, 0x7c, 0x24, 0x0c, # mov 0xc(%esp),%edi + 0x8b, 0x44, 0x24, 0x10, # mov 0x10(%esp),%eax + 0x8b, 0x4c, 0x24, 0x14, # mov 0x14(%esp),%ecx + 0x0f, 0xa2, # cpuid + 0x89, 0x07, # mov %eax,(%edi) + 0x89, 0x5f, 0x04, # mov %ebx,0x4(%edi) + 0x89, 0x4f, 0x08, # mov %ecx,0x8(%edi) + 0x89, 0x57, 0x0c, # mov %edx,0xc(%edi) + 0x5f, # pop %edi + 0x5b, # pop %ebx + 0xc3 # ret +] + +is_windows = os.name == "nt" +is_64bit = ctypes.sizeof(ctypes.c_voidp) == 8 + + +class CPUID_struct(ctypes.Structure): + _register_names = ("eax", "ebx", "ecx", "edx") + _fields_ = [(r, c_uint32) for r in _register_names] + + def __getitem__(self, item): + if item not in self._register_names: + raise KeyError(item) + return getattr(self, item) + + def __repr__(self): + return "eax=0x{:x}, ebx=0x{:x}, ecx=0x{:x}, edx=0x{:x}".format(self.eax, self.ebx, self.ecx, self.edx) + + +class CPUID(object): + def __init__(self): + if platform.machine() not in ("AMD64", "x86_64", "x86", "i686"): + raise SystemError("Only available for x86") + + if is_windows: + if is_64bit: + # VirtualAlloc seems to fail under some weird + # circumstances when ctypes.windll.kernel32 is + # used under 64 bit Python. CDLL fixes this. + self.win = ctypes.CDLL("kernel32.dll") + opc = _WINDOWS_64_OPC + else: + # Here ctypes.windll.kernel32 is needed to get the + # right DLL. Otherwise it will fail when running + # 32 bit Python on 64 bit Windows. + self.win = ctypes.windll.kernel32 + opc = _CDECL_32_OPC + else: + opc = _POSIX_64_OPC if is_64bit else _CDECL_32_OPC + + size = len(opc) + code = (ctypes.c_ubyte * size)(*opc) + + if is_windows: + self.win.VirtualAlloc.restype = c_void_p + self.win.VirtualAlloc.argtypes = [ctypes.c_void_p, ctypes.c_size_t, ctypes.c_ulong, ctypes.c_ulong] + self.addr = self.win.VirtualAlloc(None, size, 0x1000, 0x40) + if not self.addr: + raise MemoryError("Could not allocate RWX memory") + ctypes.memmove(self.addr, code, size) + else: + from mmap import ( + mmap, + MAP_PRIVATE, + MAP_ANONYMOUS, + PROT_WRITE, + PROT_READ, + PROT_EXEC, + ) + self.mm = mmap( + -1, + size, + flags=MAP_PRIVATE | MAP_ANONYMOUS, + prot=PROT_WRITE | PROT_READ | PROT_EXEC, + ) + self.mm.write(code) + self.addr = ctypes.addressof(ctypes.c_int.from_buffer(self.mm)) + + func_type = CFUNCTYPE(None, POINTER(CPUID_struct), c_uint32, c_uint32) + self.func_ptr = func_type(self.addr) + + def __call__(self, eax, ecx=0): + struct = self.registers_for(eax=eax, ecx=ecx) + return struct.eax, struct.ebx, struct.ecx, struct.edx + + def registers_for(self, eax, ecx=0): + """Calls cpuid with eax and ecx set as the input arguments, and returns a structure + containing eax, ebx, ecx, and edx. + """ + struct = CPUID_struct() + self.func_ptr(struct, eax, ecx) + return struct + + def __del__(self): + if is_windows: + self.win.VirtualFree.restype = c_long + self.win.VirtualFree.argtypes = [c_void_p, c_size_t, c_ulong] + self.win.VirtualFree(self.addr, 0, 0x8000) + else: + self.mm.close() + + + +if __name__ == "__main__": + def valid_inputs(): + cpuid = CPUID() + for eax in (0x0, 0x80000000): + highest, _, _, _ = cpuid(eax) + while eax <= highest: + regs = cpuid(eax) + yield (eax, regs) + eax += 1 + + + print(" ".join(x.ljust(8) for x in ("CPUID", "A", "B", "C", "D")).strip()) + for eax, regs in valid_inputs(): + print("%08x" % eax, " ".join("%08x" % reg for reg in regs)) diff --git a/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py new file mode 100644 index 0000000000000000000000000000000000000000..e07e3c15215b0a9411eb1c4cb6322ecb0fbe8892 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/archspec/vendor/cpuid/example.py @@ -0,0 +1,62 @@ +# -*- coding: utf-8 -*- +# +# Copyright (c) 2024 Anders Høst +# + +from __future__ import print_function + +import struct +import cpuid + + +def cpu_vendor(cpu): + _, b, c, d = cpu(0) + return struct.pack("III", b, d, c).decode("utf-8") + + +def cpu_name(cpu): + name = "".join((struct.pack("IIII", *cpu(0x80000000 + i)).decode("utf-8") + for i in range(2, 5))) + + return name.split('\x00', 1)[0] + + +def is_set(cpu, leaf, subleaf, reg_idx, bit): + """ + @param {leaf} %eax + @param {sublead} %ecx, 0 in most cases + @param {reg_idx} idx of [%eax, %ebx, %ecx, %edx], 0-based + @param {bit} bit of reg selected by {reg_idx}, 0-based + """ + + regs = cpu(leaf, subleaf) + + if (1 << bit) & regs[reg_idx]: + return "Yes" + else: + return "--" + + +if __name__ == "__main__": + cpu = cpuid.CPUID() + + print("Vendor ID : %s" % cpu_vendor(cpu)) + print("CPU name : %s" % cpu_name(cpu)) + print() + print("Vector instructions supported:") + print("SSE : %s" % is_set(cpu, 1, 0, 3, 25)) + print("SSE2 : %s" % is_set(cpu, 1, 0, 3, 26)) + print("SSE3 : %s" % is_set(cpu, 1, 0, 2, 0)) + print("SSSE3 : %s" % is_set(cpu, 1, 0, 2, 9)) + print("SSE4.1 : %s" % is_set(cpu, 1, 0, 2, 19)) + print("SSE4.2 : %s" % is_set(cpu, 1, 0, 2, 20)) + print("SSE4a : %s" % is_set(cpu, 0x80000001, 0, 2, 6)) + print("AVX : %s" % is_set(cpu, 1, 0, 2, 28)) + print("AVX2 : %s" % is_set(cpu, 7, 0, 1, 5)) + print("BMI1 : %s" % is_set(cpu, 7, 0, 1, 3)) + print("BMI2 : %s" % is_set(cpu, 7, 0, 1, 8)) + # Intel RDT CMT/MBM + print("L3 Monitoring : %s" % is_set(cpu, 0xf, 0, 3, 1)) + print("L3 Occupancy : %s" % is_set(cpu, 0xf, 1, 3, 0)) + print("L3 Total BW : %s" % is_set(cpu, 0xf, 1, 3, 1)) + print("L3 Local BW : %s" % is_set(cpu, 0xf, 1, 3, 2)) diff --git a/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9725772c7967075d97dc78d60f3735435eccba63 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/charset_normalizer-3.4.4.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 TAHRI Ahmed R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..622c9432b9b9adeebb62752f36784caa8b860c2a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0690002e69e6b87775bef736d101c3e7dd5429e7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/animation.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/animation.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36da471841895590c419cac2423dea3959f83a3e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/animation.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/asset.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/asset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b964dac58ebe429c3469f46486f05918c12bbf91 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/asset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/camera.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/camera.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7557d33c6a06783694d2ec0342286bcf1f1a596c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/camera.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/common.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7d092f7964a50546463b5dc15f891bd94689178 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/common.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/controller.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/controller.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef2a1b7b43f00c8acc0d9090ce969a449c0ec769 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/controller.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/geometry.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/geometry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d1f0caa8fd507548ed68f6abbeb6ce6372342c0f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/geometry.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/light.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/light.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5c45c729b45a452312e8e5b9c0729454940766f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/light.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/lineset.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/lineset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e383cfa8b2923b3d4dd2dee2d64fca186c59b80a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/lineset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/material.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/material.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9c6d809eba4fbde656c4d6515f3a4333988054b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/material.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polygons.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polygons.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab000e5327fb893ca0e4abfd386cbafa7d8d0af2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polygons.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polylist.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polylist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03387724a0604a27b9995521eabbedebfb7b1ff9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/polylist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/primitive.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/primitive.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf762c4882123c75769f68ecfee58004a608338a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/primitive.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/scene.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/scene.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c093451dedf07f156bfe87c87ce84bd31d04f836 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/scene.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/schema.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/schema.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d56510b6d8e4f4179d98fe4d4f46c9defcb24a63 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/schema.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/source.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/source.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aaf950934d40c2e8344f1df0acc07b1ece35253b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/source.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/triangleset.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/triangleset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cac75e9c54809802d6550fc0f4b1dfb8318a5291 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/triangleset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/util.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35b0981e36210f9bf5f1aaeacf75c0bf7e839f61 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/xmlutil.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/xmlutil.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aa8de30a4c7f2a52f27bc870ba7506deda5bfe51 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/__pycache__/xmlutil.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/resources/__init__.py b/data/miniconda3/lib/python3.13/site-packages/collada/resources/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d8a487cdbf0c651ddfdc0301d8bd4be9109a4e72 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/resources/__init__.py @@ -0,0 +1,19 @@ +from importlib import resources + + +def resource_string(file_name: str) -> str: + """ + Get the value of a file in `collada/resources/{file_name}` + as a string. + + Parameters + ----------- + file_name + The name of the file in `collada/resources/{file_name}` + + Returns + ---------- + value + The contents of the file. + """ + return resources.files("collada").joinpath("resources", file_name).read_text() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/resources/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/resources/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8be777b3ca3e0f8cffe2216140f0e5db09e6c650 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/resources/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/resources/schema-1.4.1.xml b/data/miniconda3/lib/python3.13/site-packages/collada/resources/schema-1.4.1.xml new file mode 100644 index 0000000000000000000000000000000000000000..dc77ed0b7e7b9100d2bdd1133a2886e06df27504 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/resources/schema-1.4.1.xml @@ -0,0 +1,11046 @@ + + + + + + COLLADA Schema + Version 1.4.1 (June 23, 2006) + + Copyright (C) 2005, 2006 The Khronos Group Inc., Sony Computer Entertainment Inc. + All Rights Reserved. + + Khronos is a trademark of The Khronos Group Inc. + COLLADA is a trademark of Sony Computer Entertainment Inc. used by permission by Khronos. + + Note that this software document is distributed on an "AS IS" basis, with ALL EXPRESS AND + IMPLIED WARRANTIES AND CONDITIONS DISCLAIMED, INCLUDING, WITHOUT LIMITATION, ANY IMPLIED + WARRANTIES AND CONDITIONS OF MERCHANTABILITY, SATISFACTORY QUALITY, FITNESS FOR A PARTICULAR + PURPOSE, AND NON-INFRINGEMENT. + + + + + + + + enable-xmlns + + The COLLADA element declares the root of the document that comprises some of the content + in the COLLADA schema. + + + + + + + + The COLLADA element must contain an asset element. + + + + + + + + The COLLADA element may contain any number of library_animations elements. + + + + + + + The COLLADA element may contain any number of library_animation_clips elements. + + + + + + + The COLLADA element may contain any number of library_cameras elements. + + + + + + + The COLLADA element may contain any number of library_controllerss elements. + + + + + + + The COLLADA element may contain any number of library_geometriess elements. + + + + + + + The COLLADA element may contain any number of library_effects elements. + + + + + + + The COLLADA element may contain any number of library_force_fields elements. + + + + + + + The COLLADA element may contain any number of library_images elements. + + + + + + + The COLLADA element may contain any number of library_lights elements. + + + + + + + The COLLADA element may contain any number of library_materials elements. + + + + + + + The COLLADA element may contain any number of library_nodes elements. + + + + + + + The COLLADA element may contain any number of library_materials elements. + + + + + + + The COLLADA element may contain any number of library_physics_models elements. + + + + + + + The COLLADA element may contain any number of library_physics_scenes elements. + + + + + + + The COLLADA element may contain any number of library_visual_scenes elements. + + + + + + + + The scene embodies the entire set of information that can be visualized from the + contents of a COLLADA resource. The scene element declares the base of the scene + hierarchy or scene graph. The scene contains elements that comprise much of the + visual and transformational information content as created by the authoring tools. + + + + + + + + The instance_physics_scene element declares the instantiation of a COLLADA physics_scene resource. + The instance_physics_scene element may appear any number of times. + + + + + + + The instance_visual_scene element declares the instantiation of a COLLADA visual_scene resource. + The instance_visual_scene element may only appear once. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The version attribute is the COLLADA schema revision with which the instance document + conforms. Required Attribute. + + + + + + + The xml:base attribute allows you to define the base URI for this COLLADA document. See + http://www.w3.org/TR/xmlbase/ for more information. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + An enumuerated type specifying the acceptable morph methods. + + + + + + + + + + + An enumerated type specifying the acceptable node types. + + + + + + + + + + + This type is used for URI reference which can only reference a resource declared within it's same document. + + + + + + + + + + An enumerated type specifying the acceptable up-axis values. + + + + + + + + + + + + An enumerated type specifying the acceptable document versions. + + + + + + + + + + + + The InputGlobal type is used to represent inputs that can reference external resources. + + + + + + The semantic attribute is the user-defined meaning of the input connection. Required attribute. + + + + + + + The source attribute indicates the location of the data source. Required attribute. + + + + + + + + The InputLocal type is used to represent inputs that can only reference resources declared in the same document. + + + + + + The semantic attribute is the user-defined meaning of the input connection. Required attribute. + + + + + + + The source attribute indicates the location of the data source. Required attribute. + + + + + + + + The InputLocalOffset type is used to represent indexed inputs that can only reference resources declared in the same document. + + + + + + The offset attribute represents the offset into the list of indices. If two input elements share + the same offset, they will be indexed the same. This works as a simple form of compression for the + list of indices as well as defining the order the inputs should be used in. Required attribute. + + + + + + + The semantic attribute is the user-defined meaning of the input connection. Required attribute. + + + + + + + The source attribute indicates the location of the data source. Required attribute. + + + + + + + The set attribute indicates which inputs should be grouped together as a single set. This is helpful + when multiple inputs share the same semantics. + + + + + + + + The InstanceWithExtra type is used for all generic instance elements. A generic instance element + is one which does not have any specific child elements declared. + + + + + + + The extra element may occur any number of times. + + + + + + + + The url attribute refers to resource to instantiate. This may refer to a local resource using a + relative URL fragment identifier that begins with the "#" character. The url attribute may refer + to an external resource using an absolute or relative URL. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + The TargetableFloat type is used to represent elements which contain a single float value which can + be targeted for animation. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + The TargetableFloat3 type is used to represent elements which contain a float3 value which can + be targeted for animation. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The IDREF_array element declares the storage for a homogenous array of ID reference values. + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of values in the array. Required attribute. + + + + + + + + + + + The Name_array element declares the storage for a homogenous array of Name string values. + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of values in the array. Required attribute. + + + + + + + + + + + The bool_array element declares the storage for a homogenous array of boolean values. + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of values in the array. Required attribute. + + + + + + + + + + + The float_array element declares the storage for a homogenous array of floating point values. + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of values in the array. Required attribute. + + + + + + + The digits attribute indicates the number of significant decimal digits of the float values that + can be contained in the array. The default value is 6. Optional attribute. + + + + + + + The magnitude attribute indicates the largest exponent of the float values that can be contained + in the array. The default value is 38. Optional attribute. + + + + + + + + + + + The int_array element declares the storage for a homogenous array of integer values. + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of values in the array. Required attribute. + + + + + + + The minInclusive attribute indicates the smallest integer value that can be contained in + the array. The default value is -2147483648. Optional attribute. + + + + + + + The maxInclusive attribute indicates the largest integer value that can be contained in + the array. The default value is 2147483647. Optional attribute. + + + + + + + + + + + + The accessor element declares an access pattern to one of the array elements: float_array, + int_array, Name_array, bool_array, and IDREF_array. The accessor element describes access + to arrays that are organized in either an interleaved or non-interleaved manner, depending + on the offset and stride attributes. + + + + + + + + The accessor element may have any number of param elements. + + + + + + + + The count attribute indicates the number of times the array is accessed. Required attribute. + + + + + + + The offset attribute indicates the index of the first value to be read from the array. + The default value is 0. Optional attribute. + + + + + + + The source attribute indicates the location of the array to access using a URL expression. Required attribute. + + + + + + + The stride attribute indicates number of values to be considered a unit during each access to + the array. The default value is 1, indicating that a single value is accessed. Optional attribute. + + + + + + + + + The param element declares parametric information regarding its parent element. + + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The semantic attribute is the user-defined meaning of the parameter. Optional attribute. + + + + + + + The type attribute indicates the type of the value data. This text string must be understood + by the application. Required attribute. + + + + + + + + + + + The source element declares a data repository that provides values according to the semantics of an + input element that refers to it. + + + + + + + + The source element may contain an asset element. + + + + + + + + The source element may contain an IDREF_array. + + + + + + + The source element may contain a Name_array. + + + + + + + The source element may contain a bool_array. + + + + + + + The source element may contain a float_array. + + + + + + + The source element may contain an int_array. + + + + + + + + The technique common specifies the common method for accessing this source element's data. + + + + + + + + The source's technique_common must have one and only one accessor. + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Required attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + Geometry describes the visual shape and appearance of an object in the scene. + The geometry element categorizes the declaration of geometric information. Geometry is a + branch of mathematics that deals with the measurement, properties, and relationships of + points, lines, angles, surfaces, and solids. + + + + + + + + The geometry element may contain an asset element. + + + + + + + + The geometry element may contain only one mesh or convex_mesh. + + + + + + + The geometry element may contain only one mesh or convex_mesh. + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The mesh element contains vertex and primitive information sufficient to describe basic geometric meshes. + + + + + + + + The mesh element must contain one or more source elements. + + + + + + + The mesh element must contain one vertices element. + + + + + + + + The mesh element may contain any number of lines elements. + + + + + + + The mesh element may contain any number of linestrips elements. + + + + + + + The mesh element may contain any number of polygons elements. + + + + + + + The mesh element may contain any number of polylist elements. + + + + + + + The mesh element may contain any number of triangles elements. + + + + + + + The mesh element may contain any number of trifans elements. + + + + + + + The mesh element may contain any number of tristrips elements. + + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The spline element contains control vertex information sufficient to describe basic splines. + + + + + + + + The mesh element must contain one or more source elements. + + + + + + The control vertices element must occur exactly one time. It is used to describe the CVs of the spline. + + + + + + + The input element must occur at least one time. These inputs are local inputs. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + + + + + The p element represents primitive data for the primitive types (lines, linestrips, polygons, + polylist, triangles, trifans, tristrips). The p element contains indices that reference into + the parent's source elements referenced by the input elements. + + + + + + + The lines element provides the information needed to bind vertex attributes together and then + organize those vertices into individual lines. Each line described by the mesh has two vertices. + The first line is formed from first and second vertices. The second line is formed from the + third and fourth vertices and so on. + + + + + + + + The input element may occur any number of times. This input is a local input with the offset + and set attributes. + + + + + + + The p element may occur once. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of line primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material at + the time of instantiation. If the material attribute is not specified then the lighting and + shading results are application defined. Optional attribute. + + + + + + + + + The linestrips element provides the information needed to bind vertex attributes together and + then organize those vertices into connected line-strips. Each line-strip described by the mesh + has an arbitrary number of vertices. Each line segment within the line-strip is formed from the + current vertex and the preceding vertex. + + + + + + + + The input element may occur any number of times. This input is a local input with the offset + and set attributes. + + + + + + + The linestrips element may have any number of p elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of linestrip primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material + at the time of instantiation. If the material attribute is not specified then the lighting + and shading results are application defined. Optional attribute. + + + + + + + + + The polygons element provides the information needed to bind vertex attributes together and + then organize those vertices into individual polygons. The polygons described can contain + arbitrary numbers of vertices. These polygons may be self intersecting and may also contain holes. + + + + + + + + The input element may occur any number of times. This input is a local input with the + offset and set attributes. + + + + + + + + The p element may occur any number of times. + + + + + + + The ph element describes a polygon with holes. + + + + + + + + Theere may only be one p element. + + + + + + + The h element represents a hole in the polygon specified. There must be at least one h element. + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of polygon primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material + at the time of instantiation. If the material attribute is not specified then the lighting + and shading results are application defined. Optional attribute. + + + + + + + + + The polylist element provides the information needed to bind vertex attributes together and + then organize those vertices into individual polygons. The polygons described in polylist can + contain arbitrary numbers of vertices. Unlike the polygons element, the polylist element cannot + contain polygons with holes. + + + + + + + + The input element may occur any number of times. This input is a local input with the + offset and set attributes. + + + + + + + The vcount element contains a list of integers describing the number of sides for each polygon + described by the polylist element. The vcount element may occur once. + + + + + + + The p element may occur once. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of polygon primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material at + the time of instantiation. If the material attribute is not specified then the lighting and + shading results are application defined. Optional attribute. + + + + + + + + + The triangles element provides the information needed to bind vertex attributes together and + then organize those vertices into individual triangles. Each triangle described by the mesh has + three vertices. The first triangle is formed from the first, second, and third vertices. The + second triangle is formed from the fourth, fifth, and sixth vertices, and so on. + + + + + + + + The input element may occur any number of times. This input is a local input with the + offset and set attributes. + + + + + + + The triangles element may have any number of p elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of triangle primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material at + the time of instantiation. Optional attribute. If the material attribute is not specified then + the lighting and shading results are application defined. + + + + + + + + + The trifans element provides the information needed to bind vertex attributes together and then + organize those vertices into connected triangles. Each triangle described by the mesh has three + vertices. The first triangle is formed from first, second, and third vertices. Each subsequent + triangle is formed from the current vertex, reusing the first and the previous vertices. + + + + + + + + The input element may occur any number of times. This input is a local input with the + offset and set attributes. + + + + + + + The trifans element may have any number of p elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of triangle fan primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material + at the time of instantiation. If the material attribute is not specified then the lighting + and shading results are application defined. Optional attribute. + + + + + + + + + The tristrips element provides the information needed to bind vertex attributes together and then + organize those vertices into connected triangles. Each triangle described by the mesh has three + vertices. The first triangle is formed from first, second, and third vertices. Each subsequent + triangle is formed from the current vertex, reusing the previous two vertices. + + + + + + + + The input element may occur any number of times. This input is a local input with the offset + and set attributes. + + + + + + + The tristrips element may have any number of p elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The count attribute indicates the number of triangle strip primitives. Required attribute. + + + + + + + The material attribute declares a symbol for a material. This symbol is bound to a material + at the time of instantiation. If the material attribute is not specified then the lighting + and shading results are application defined. Optional attribute. + + + + + + + + + The vertices element declares the attributes and identity of mesh-vertices. The vertices element + describes mesh-vertices in a mesh geometry. The mesh-vertices represent the position (identity) + of the vertices comprising the mesh and other vertex attributes that are invariant to tessellation. + + + + + + + + The input element must occur at least one time. These inputs are local inputs. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This + value must be unique within the instance document. Required attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + The lookat element contains a position and orientation transformation suitable for aiming a camera. + The lookat element contains three mathematical vectors within it that describe: + 1. The position of the object; + 2. The position of the interest point; + 3. The direction that points up. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + Matrix transformations embody mathematical changes to points within a coordinate systems or the + coordinate system itself. The matrix element contains a 4-by-4 matrix of floating-point values. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The rotate element contains an angle and a mathematical vector that represents the axis of rotation. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The scale element contains a mathematical vector that represents the relative proportions of the + X, Y and Z axes of a coordinated system. + + + + + + + The skew element contains an angle and two mathematical vectors that represent the axis of + rotation and the axis of translation. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The translate element contains a mathematical vector that represents the distance along the + X, Y and Z-axes. + + + + + + + + The image element declares the storage for the graphical representation of an object. + The image element best describes raster image data, but can conceivably handle other + forms of imagery. The image elements allows for specifying an external image file with + the init_from element or embed image data with the data element. + + + + + + + + The image element may contain an asset element. + + + + + + + + The data child element contains a sequence of hexadecimal encoded binary octets representing + the embedded image data. + + + + + + + The init_from element allows you to specify an external image file to use for the image element. + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The format attribute is a text string value that indicates the image format. Optional attribute. + + + + + + + The height attribute is an integer value that indicates the height of the image in pixel + units. Optional attribute. + + + + + + + The width attribute is an integer value that indicates the width of the image in pixel units. + Optional attribute. + + + + + + + The depth attribute is an integer value that indicates the depth of the image in pixel units. + A 2-D image has a depth of 1, which is also the default value. Optional attribute. + + + + + + + + + The light element declares a light source that illuminates the scene. + Light sources have many different properties and radiate light in many different patterns and + frequencies. + + + + + + + + The light element may contain an asset element. + + + + + + + The technique_common element specifies the light information for the common profile which all + COLLADA implementations need to support. + + + + + + + + The ambient element declares the parameters required to describe an ambient light source. + An ambient light is one that lights everything evenly, regardless of location or orientation. + + + + + + + + The color element contains three floating point numbers specifying the color of the light. + The color element must occur exactly once. + + + + + + + + + + The directional element declares the parameters required to describe a directional light source. + A directional light is one that lights everything from the same direction, regardless of location. + The light's default direction vector in local coordinates is [0,0,-1], pointing down the -Z axis. + The actual direction of the light is defined by the transform of the node where the light is + instantiated. + + + + + + + + The color element contains three floating point numbers specifying the color of the light. + The color element must occur exactly once. + + + + + + + + + + The point element declares the parameters required to describe a point light source. A point light + source radiates light in all directions from a known location in space. The intensity of a point + light source is attenuated as the distance to the light source increases. The position of the light + is defined by the transform of the node in which it is instantiated. + + + + + + + + The color element contains three floating point numbers specifying the color of the light. + The color element must occur exactly once. + + + + + + + The constant_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + The linear_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + The quadratic_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + + + + The spot element declares the parameters required to describe a spot light source. A spot light + source radiates light in one direction from a known location in space. The light radiates from + the spot light source in a cone shape. The intensity of the light is attenuated as the radiation + angle increases away from the direction of the light source. The intensity of a spot light source + is also attenuated as the distance to the light source increases. The position of the light is + defined by the transform of the node in which it is instantiated. The light's default direction + vector in local coordinates is [0,0,-1], pointing down the -Z axis. The actual direction of the + light is defined by the transform of the node where the light is instantiated. + + + + + + + + The color element contains three floating point numbers specifying the color of the light. + The color element must occur exactly once. + + + + + + + The constant_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + The linear_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + The quadratic_attenuation is used to calculate the total attenuation of this light given a distance. + The equation used is A = constant_attenuation + Dist*linear_attenuation + Dist^2*quadratic_attenuation. + + + + + + + The falloff_angle is used to specify the amount of attenuation based on the direction of the light. + + + + + + + The falloff_exponent is used to specify the amount of attenuation based on the direction of the light. + + + + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + Materials describe the visual appearance of a geometric object. + + + + + + + + The material element may contain an asset element. + + + + + + + The material must instance an effect. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + The camera element declares a view into the scene hierarchy or scene graph. The camera contains + elements that describe the camera's optics and imager. + + + + + + + + The camera element may contain an asset element. + + + + + + + Optics represents the apparatus on a camera that projects the image onto the image sensor. + + + + + + + + The technique_common element specifies the optics information for the common profile + which all COLLADA implementations need to support. + + + + + + + + The orthographic element describes the field of view of an orthographic camera. + + + + + + + + + + The xmag element contains a floating point number describing the horizontal + magnification of the view. + + + + + + + + The ymag element contains a floating point number describing the vertical + magnification of the view. It can also have a sid. + + + + + + + The aspect_ratio element contains a floating point number describing the aspect ratio of + the field of view. If the aspect_ratio element is not present the aspect ratio is to be + calculated from the xmag or ymag elements and the current viewport. + + + + + + + + + + + + + + The znear element contains a floating point number that describes the distance to the near + clipping plane. The znear element must occur exactly once. + + + + + + + The zfar element contains a floating point number that describes the distance to the far + clipping plane. The zfar element must occur exactly once. + + + + + + + + + + The perspective element describes the optics of a perspective camera. + + + + + + + + + + The xfov element contains a floating point number describing the horizontal field of view in degrees. + + + + + + + + The yfov element contains a floating point number describing the vertical field of view in degrees. + + + + + + + The aspect_ratio element contains a floating point number describing the aspect ratio of the field + of view. If the aspect_ratio element is not present the aspect ratio is to be calculated from the + xfov or yfov elements and the current viewport. + + + + + + + + + + + + + + The znear element contains a floating point number that describes the distance to the near + clipping plane. The znear element must occur exactly once. + + + + + + + The zfar element contains a floating point number that describes the distance to the far + clipping plane. The zfar element must occur exactly once. + + + + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + Imagers represent the image sensor of a camera (for example film or CCD). + + + + + + + + This element may contain any number of non-common profile techniques. + There is no common technique for imager. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + The animation element categorizes the declaration of animation information. The animation + hierarchy contains elements that describe the animation's key-frame data and sampler functions, + ordered in such a way to group together animations that should be executed together. + + + + + + + + The animation element may contain an asset element. + + + + + + + + + The animation element may contain any number of source elements. + + + + + + + + + The animation element may contain any number of sampler elements. + + + + + + + The animation element may contain any number of channel elements. + + + + + + + The animation may be hierarchical and may contain any number of other animation elements. + + + + + + + + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The animation_clip element defines a section of the animation curves to be used together as + an animation clip. + + + + + + + + The animation_clip element may contain an asset element. + + + + + + + The animation_clip must instance at least one animation element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The start attribute is the time in seconds of the beginning of the clip. This time is + the same as that used in the key-frame data and is used to determine which set of + key-frames will be included in the clip. The start time does not specify when the clip + will be played. If the time falls between two keyframes of a referenced animation, an + interpolated value should be used. The default value is 0.0. Optional attribute. + + + + + + + The end attribute is the time in seconds of the end of the clip. This is used in the + same way as the start time. If end is not specified, the value is taken to be the end + time of the longest animation. Optional attribute. + + + + + + + + + The channel element declares an output channel of an animation. + + + + + + + The source attribute indicates the location of the sampler using a URL expression. + The sampler must be declared within the same document. Required attribute. + + + + + + + The target attribute indicates the location of the element bound to the output of the sampler. + This text string is a path-name following a simple syntax described in Address Syntax. + Required attribute. + + + + + + + + + The sampler element declares an N-dimensional function used for animation. Animation function curves + are represented by 1-D sampler elements in COLLADA. The sampler defines sampling points and how to + interpolate between them. + + + + + + + + The input element must occur at least one time. These inputs are local inputs. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + + + + The controller element categorizes the declaration of generic control information. + A controller is a device or mechanism that manages and directs the operations of another object. + + + + + + + + The controller element may contain an asset element. + + + + + + + + The controller element may contain either a skin element or a morph element. + + + + + + + The controller element may contain either a skin element or a morph element. + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The skin element contains vertex and primitive information sufficient to describe blend-weight skinning. + + + + + + + + This provides extra information about the position and orientation of the base mesh before binding. + If bind_shape_matrix is not specified then an identity matrix may be used as the bind_shape_matrix. + The bind_shape_matrix element may occur zero or one times. + + + + + + + The skin element must contain at least three source elements. + + + + + + + The joints element associates joint, or skeleton, nodes with attribute data. + In COLLADA, this is specified by the inverse bind matrix of each joint (influence) in the skeleton. + + + + + + + + The input element must occur at least twice. These inputs are local inputs. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The vertex_weights element associates a set of joint-weight pairs with each vertex in the base mesh. + + + + + + + + The input element must occur at least twice. + + + + + + + The vcount element contains a list of integers describing the number of influences for each vertex. + The vcount element may occur once. + + + + + + + The v element describes which bones and attributes are associated with each vertex. An index + of -1 into the array of joints refers to the bind shape. Weights should be normalized before use. + The v element must occur zero or one times. + + + + + + + The extra element may appear any number of times. + + + + + + + + The count attribute describes the number of vertices in the base mesh. Required element. + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The source attribute contains a URI reference to the base mesh, (a static mesh or a morphed mesh). + This also provides the bind-shape of the skinned mesh. Required attribute. + + + + + + + + + The morph element describes the data required to blend between sets of static meshes. Each + possible mesh that can be blended (a morph target) must be specified. + + + + + + + + The morph element must contain at least two source elements. + + + + + + + The targets element declares the morph targets, their weights and any user defined attributes + associated with them. + + + + + + + + The input element must occur at least twice. These inputs are local inputs. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The method attribute specifies the which blending technique to use. The accepted values are + NORMALIZED, and RELATIVE. The default value if not specified is NORMALIZED. Optional attribute. + + + + + + + The source attribute indicates the base mesh. Required attribute. + + + + + + + + + + The asset element defines asset management information regarding its parent element. + + + + + + + + The contributor element defines authoring information for asset management + + + + + + + + The author element contains a string with the author's name. + There may be only one author element. + + + + + + + The authoring_tool element contains a string with the authoring tool's name. + There may be only one authoring_tool element. + + + + + + + The comments element contains a string with comments from this contributor. + There may be only one comments element. + + + + + + + The copyright element contains a string with copyright information. + There may be only one copyright element. + + + + + + + The source_data element contains a URI reference to the source data used for this asset. + There may be only one source_data element. + + + + + + + + + + The created element contains the date and time that the parent element was created and is + represented in an ISO 8601 format. The created element may appear zero or one time. + + + + + + + The keywords element contains a list of words used as search criteria for the parent element. + The keywords element may appear zero or more times. + + + + + + + The modified element contains the date and time that the parent element was last modified and + represented in an ISO 8601 format. The modified element may appear zero or one time. + + + + + + + The revision element contains the revision information for the parent element. The revision + element may appear zero or one time. + + + + + + + The subject element contains a description of the topical subject of the parent element. The + subject element may appear zero or one time. + + + + + + + The title element contains the title information for the parent element. The title element may + appear zero or one time. + + + + + + + The unit element contains descriptive information about unit of measure. It has attributes for + the name of the unit and the measurement with respect to the meter. The unit element may appear + zero or one time. + + + + + + + The meter attribute specifies the measurement with respect to the meter. The default + value for the meter attribute is "1.0". + + + + + + + The name attribute specifies the name of the unit. The default value for the name + attribute is "meter". + + + + + + + + + The up_axis element contains descriptive information about coordinate system of the geometric + data. All coordinates are right-handed by definition. This element specifies which axis is + considered up. The default is the Y-axis. The up_axis element may appear zero or one time. + + + + + + + + + + The extra element declares additional information regarding its parent element. + + + + + + + + The extra element may contain an asset element. + + + + + + + This element must contain at least one non-common profile technique. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The type attribute indicates the type of the value data. This text string must be understood by + the application. Optional attribute. + + + + + + + + enable-xmlns + + The technique element declares the information used to process some portion of the content. Each + technique conforms to an associated profile. Techniques generally act as a "switch". If more than + one is present for a particular portion of content, on import, one or the other is picked, but + usually not both. Selection should be based on which profile the importing application can support. + Techniques contain application data and programs, making them assets that can be managed as a unit. + + + + + + + + + + The profile attribute indicates the type of profile. This is a vendor defined character + string that indicates the platform or capability target for the technique. Required attribute. + + + + + + + + + + Nodes embody the hierarchical relationship of elements in the scene. + + + + + + + + The node element may contain an asset element. + + + + + + + + The node element may contain any number of lookat elements. + + + + + + + The node element may contain any number of matrix elements. + + + + + + + The node element may contain any number of rotate elements. + + + + + + + The node element may contain any number of scale elements. + + + + + + + The node element may contain any number of skew elements. + + + + + + + The node element may contain any number of translate elements. + + + + + + + + The node element may instance any number of camera objects. + + + + + + + The node element may instance any number of controller objects. + + + + + + + The node element may instance any number of geometry objects. + + + + + + + The node element may instance any number of light objects. + + + + + + + The node element may instance any number of node elements or hierarchies objects. + + + + + + + The node element may be hierarchical and be the parent of any number of other node elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The type attribute indicates the type of the node element. The default value is "NODE". + Optional attribute. + + + + + + + The layer attribute indicates the names of the layers to which this node belongs. For example, + a value of "foreground glowing" indicates that this node belongs to both the 'foreground' layer + and the 'glowing' layer. The default value is empty, indicating that the node doesn't belong to + any layer. Optional attribute. + + + + + + + + + The visual_scene element declares the base of the visual_scene hierarchy or scene graph. The + scene contains elements that comprise much of the visual and transformational information + content as created by the authoring tools. + + + + + + + + The visual_scene element may contain an asset element. + + + + + + + The visual_scene element must have at least one node element. + + + + + + + The evaluate_scene element declares information specifying a specific way to evaluate this + visual_scene. There may be any number of evaluate_scene elements. + + + + + + + + The render element describes one effect pass to evaluate the scene. + There must be at least one render element. + + + + + + + + The layer element specifies which layer to render in this compositing step + while evaluating the scene. You may specify any number of layers. + + + + + + + The instance_effect element specifies which effect to render in this compositing step + while evaluating the scene. + + + + + + + + The camera_node attribute refers to a node that contains a camera describing the viewpoint to + render this compositing step from. + + + + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This + value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + Bind a specific material to a piece of geometry, binding varying and uniform parameters at the + same time. + + + + + + + + The bind_material element may contain any number of param elements. + + + + + + + The technique_common element specifies the bind_material information for the common + profile which all COLLADA implementations need to support. + + + + + + + + The instance_material element specifies the information needed to bind a geometry + to a material. This element must appear at least once. + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The instance_camera element declares the instantiation of a COLLADA camera resource. + + + + + + + The instance_controller element declares the instantiation of a COLLADA controller resource. + + + + + + + + The skeleton element is used to indicate where a skin controller is to start to search for + the joint nodes it needs. This element is meaningless for morph controllers. + + + + + + + Bind a specific material to a piece of geometry, binding varying and uniform parameters at the + same time. + + + + + + + The extra element may appear any number of times. + + + + + + + + The url attribute refers to resource. This may refer to a local resource using a relative + URL fragment identifier that begins with the "#" character. The url attribute may refer to an + external resource using an absolute or relative URL. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The instance_effect element declares the instantiation of a COLLADA effect resource. + + + + + + + + Add a hint for a platform of which technique to use in this effect. + + + + + + + A platform defines a string that specifies which platform this is hint is aimed for. + + + + + + + A profile defines a string that specifies which API profile this is hint is aimed for. + + + + + + + A reference to the technique to use for the specified platform. + + + + + + + + + Assigns a new value to a previously defined parameter + + + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The url attribute refers to resource. This may refer to a local resource using a relative URL + fragment identifier that begins with the "#" character. The url attribute may refer to an external + resource using an absolute or relative URL. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The instance_force_field element declares the instantiation of a COLLADA force_field resource. + + + + + + + The instance_geometry element declares the instantiation of a COLLADA geometry resource. + + + + + + + + Bind a specific material to a piece of geometry, binding varying and uniform parameters at the + same time. + + + + + + + The extra element may appear any number of times. + + + + + + + + The url attribute refers to resource. This may refer to a local resource using a relative URL + fragment identifier that begins with the "#" character. The url attribute may refer to an external + resource using an absolute or relative URL. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The instance_light element declares the instantiation of a COLLADA light resource. + + + + + + + The instance_material element declares the instantiation of a COLLADA material resource. + + + + + + + + The bind element binds values to effect parameters upon instantiation. + + + + + + + The semantic attribute specifies which effect parameter to bind. + + + + + + + The target attribute specifies the location of the value to bind to the specified semantic. + This text string is a path-name following a simple syntax described in the "Addressing Syntax" + section. + + + + + + + + + The bind_vertex_input element binds vertex inputs to effect parameters upon instantiation. + + + + + + + The semantic attribute specifies which effect parameter to bind. + + + + + + + The input_semantic attribute specifies which input semantic to bind. + + + + + + + The input_set attribute specifies which input set to bind. + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The symbol attribute specifies which symbol defined from within the geometry this material binds to. + + + + + + + The target attribute specifies the URL of the location of the object to instantiate. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The instance_node element declares the instantiation of a COLLADA node resource. + + + + + + + The instance_physics_material element declares the instantiation of a COLLADA physics_material + resource. + + + + + + + This element allows instancing physics model within another physics model, or in a physics scene. + + + + + + + + The instance_physics_model element may instance any number of force_field elements. + + + + + + + The instance_physics_model element may instance any number of rigid_body elements. + + + + + + + The instance_physics_model element may instance any number of rigid_constraint elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The url attribute refers to resource. This may refer to a local resource using a relative URL + fragment identifier that begins with the "#" character. The url attribute may refer to an external + resource using an absolute or relative URL. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The parent attribute points to the id of a node in the visual scene. This allows a physics model + to be instantiated under a specific transform node, which will dictate the initial position and + orientation, and could be animated to influence kinematic rigid bodies. + + + + + + + + + This element allows instancing a rigid_body within an instance_physics_model. + + + + + + + + The technique_common element specifies the instance_rigid_body information for the common + profile which all COLLADA implementations need to support. + + + + + + + + Specifies the initial angular velocity of the rigid_body instance in degrees per second + around each axis, in the form of an X-Y-Z Euler rotation. + + + + + + + Specifies the initial linear velocity of the rigid_body instance. + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The body attribute indicates which rigid_body to instantiate. Required attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + The target attribute indicates which node is influenced by this rigid_body instance. + Required attribute + + + + + + + + + This element allows instancing a rigid_constraint within an instance_physics_model. + + + + + + + + The extra element may appear any number of times. + + + + + + + + The constraint attribute indicates which rigid_constraing to instantiate. Required attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + The library_animations element declares a module of animation elements. + + + + + + + + The library_animations element may contain an asset element. + + + + + + + There must be at least one animation element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_animation_clips element declares a module of animation_clip elements. + + + + + + + + The library_animation_clips element may contain an asset element. + + + + + + + There must be at least one animation_clip element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_cameras element declares a module of camera elements. + + + + + + + + The library_cameras element may contain an asset element. + + + + + + + There must be at least one camera element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_controllers element declares a module of controller elements. + + + + + + + + The library_controllers element may contain an asset element. + + + + + + + There must be at least one controller element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_geometries element declares a module of geometry elements. + + + + + + + + The library_geometries element may contain an asset element. + + + + + + + There must be at least one geometry element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_effects element declares a module of effect elements. + + + + + + + + The library_effects element may contain an asset element. + + + + + + + There must be at least one effect element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_force_fields element declares a module of force_field elements. + + + + + + + + The library_force_fields element may contain an asset element. + + + + + + + There must be at least one force_field element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_images element declares a module of image elements. + + + + + + + + The library_images element may contain an asset element. + + + + + + + There must be at least one image element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_lights element declares a module of light elements. + + + + + + + + The library_lights element may contain an asset element. + + + + + + + There must be at least one light element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_materials element declares a module of material elements. + + + + + + + + The library_materials element may contain an asset element. + + + + + + + There must be at least one material element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_nodes element declares a module of node elements. + + + + + + + + The library_nodes element may contain an asset element. + + + + + + + There must be at least one node element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_physics_materials element declares a module of physics_material elements. + + + + + + + + The library_physics_materials element may contain an asset element. + + + + + + + There must be at least one physics_material element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_physics_models element declares a module of physics_model elements. + + + + + + + + The library_physics_models element may contain an asset element. + + + + + + + There must be at least one physics_model element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_physics_scenes element declares a module of physics_scene elements. + + + + + + + + The library_physics_scenes element may contain an asset element. + + + + + + + There must be at least one physics_scene element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + The library_visual_scenes element declares a module of visual_scene elements. + + + + + + + + The library_visual_scenes element may contain an asset element. + + + + + + + There must be at least one visual_scene element. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + + + + + + + + When a transparent opaque attribute is set to A_ONE, it means the transparency information will be taken from the alpha channel of the color, texture, or parameter supplying the value. The value of 1.0 is opaque in this mode. + + + + + + + When a transparent opaque attribute is set to RGB_ZERO, it means the transparency information will be taken from the red, green, and blue channels of the color, texture, or parameter supplying the value. Each channel is modulated independently. The value of 0.0 is opaque in this mode. + + + + + + + + + + + When a surface's type attribute is set to UNTYPED, its type is initially unknown and established later by the context in which it is used, such as by a texture sampler that references it. A surface of any other type may be changed into an UNTYPED surface at run-time, as if it were created by <newparam>, using <setparam>. If there is a type mismatch between a <setparam> operation and what the run-time decides the type should be, the result is profile- and platform-specific behavior. + + + + + + + + + + + + + + + + + + + + + + + + The per-texel layout of the format. The length of the string indicate how many channels there are and the letter respresents the name of the channel. There are typically 0 to 4 channels. + + + + + RGB color map + + + + + RGB color + Alpha map often used for color + transparency or other things packed into channel A like specular power + + + + + Luminance map often used for light mapping + + + + + Luminance+Alpha map often used for light mapping + + + + + Depth map often used for displacement, parellax, relief, or shadow mapping + + + + + Typically used for normal maps or 3component displacement maps. + + + + + Typically used for normal maps where W is the depth for relief or parrallax mapping + + + + + + + Each channel of the texel has a precision. Typically these are all linked together. An exact format lay lower the precision of an individual channel but applying a higher precision by linking the channels together may still convey the same information. + + + + + For integers this typically represents 8 bits. For floats typically 16 bits. + + + + + For integers this typically represents 8 to 24 bits. For floats typically 16 to 32 bits. + + + + + For integers this typically represents 16 to 32 bits. For floats typically 24 to 32 bits. + + + + + + + Each channel represents a range of values. Some example ranges are signed or unsigned integers, or between between a clamped range such as 0.0f to 1.0f, or high dynamic range via floating point + + + + + Format is representing a decimal value that remains within the -1 to 1 range. Implimentation could be integer-fixedpoint or floats. + + + + + Format is representing a decimal value that remains within the 0 to 1 range. Implimentation could be integer-fixedpoint or floats. + + + + + Format is representing signed integer numbers. (ex. 8bits = -128 to 127) + + + + + Format is representing unsigned integer numbers. (ex. 8bits = 0 to 255) + + + + + Format should support full floating point ranges. High precision is expected to be 32bit. Mid precision may be 16 to 32 bit. Low precision is expected to be 16 bit. + + + + + + + Additional hints about data relationships and other things to help the application pick the best format. + + + + + colors are stored with respect to the sRGB 2.2 gamma curve rather than linear + + + + + the texel's XYZ/RGB should be normalized such as in a normal map. + + + + + the texel's XYZW/RGBA should be normalized such as in a normal map. + + + + + The surface may use run-time compression. Considering the best compression based on desired, channel, range, precision, and options + + + + + + + If the exact format cannot be resolve via other methods then the format_hint will describe the important features of the format so that the application may select a compatible or close format + + + + + The per-texel layout of the format. The length of the string indicate how many channels there are and the letter respresents the name of the channel. There are typically 0 to 4 channels. + + + + + Each channel represents a range of values. Some example ranges are signed or unsigned integers, or between between a clamped range such as 0.0f to 1.0f, or high dynamic range via floating point + + + + + Each channel of the texel has a precision. Typically these are all linked together. An exact format lay lower the precision of an individual channel but applying a higher precision by linking the channels together may still convey the same information. + + + + + Additional hints about data relationships and other things to help the application pick the best format. + + + + + + + + For 1D, 2D, RECT surface types + + + + This choice exists for consistency with other init types (volume and cube). When other initialization methods are needed. + + + + Init the entire surface with one compound image such as DDS + + + + + + + + + + + + Init the entire surface with one compound image such as DDS + + + + + + + + Init mip level 0 of the surface with one compound image such as DDS. Use of this element expects that the surface has element mip_levels=0 or mipmap_generate. + + + + + + + + + + + + Init the entire surface with one compound image such as DDS + + + + + + + + Init all primary mip level 0 subsurfaces with one compound image such as DDS. Use of this element expects that the surface has element mip_levels=0 or mipmap_generate. + + + + + This sequence exists to allow the order elements to be optional but require that if they exist there must be 6 of them. + + + + If the image dues not natively describe the face ordering then this series of order elements will describe which face the index belongs too + + + + + + + + + Init each face mipchain with one compound image such as DDS + + + + + + + + + + + This element is an IDREF which specifies the image to use to initialize a specific mip of a 1D or 2D surface, 3D slice, or Cube face. + + + + + + + + + + + + + The common set of initialization options for surfaces. Choose which is appropriate for your surface based on type and other characteristics. described by the annotation docs on the child elements. + + + + + This surface is intended to be initialized later externally by a "setparam" element. If it is used before being initialized there is profile and platform specific behavior. Most elements on the surface element containing this will be ignored including mip_levels, mipmap_generate, size, viewport_ratio, and format. + + + + + Init as a target for depth, stencil, or color. It does not need image data. Surface should not have mipmap_generate when using this. + + + + + Init a CUBE from a compound image such as DDS + + + + + Init a 3D from a compound image such as DDS + + + + + Init a 1D,2D,RECT,DEPTH from a compound image such as DDS + + + + + Initialize the surface one sub-surface at a time by specifying combinations of mip, face, and slice which make sense for a particular surface type. Each sub-surface is initialized by a common 2D image, not a complex compound image such as DDS. If not all subsurfaces are initialized, it is invalid and will result in profile and platform specific behavior unless mipmap_generate is responsible for initializing the remainder of the sub-surfaces + + + + + + + + The fx_surface_common type is used to declare a resource that can be used both as the source for texture samples and as the target of a rendering pass. + + + + + + The common set of initialization options for surfaces. Choose which is appropriate for your surface based on the type attribute and other characteristics described by the annotation docs on the choiced child elements of this type. + + + + + Contains a string representing the profile and platform specific texel format that the author would like this surface to use. If this element is not specified then the application will use a common format R8G8B8A8 with linear color gradient, not sRGB. + + + + + If the exact format cannot be resolved via the "format" element then the format_hint will describe the important features of the format so that the application may select a compatible or close format + + + + + + The surface should be sized to these exact dimensions + + + + + The surface should be sized to a dimension based on this ratio of the viewport's dimensions in pixels + + + + + + the surface should contain the following number of MIP levels. If this element is not present it is assumed that all miplevels exist until a dimension becomes 1 texel. To create a surface that has only one level of mip maps (mip=0) set this to 1. If the value is 0 the result is the same as if mip_levels was unspecified, all possible mip_levels will exist. + + + + + By default it is assumed that mipmaps are supplied by the author so, if not all subsurfaces are initialized, it is invalid and will result in profile and platform specific behavior unless mipmap_generate is responsible for initializing the remainder of the sub-surfaces + + + + + + + Specifying the type of a surface is mandatory though the type may be "UNTYPED". When a surface is typed as UNTYPED, it is said to be temporarily untyped and instead will be typed later by the context it is used in such as which samplers reference it in that are used in a particular technique or pass. If there is a type mismatch between what is set into it later and what the runtime decides the type should be the result in profile and platform specific behavior. + + + + + + + + + + + + + + + + + + + + + + + + + + + A one-dimensional texture sampler. + + + + + + + + + + + + + + + + + + A two-dimensional texture sampler. + + + + + + + + + + + + + + + + + + + A three-dimensional texture sampler. + + + + + + + + + + + + + + + + + + + + A texture sampler for cube maps. + + + + + + + + + + + + + + + + + + + + A two-dimensional texture sampler. + + + + + + + + + + + + + + + + + + + A texture sampler for depth maps. + + + + + + + + + + + + + + + A group that specifies the allowable types for an annotation. + + + + + + + + + + + + + + + + + + + + + + + + + A group that specifies the allowable types for effect scoped parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The include element is used to import source code or precompiled binary shaders into the FX Runtime by referencing an external resource. + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The url attribute refers to resource. This may refer to a local resource using a relative URL + fragment identifier that begins with the "#" character. The url attribute may refer to an external + resource using an absolute or relative URL. + + + + + + + + This element creates a new, named param object in the FX Runtime, assigns it a type, an initial value, and additional attributes at declaration time. + + + + + + + The annotate element allows you to specify an annotation for this new param. + + + + + + + The semantic element allows you to specify a semantic for this new param. + + + + + + + The modifier element allows you to specify a modifier for this new param. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The fx_code_profile type allows you to specify an inline block of source code. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + + The fx_profile_abstract element is only used as a substitution group hook for COLLADA FX profiles. + + + + + + + A self contained description of a shader effect. + + + + + + + + The effect element may contain an asset element. + + + + + + + The annotate element allows you to specify an annotation on this effect. + + + + + + + The image element allows you to create image resources which can be shared by multiple profiles. + + + + + + + The newparam element allows you to create new effect parameters which can be shared by multiple profiles. + + + + + + + This is the substitution group hook which allows you to swap in other COLLADA FX profiles. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + A one-dimensional texture sampler for the GLSL profile. + + + + + + + + + + A two-dimensional texture sampler for the GLSL profile. + + + + + + + + + + A three-dimensional texture sampler for the GLSL profile. + + + + + + + + + + A cube map texture sampler for the GLSL profile. + + + + + + + + + + A two-dimensional texture sampler for the GLSL profile. + + + + + + + + + + A depth texture sampler for the GLSL profile. + + + + + + + + + + + value=0x0 + + + + + value=0x1 + + + + + value=0x0300 + + + + + value=0x0301 + + + + + value=0x0306 + + + + + value=0x0307 + + + + + value=0x0302 + + + + + value=0x0303 + + + + + value=0x0304 + + + + + value=0x0305 + + + + + value=0x8001 + + + + + value=0x8002 + + + + + value=0x8003 + + + + + value=0x8004 + + + + + value=0x0308 + + + + + + + + + value=0x0404 + + + + + value=0x0405 + + + + + value=0x0408 + + + + + + + + + value=0x8006 + + + + + value=0x800A + + + + + value=0x800B + + + + + value=0x8007 + + + + + value=0x8008 + + + + + + + + + value=0x0200 + + + + + value=0x0201 + + + + + value=0x0203 + + + + + value=0x0202 + + + + + value=0x0204 + + + + + value=0x0205 + + + + + value=0x0206 + + + + + value=0x0207 + + + + + + + + + value=0x1E00 + + + + + value=0x0 + + + + + value=0x1E01 + + + + + value=0x1E02 + + + + + value=0x1E03 + + + + + value=0x150A + + + + + value=0x8507 + + + + + value=0x8508 + + + + + + + + + value=0x1600 + + + + + value=0x1200 + + + + + value=0x1201 + + + + + value=0x1202 + + + + + value=0x1602 + + + + + + + + + value=0x2601 + + + + + value=0x0800 + + + + + value=0x0801 + + + + + + + + + value=0x8451 + + + + + value=0x8452 + + + + + + + + + value=0x0900 + + + + + value=0x0901 + + + + + + + + + value=0x81F9 + + + + + value=0x81FA + + + + + + + + + value=0x1500 + + + + + value=0x1501 + + + + + value=0x1502 + + + + + value=0x1503 + + + + + value=0x1504 + + + + + value=0x1505 + + + + + value=0x1506 + + + + + value=0x1507 + + + + + value=0x1508 + + + + + value=0x1509 + + + + + value=0x150A + + + + + value=0x150B + + + + + value=0x150C + + + + + value=0x150E + + + + + value=0x150F + + + + + + + + + value=0x1B00 + + + + + value=0x1B01 + + + + + value=0x1B02 + + + + + + + + + value=0x1D00 + + + + + value=0x1D01 + + + + + + + + + + + + + + + + + A group that defines all of the renderstates used for the CG and GLSL profiles. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The glsl_newarray_type is used to creates a parameter of a one-dimensional array type. + + + + + + + + You may recursively nest glsl_newarray elements to create multidimensional arrays. + + + + + + + + The length attribute specifies the length of the array. + + + + + + + + The glsl_newarray_type is used to creates a parameter of a one-dimensional array type. + + + + + + + + You may recursively nest glsl_newarray elements to create multidimensional arrays. + + + + + + + + The length attribute specifies the length of the array. + + + + + + + + A surface type for the GLSL profile. This surface inherits from the fx_surface_common type and adds the + ability to programmatically generate textures. + + + + + + + + + A procedural surface generator. + + + + + + + + The annotate element allows you to specify an annotation for this surface generator. + + + + + + + + The code element allows you to embed GLSL code to use for this surface generator. + + + + + + + The include element allows you to import GLSL code to use for this surface generator. + + + + + + + + The entry symbol for the shader function. + + + + + + + + + + + + + + The setparam element allows you to assign a new value to a previously defined parameter. + + + + + + + + + + + + + + A group that specifies the allowable types for GLSL profile parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Opens a block of GLSL platform-specific data types and technique declarations. + + + + + + + + + + + + + + + + + Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method. + + + + + + + + + + + + + + + + + + A static declaration of all the render states, shaders, and settings for one rendering pipeline. + + + + + + + + + + + + + + + + + + Declare and prepare a shader for execution in the rendering pipeline of a pass. + + + + + + + + + + A string declaring which profile or platform the compiler is targeting this shader for. + + + + + + + + + + + + A string containing command-line operations for the shader compiler. + + + + + + + + The entry symbol for the shader function. + + + + + + + + + + + + + + Binds values to uniform inputs of a shader. + + + + + + + + + + + + + + + The identifier for a uniform input parameter to the shader (a formal function parameter or in-scope + global) that will be bound to an external resource. + + + + + + + + + + In which pipeline stage this programmable shader is designed to execute, for example, VERTEX, FRAGMENT, etc. + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + Opens a block of COMMON platform-specific data types and technique declarations. + + + + + + + + + + + + + Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method. + + + + + + + + The technique element may contain an asset element. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Creates a symbolic connection between two previously defined parameters. + + + + + + + + Creates a parameter of a one-dimensional array type. + + + + + + + + Nested array elements allow you to create multidemensional arrays. + + + + + + + The usertype element allows you to create arrays of usertypes. + + + + + + + + + The length attribute specifies the length of the array. + + + + + + + + Creates a parameter of a one-dimensional array type. + + + + + + + + Nested array elements allow you to create multidemensional arrays. + + + + + + + The usertype element allows you to create arrays of usertypes. + + + + + + + + The length attribute specifies the length of the array. + + + + + + + + Creates an instance of a structured class. + + + + + Some usertypes do not have data. They may be used only to implement interface functions. + + + + Use a combination of these to initialize the usertype in an order-dependent manner. + + + + + + + + + Use a series of these to set the members by name. The ref attribute will be relative to the usertype you are in right now. + + + + + + + + Reference a code or include element which defines the usertype + + + + + + + + Declares a resource that can be used both as the source for texture samples and as the target of a rendering pass. + + + + + + + + + A procedural surface generator for the cg profile. + + + + + + + + The annotate element allows you to specify an annotation for this generator. + + + + + + + + The code element allows you to embed cg sourcecode for the surface generator. + + + + + + + The include element imports cg source code or precompiled binary shaders into the FX Runtime by referencing an external resource. + + + + + + + + The entry symbol for the shader function. + + + + + + + + + + + + + + Assigns a new value to a previously defined parameter. + + + + + + + + + + + + + + A group that specifies the allowable types for CG profile parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create a new, named param object in the CG Runtime, assign it a type, an initial value, and additional attributes at declaration time. + + + + + + + The annotate element allows you to specify an annotation for this new param. + + + + + + + The semantic element allows you to specify a semantic for this new param. + + + + + + + The modifier element allows you to specify a modifier for this new param. + + + + + + + + + + + + + + + + + + + + + + Assigns a new value to a previously defined parameter. + + + + + + + + + + + + + + + Opens a block of CG platform-specific data types and technique declarations. + + + + + + + + + + + + + + + + + Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method. + + + + + + + + The technique element may contain an asset element. + + + + + + + + + + + + + + + + + A static declaration of all the render states, shaders, and settings for one rendering pipeline. + + + + + + + + + + + + + + + + + + Declare and prepare a shader for execution in the rendering pipeline of a pass. + + + + + + + + + + + + + + + + + A string containing command-line operations for the shader compiler. + + + + + + + + The entry symbol for the shader function. + + + + + + + + + + + + + + Binds values to uniform inputs of a shader. + + + + + + + + + References a predefined parameter in shader binding declarations. + + + + + + + + + + + The identifier for a uniform input parameter to the shader (a formal function parameter or in-scope + global) that will be bound to an external resource. + + + + + + + + + + In which pipeline stage this programmable shader is designed to execute, for example, VERTEX, FRAGMENT, etc. + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The type of platform. This is a vendor-defined character string that indicates the platform or capability target for the technique. Optional + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + value=0x1E01 + + + + + value=0x2100 + + + + + value=0x2101 + + + + + value=0x0BE2 + + + + + value=0x0104 + + + + + + + + + + + + + + + + + + + + value=0x1E01 + + + + + value=0x2100 + + + + + value=0x0104 + + + + + value=0x8574 + + + + + value=0x8575 + + + + + value=0x84E7 + + + + + value=0x86AE + + + + + value=0x86AF + + + + + + + + + value=0x1E01 + + + + + value=0x2100 + + + + + value=0x0104 + + + + + value=0x8574 + + + + + value=0x8575 + + + + + value=0x84E7 + + + + + + + + + value=0x1702 + + + + + value=0x8576 + + + + + value=0x8577 + + + + + value=0x8578 + + + + + + + + + value=0x0300 + + + + + value=0x0301 + + + + + value=0x0302 + + + + + value=0x0303 + + + + + + + + + value=0x0302 + + + + + value=0x0303 + + + + + + + + + + + + + + + + + + + + + + + + Defines the RGB portion of a texture_pipeline command. This is a combiner-mode texturing operation. + + + + + + + + + + + + + + + + + + + + + + + + + + Defines a set of texturing commands that will be converted into multitexturing operations using glTexEnv in regular and combiner mode. + + + + + + + Defines a texture_pipeline command. This is a combiner-mode texturing operation. + + + + + + + Defines a texture_pipeline command. It is a simple noncombiner mode of texturing operations. + + + + + + + The extra element may appear any number of times. + OpenGL ES extensions may be used here. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + + supported by GLES 1.1 only + + + + + + + + + Two-dimensional texture sampler state for profile_GLES. This is a bundle of sampler-specific states that will be referenced by one or more texture_units. + + + + + + + + + + + + + + + The extra element may appear any number of times. + OpenGL ES extensions may be used here. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + value=0x1E00 + + + + + value=0x0 + + + + + value=0x1E01 + + + + + value=0x1E02 + + + + + value=0x1E03 + + + + + value=0x150A + + + + + + + + + + + A group that contains the renderstates available for the GLES profile. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + A group that defines the available variable types for GLES parameters. + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Create a new, named param object in the GLES Runtime, assign it a type, an initial value, and additional attributes at declaration time. + + + + + + + The annotate element allows you to specify an annotation for this new param. + + + + + + + The semantic element allows you to specify a semantic for this new param. + + + + + + + The modifier element allows you to specify a modifier for this new param. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. + + + + + + + + + + + Opens a block of GLES platform-specific data types and technique declarations. + + + + + + + + + + + + + Holds a description of the textures, samplers, shaders, parameters, and passes necessary for rendering this effect using one method. + + + + + + + + + + + + + + + + + + + + + + + A static declaration of all the render states, shaders, and settings for one rendering pipeline. + + + + + + + + + + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. + + + + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The type of platform. This is a vendor-defined character string that indicates the platform or capability target for the technique. Optional + + + + + + + + + + + An axis-aligned, centered box primitive. + + + + + + + + 3 float values that represent the extents of the box + + + + + + + The extra element may appear any number of times. + + + + + + + + + + An infinite plane primitive. + + + + + + + + 4 float values that represent the coefficients for the plane's equation: Ax + By + Cz + D = 0 + + + + + + + The extra element may appear any number of times. + + + + + + + + + + A centered sphere primitive. + + + + + + + + A float value that represents the radius of the sphere + + + + + + + The extra element may appear any number of times. + + + + + + + + + + + + + + + + + A cylinder primitive that is centered on, and aligned with. the local Y axis. + + + + + + + + A float value that represents the length of the cylinder along the Y axis. + + + + + + + float2 values that represent the radii of the cylinder. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + A tapered cylinder primitive that is centered on and aligned with the local Y axis. + + + + + + + + A float value that represents the length of the cylinder along the Y axis. + + + + + + + Two float values that represent the radii of the tapered cylinder at the positive (height/2) + Y value. Both ends of the tapered cylinder may be elliptical. + + + + + + + Two float values that represent the radii of the tapered cylinder at the negative (height/2) + Y value.Both ends of the tapered cylinder may be elliptical. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + A capsule primitive that is centered on and aligned with the local Y axis. + + + + + + + + A float value that represents the length of the line segment connecting the centers + of the capping hemispheres. + + + + + + + Two float values that represent the radii of the capsule (it may be elliptical) + + + + + + + The extra element may appear any number of times. + + + + + + + + + + A tapered capsule primitive that is centered on, and aligned with, the local Y axis. + + + + + + + + A float value that represents the length of the line segment connecting the centers of the + capping hemispheres. + + + + + + + Two float values that represent the radii of the tapered capsule at the positive (height/2) + Y value.Both ends of the tapered capsule may be elliptical. + + + + + + + Two float values that represent the radii of the tapered capsule at the negative (height/2) + Y value.Both ends of the tapered capsule may be elliptical. + + + + + + + The extra element may appear any number of times. + + + + + + + + + + The definition of the convex_mesh element is identical to the mesh element with the exception that + instead of a complete description (source, vertices, polygons etc.), it may simply point to another + geometry to derive its shape. The latter case means that the convex hull of that geometry should + be computed and is indicated by the optional "convex_hull_of" attribute. + + + + + + + + + + + + + + + + + + + The extra element may appear any number of times. + + + + + + + + The convex_hull_of attribute is a URI string of geometry to compute the convex hull of. + Optional attribute. + + + + + + + + + + A general container for force-fields. At the moment, it only has techniques and extra elements. + + + + + + + + The force_field element may contain an asset element. + + + + + + + This element must contain at least one non-common profile technique. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. This value + must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + This element defines the physical properties of an object. It contains a technique/profile with + parameters. The COMMON profile defines the built-in names, such as static_friction. + + + + + + + + The physics_material element may contain an asset element. + + + + + + + The technique_common element specifies the physics_material information for the common profile + which all COLLADA implementations need to support. + + + + + + + + Dynamic friction coefficient + + + + + + + The proportion of the kinetic energy preserved in the impact (typically ranges from 0.0 to 1.0) + + + + + + + Static friction coefficient + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + + + The physics_scene element may contain an asset element. + + + + + + + There may be any number of instance_force_field elements. + + + + + + + There may be any number of instance_physics_model elements. + + + + + + + The technique_common element specifies the physics_scene information for the common profile + which all COLLADA implementations need to support. + + + + + + + + The gravity vector to use for the physics_scene. + + + + + + + The time_step for the physics_scene. + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + + + + + + + This element allows for describing simulated bodies that do not deform. These bodies may or may + not be connected by constraints (hinge, ball-joint etc.). Rigid-bodies, constraints etc. are + encapsulated in physics_model elements to allow for instantiating complex models. + + + + + + + + The technique_common element specifies the rigid_body information for the common profile which all + COLLADA implementations need to support. + + + + + + + + If false, the rigid_body is not moveable + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The total mass of the rigid-body + + + + + + + Defines the center and orientation of mass of the rigid-body relative to the local origin of the + "root" shape.This makes the off-diagonal elements of the inertia tensor (products of inertia) all + 0 and allows us to just store the diagonal elements (moments of inertia). + + + + + + + + + + + + + float3 - The diagonal elements of the inertia tensor (moments of inertia), which is represented + in the local frame of the center of mass. See above. + + + + + + + + References a physics_material for the rigid_body. + + + + + + + Defines a physics_material for the rigid_body. + + + + + + + + This element allows for describing components of a rigid_body. + + + + + + + + If true, the mass is distributed along the surface of the shape + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The mass of the shape. + + + + + + + The density of the shape. + + + + + + + + References a physics_material for the shape. + + + + + + + Defines a physics_material for the shape. + + + + + + + + + Instances a geometry to use to define this shape. + + + + + + + Defines a plane to use for this shape. + + + + + + + Defines a box to use for this shape. + + + + + + + Defines a sphere to use for this shape. + + + + + + + Defines a cyliner to use for this shape. + + + + + + + Defines a tapered_cylinder to use for this shape. + + + + + + + Defines a capsule to use for this shape. + + + + + + + Defines a tapered_capsule to use for this shape. + + + + + + + + + Allows a transformation for the shape. + + + + + + + Allows a transformation for the shape. + + + + + + + + The extra element may appear any number of times. + + + + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. This + value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + This element allows for connecting components, such as rigid_body into complex physics models + with moveable parts. + + + + + + + + Defines the attachment (to a rigid_body or a node) to be used as the reference-frame. + + + + + + + + Allows you to "position" the attachment point. + + + + + + + Allows you to "position" the attachment point. + + + + + + + The extra element may appear any number of times. + + + + + + + + The "rigid_body" attribute is a relative reference to a rigid-body within the same + physics_model. + + + + + + + + + Defines an attachment to a rigid-body or a node. + + + + + + + + Allows you to "position" the attachment point. + + + + + + + Allows you to "position" the attachment point. + + + + + + + The extra element may appear any number of times. + + + + + + + + The "rigid_body" attribute is a relative reference to a rigid-body within the same physics_model. + + + + + + + + + The technique_common element specifies the rigid_constraint information for the common profile + which all COLLADA implementations need to support. + + + + + + + + If false, the constraint doesn't exert any force or influence on the rigid bodies. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + Indicates whether the attached rigid bodies may inter-penetrate. + + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + + + + + The limits element provides a flexible way to specify the constraint limits (degrees of freedom + and ranges). + + + + + + + + The swing_cone_and_twist element describes the angular limits along each rotation axis in degrees. + The the X and Y limits describe a "swing cone" and the Z limits describe the "twist angle" range + + + + + + + + The minimum values for the limit. + + + + + + + The maximum values for the limit. + + + + + + + + + + The linear element describes linear (translational) limits along each axis. + + + + + + + + The minimum values for the limit. + + + + + + + The maximum values for the limit. + + + + + + + + + + + + + Spring, based on distance ("LINEAR") or angle ("ANGULAR"). + + + + + + + + The angular spring properties. + + + + + + + + The stiffness (also called spring coefficient) has units of force/angle in degrees. + + + + + + + The spring damping coefficient. + + + + + + + The spring's target or resting distance. + + + + + + + + + + The linear spring properties. + + + + + + + + The stiffness (also called spring coefficient) has units of force/distance. + + + + + + + The spring damping coefficient. + + + + + + + The spring's target or resting distance. + + + + + + + + + + + + + + + + This element may contain any number of non-common profile techniques. + + + + + + + The extra element may appear any number of times. + + + + + + + + The sid attribute is a text string value containing the sub-identifier of this element. + This value must be unique within the scope of the parent element. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + This element allows for building complex combinations of rigid-bodies and constraints that + may be instantiated multiple times. + + + + + + + + The physics_model element may contain an asset element. + + + + + + + The physics_model may define any number of rigid_body elements. + + + + + + + The physics_model may define any number of rigid_constraint elements. + + + + + + + The physics_model may instance any number of other physics_model elements. + + + + + + + The extra element may appear any number of times. + + + + + + + + The id attribute is a text string containing the unique identifier of this element. + This value must be unique within the instance document. Optional attribute. + + + + + + + The name attribute is the text string name of this element. Optional attribute. + + + + + + + + + constant-strings + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + constant-strings + + + + + + + + + + + + + + + + + + + + + + diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/resources/xsd.xml b/data/miniconda3/lib/python3.13/site-packages/collada/resources/xsd.xml new file mode 100644 index 0000000000000000000000000000000000000000..e27418f2bc9b5e078b22f58068eb763e37318861 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/resources/xsd.xml @@ -0,0 +1,109 @@ + + + + + + See http://www.w3.org/XML/1998/namespace.html and + http://www.w3.org/TR/REC-xml for information about this namespace. + + This schema document describes the XML namespace, in a form + suitable for import by other schema documents. + + Note that local names in this namespace are intended to be defined + only by the World Wide Web Consortium or its subgroups. The + following names are currently defined in this namespace and should + not be used with conflicting semantics by any Working Group, + specification, or document instance: + + base (as an attribute name): denotes an attribute whose value + provides a URI to be used as the base for interpreting any + relative URIs in the scope of the element on which it + appears; its value is inherited. This name is reserved + by virtue of its definition in the XML Base specification. + + lang (as an attribute name): denotes an attribute whose value + is a language code for the natural language of the content of + any element; its value is inherited. This name is reserved + by virtue of its definition in the XML specification. + + space (as an attribute name): denotes an attribute whose + value is a keyword indicating what whitespace processing + discipline is intended for the content of the element; its + value is inherited. This name is reserved by virtue of its + definition in the XML specification. + + Father (in any context at all): denotes Jon Bosak, the chair of + the original XML Working Group. This name is reserved by + the following decision of the W3C XML Plenary and + XML Coordination groups: + + In appreciation for his vision, leadership and dedication + the W3C XML Plenary on this 10th day of February, 2000 + reserves for Jon Bosak in perpetuity the XML name + xml:Father + + + + This schema defines attributes and an attribute group + suitable for use by + schemas wishing to allow xml:base, xml:lang or xml:space attributes + on elements they define. + + To enable this, such a schema must import this schema + for the XML namespace, e.g. as follows: + <schema . . .> + . . . + <import namespace="http://www.w3.org/XML/1998/namespace" + schemaLocation="http://www.w3.org/2001/03/xml.xsd"/> + + Subsequently, qualified reference to any of the attributes + or the group defined below will have the desired effect, e.g. + + <type . . .> + . . . + <attributeGroup ref="xml:specialAttrs"/> + + will define a type which will schema-validate an instance + element with any of those attributes + + + In keeping with the XML Schema WG's standard versioning + policy, this schema document will persist at + http://www.w3.org/2001/03/xml.xsd. + At the date of issue it can also be found at + http://www.w3.org/2001/xml.xsd. + The schema document at that URI may however change in the future, + in order to remain compatible with the latest version of XML Schema + itself. In other words, if the XML Schema namespace changes, the version + of this document at + http://www.w3.org/2001/xml.xsd will change + accordingly; the version at + http://www.w3.org/2001/03/xml.xsd will not change. + + + + + In due course, we should install the relevant ISO 2- and 3-letter + codes as the enumerated possible values . . . + + + + + + + + + + + + + See http://www.w3.org/TR/xmlbase/ for + information about this attribute. + + + + + + + + diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__init__.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f49136c029a129d01669120771f71f9be11f09f5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_asset.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_asset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..81952e50be5a7c8d223e2db76a1e47795b36c059 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_asset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_camera.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_camera.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9ecb708d480ec62a6877abb10f1d3a18985eb71 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_camera.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_collada.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_collada.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d3aa12fe29be082b323dd286c702855aec1461c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_collada.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_geometry.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_geometry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..118f4654ab7ef02048626c7d314fbe1c9b885648 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_geometry.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_ignore.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_ignore.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e9e774d0af8e116885fc48d7e757a8c5ed0b471a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_ignore.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_iteration.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_iteration.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2df323f00af30be9d949debdf38ae62e65e931b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_iteration.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_light.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_light.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..31a4a712445a61511430b127d5c887030f0d745e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_light.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_lineset.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_lineset.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3958711737ea2702fde2133b0307dc30e751fd7f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_lineset.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_material.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_material.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4084cc8986aa9be952bb63e90ea935b43ff07487 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_material.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_scene.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_scene.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6fdd214448ef3cb4aa64c42904076f1d929f6184 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_scene.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_source.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_source.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..132f4b29cb4e916a07930aa4b60dbd50b5f119a2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/collada/tests/__pycache__/test_source.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_asset.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..db181fee58049c1c84334285465e32fbaf66f803 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_asset.py @@ -0,0 +1,104 @@ +import datetime + +import collada +import unittest +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestAsset(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_asset_contributor(self): + contributor = collada.asset.Contributor() + self.assertIsNone(contributor.author) + self.assertIsNone(contributor.authoring_tool) + self.assertIsNone(contributor.comments) + self.assertIsNone(contributor.copyright) + self.assertIsNone(contributor.source_data) + + contributor.save() + contributor = collada.asset.Contributor.load(self.dummy, {}, fromstring(tostring(contributor.xmlnode))) + self.assertIsNone(contributor.author) + self.assertIsNone(contributor.authoring_tool) + self.assertIsNone(contributor.comments) + self.assertIsNone(contributor.copyright) + self.assertIsNone(contributor.source_data) + + contributor.author = "author1" + contributor.authoring_tool = "tool2" + contributor.comments = "comments3" + contributor.copyright = "copyright4" + contributor.source_data = "data5" + + contributor.save() + contributor = collada.asset.Contributor.load(self.dummy, {}, fromstring(tostring(contributor.xmlnode))) + self.assertEqual(contributor.author, "author1") + self.assertEqual(contributor.authoring_tool, "tool2") + self.assertEqual(contributor.comments, "comments3") + self.assertEqual(contributor.copyright, "copyright4") + self.assertEqual(contributor.source_data, "data5") + + def test_asset(self): + asset = collada.asset.Asset() + + self.assertIsNone(asset.title) + self.assertIsNone(asset.subject) + self.assertIsNone(asset.revision) + self.assertIsNone(asset.keywords) + self.assertIsNone(asset.unitname) + self.assertIsNone(asset.unitmeter) + self.assertEqual(asset.contributors, []) + self.assertEqual(asset.upaxis, collada.asset.UP_AXIS.Y_UP) + self.assertIsInstance(asset.created, datetime.datetime) + self.assertIsInstance(asset.modified, datetime.datetime) + + asset.save() + asset = collada.asset.Asset.load(self.dummy, {}, fromstring(tostring(asset.xmlnode))) + + self.assertIsNone(asset.title) + self.assertIsNone(asset.subject) + self.assertIsNone(asset.revision) + self.assertIsNone(asset.keywords) + self.assertIsNone(asset.unitname) + self.assertIsNone(asset.unitmeter) + self.assertEqual(asset.contributors, []) + self.assertEqual(asset.upaxis, collada.asset.UP_AXIS.Y_UP) + self.assertIsInstance(asset.created, datetime.datetime) + self.assertIsInstance(asset.modified, datetime.datetime) + + asset.title = 'title1' + asset.subject = 'subject2' + asset.revision = 'revision3' + asset.keywords = 'keywords4' + asset.unitname = 'feet' + asset.unitmeter = 3.1 + contrib1 = collada.asset.Contributor(author="jeff") + contrib2 = collada.asset.Contributor(author="bob") + asset.contributors = [contrib1, contrib2] + asset.upaxis = collada.asset.UP_AXIS.Z_UP + time1 = datetime.datetime.now() + asset.created = time1 + time2 = datetime.datetime.now() + datetime.timedelta(hours=5) + asset.modified = time2 + + asset.save() + asset = collada.asset.Asset.load(self.dummy, {}, fromstring(tostring(asset.xmlnode))) + self.assertEqual(asset.title, 'title1') + self.assertEqual(asset.subject, 'subject2') + self.assertEqual(asset.revision, 'revision3') + self.assertEqual(asset.keywords, 'keywords4') + self.assertEqual(asset.unitname, 'feet') + self.assertEqual(asset.unitmeter, 3.1) + self.assertEqual(asset.upaxis, collada.asset.UP_AXIS.Z_UP) + self.assertEqual(asset.created, time1) + self.assertEqual(asset.modified, time2) + self.assertEqual(len(asset.contributors), 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_camera.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_camera.py new file mode 100644 index 0000000000000000000000000000000000000000..39b8dbdd564c2e4556c19f7b0e9d344349ac5cb2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_camera.py @@ -0,0 +1,185 @@ +import collada +import unittest +from collada.common import DaeMalformedError +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestCamera(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_perspective_camera_xfov_yfov_aspect_ratio(self): + # test invalid xfov,yfov,aspect_ratio combinations + with self.assertRaises(DaeMalformedError): + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=None, yfov=None, aspect_ratio=None) + with self.assertRaises(DaeMalformedError): + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=0.2, yfov=30, aspect_ratio=50) + with self.assertRaises(DaeMalformedError): + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=None, yfov=None, aspect_ratio=50) + + # xfov alone + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=30, yfov=None, aspect_ratio=None) + self.assertEqual(cam.xfov, 30) + self.assertIsNone(cam.yfov) + self.assertIsNone(cam.aspect_ratio) + + # yfov alone + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=None, yfov=50, aspect_ratio=None) + self.assertIsNone(cam.xfov) + self.assertEqual(cam.yfov, 50) + self.assertIsNone(cam.aspect_ratio) + + # xfov + yfov + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=30, yfov=50, aspect_ratio=None) + self.assertEqual(cam.xfov, 30) + self.assertEqual(cam.yfov, 50) + self.assertIsNone(cam.aspect_ratio) + + # xfov + aspect_ratio + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=30, yfov=None, aspect_ratio=1) + self.assertEqual(cam.xfov, 30) + self.assertIsNone(cam.yfov) + self.assertEqual(cam.aspect_ratio, 1) + + # yfov + aspect_ratio + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=None, yfov=50, aspect_ratio=1) + self.assertIsNone(cam.xfov) + self.assertEqual(cam.yfov, 50) + self.assertEqual(cam.aspect_ratio, 1) + + def test_perspective_camera_saving(self): + cam = collada.camera.PerspectiveCamera("mycam", 1, 1000, xfov=30) + + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xfov, 30) + self.assertEqual(cam.yfov, None) + self.assertEqual(cam.aspect_ratio, None) + + cam.save() + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xfov, 30) + self.assertEqual(cam.yfov, None) + self.assertEqual(cam.aspect_ratio, None) + + cam = collada.camera.PerspectiveCamera.load(self.dummy, {}, fromstring(tostring(cam.xmlnode))) + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xfov, 30) + self.assertEqual(cam.yfov, None) + self.assertEqual(cam.aspect_ratio, None) + + cam.id = "yourcam" + cam.znear = 5 + cam.zfar = 500 + cam.xfov = None + cam.yfov = 50 + cam.aspect_ratio = 1.3 + cam.save() + cam = collada.camera.PerspectiveCamera.load(self.dummy, {}, fromstring(tostring(cam.xmlnode))) + self.assertEqual(cam.id, "yourcam") + self.assertEqual(cam.znear, 5) + self.assertEqual(cam.zfar, 500) + self.assertEqual(cam.xfov, None) + self.assertEqual(cam.yfov, 50) + self.assertEqual(cam.aspect_ratio, 1.3) + + cam.xfov = 20 + with self.assertRaises(DaeMalformedError): + cam.save() + + def test_orthographic_camera_xmag_ymag_aspect_ratio(self): + # test invalid xmag,ymag,aspect_ratio combinations + with self.assertRaises(DaeMalformedError): + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=None, ymag=None, aspect_ratio=None) + with self.assertRaises(DaeMalformedError): + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=0.2, ymag=30, aspect_ratio=50) + with self.assertRaises(DaeMalformedError): + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=None, ymag=None, aspect_ratio=50) + + # xmag alone + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=30, ymag=None, aspect_ratio=None) + self.assertEqual(cam.xmag, 30) + self.assertIsNone(cam.ymag) + self.assertIsNone(cam.aspect_ratio) + + # ymag alone + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=None, ymag=50, aspect_ratio=None) + self.assertIsNone(cam.xmag) + self.assertEqual(cam.ymag, 50) + self.assertIsNone(cam.aspect_ratio) + + # xmag + ymag + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=30, ymag=50, aspect_ratio=None) + self.assertEqual(cam.xmag, 30) + self.assertEqual(cam.ymag, 50) + self.assertIsNone(cam.aspect_ratio) + + # xmag + aspect_ratio + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=30, ymag=None, aspect_ratio=1) + self.assertEqual(cam.xmag, 30) + self.assertIsNone(cam.ymag) + self.assertEqual(cam.aspect_ratio, 1) + + # ymag + aspect_ratio + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=None, ymag=50, aspect_ratio=1) + self.assertIsNone(cam.xmag) + self.assertEqual(cam.ymag, 50) + self.assertEqual(cam.aspect_ratio, 1) + + def test_orthographic_camera_saving(self): + cam = collada.camera.OrthographicCamera("mycam", 1, 1000, xmag=30) + + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xmag, 30) + self.assertEqual(cam.ymag, None) + self.assertEqual(cam.aspect_ratio, None) + + cam.save() + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xmag, 30) + self.assertEqual(cam.ymag, None) + self.assertEqual(cam.aspect_ratio, None) + + cam = collada.camera.OrthographicCamera.load(self.dummy, {}, fromstring(tostring(cam.xmlnode))) + self.assertEqual(cam.id, "mycam") + self.assertEqual(cam.znear, 1) + self.assertEqual(cam.zfar, 1000) + self.assertEqual(cam.xmag, 30) + self.assertEqual(cam.ymag, None) + self.assertEqual(cam.aspect_ratio, None) + + cam.id = "yourcam" + cam.znear = 5 + cam.zfar = 500 + cam.xmag = None + cam.ymag = 50 + cam.aspect_ratio = 1.3 + cam.save() + cam = collada.camera.OrthographicCamera.load(self.dummy, {}, fromstring(tostring(cam.xmlnode))) + self.assertEqual(cam.id, "yourcam") + self.assertEqual(cam.znear, 5) + self.assertEqual(cam.zfar, 500) + self.assertEqual(cam.xmag, None) + self.assertEqual(cam.ymag, 50) + self.assertEqual(cam.aspect_ratio, 1.3) + + cam.xmag = 20 + with self.assertRaises(DaeMalformedError): + cam.save() + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_collada.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_collada.py new file mode 100644 index 0000000000000000000000000000000000000000..c3a86d530ed44690e4f86581595584e32dca3952 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_collada.py @@ -0,0 +1,387 @@ +import io +import os +import numpy +import dateutil.parser +import unittest + +import collada +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestCollada(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + self.datadir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") + + def test_collada_duck_tris(self): + f = os.path.join(self.datadir, "duck_triangles.dae") + mesh = collada.Collada(f, validate_output=True) + + self.assertEqual(mesh.assetInfo.contributors[0].author, 'gcorson') + self.assertEqual(mesh.assetInfo.contributors[0].authoring_tool, 'Maya 8.0 | ColladaMaya v3.02 | FCollada v3.2') + self.assertEqual(mesh.assetInfo.contributors[0].source_data, + 'file:///C:/vs2005/sample_data/Complete_Packages/SCEA_Private/Maya_MoonLander/Moonlander/untitled') + self.assertEqual(len(mesh.assetInfo.contributors[0].copyright), 595) + self.assertEqual(len(mesh.assetInfo.contributors[0].comments), 449) + + self.assertEqual(mesh.assetInfo.unitmeter, 0.01) + self.assertEqual(mesh.assetInfo.unitname, 'centimeter') + self.assertEqual(mesh.assetInfo.upaxis, collada.asset.UP_AXIS.Y_UP) + self.assertIsNone(mesh.assetInfo.title) + self.assertIsNone(mesh.assetInfo.subject) + self.assertIsNone(mesh.assetInfo.revision) + self.assertIsNone(mesh.assetInfo.keywords) + self.assertEqual(mesh.assetInfo.created, dateutil.parser.parse('2006-08-23T22:29:59Z')) + self.assertEqual(mesh.assetInfo.modified, dateutil.parser.parse('2007-02-21T22:52:44Z')) + + self.assertEqual(mesh.scene.id, 'VisualSceneNode') + self.assertIn('LOD3spShape-lib', mesh.geometries) + self.assertIn('directionalLightShape1-lib', mesh.lights) + self.assertIn('cameraShape1', mesh.cameras) + self.assertIn('file2', mesh.images) + self.assertIn('blinn3-fx', mesh.effects) + self.assertIn('blinn3', mesh.materials) + self.assertEqual(len(mesh.nodes), 0) + self.assertIn('VisualSceneNode', mesh.scenes) + + triset = mesh.geometries[0].primitives[0] + input_list = triset.getInputList().getList() + self.assertEqual(3, len(input_list)) + + self.assertIsNotNone(str(list(mesh.scene.objects('geometry')))) + self.assertIsNotNone(str(list(mesh.scene.objects('light')))) + self.assertIsNotNone(str(list(mesh.scene.objects('camera')))) + + s = io.BytesIO() + mesh.write(s) + out = s.getvalue() + t = io.BytesIO(out) + mesh = collada.Collada(t, validate_output=True) + + self.assertEqual(mesh.assetInfo.contributors[0].author, 'gcorson') + self.assertEqual(mesh.assetInfo.contributors[0].authoring_tool, 'Maya 8.0 | ColladaMaya v3.02 | FCollada v3.2') + self.assertEqual(mesh.assetInfo.contributors[0].source_data, + 'file:///C:/vs2005/sample_data/Complete_Packages/SCEA_Private/Maya_MoonLander/Moonlander/untitled') + self.assertEqual(len(mesh.assetInfo.contributors[0].copyright), 595) + self.assertEqual(len(mesh.assetInfo.contributors[0].comments), 449) + + self.assertEqual(mesh.assetInfo.unitmeter, 0.01) + self.assertEqual(mesh.assetInfo.unitname, 'centimeter') + self.assertEqual(mesh.assetInfo.upaxis, collada.asset.UP_AXIS.Y_UP) + self.assertIsNone(mesh.assetInfo.title) + self.assertIsNone(mesh.assetInfo.subject) + self.assertIsNone(mesh.assetInfo.revision) + self.assertIsNone(mesh.assetInfo.keywords) + self.assertEqual(mesh.assetInfo.created, dateutil.parser.parse('2006-08-23T22:29:59Z')) + self.assertEqual(mesh.assetInfo.modified, dateutil.parser.parse('2007-02-21T22:52:44Z')) + + self.assertEqual(mesh.scene.id, 'VisualSceneNode') + self.assertIn('LOD3spShape-lib', mesh.geometries) + self.assertIn('directionalLightShape1-lib', mesh.lights) + self.assertIn('cameraShape1', mesh.cameras) + self.assertIn('file2', mesh.images) + self.assertIn('blinn3-fx', mesh.effects) + self.assertIn('blinn3', mesh.materials) + self.assertEqual(len(mesh.nodes), 0) + self.assertIn('VisualSceneNode', mesh.scenes) + + self.assertIsNotNone(str(list(mesh.scene.objects('geometry')))) + self.assertIsNotNone(str(list(mesh.scene.objects('light')))) + self.assertIsNotNone(str(list(mesh.scene.objects('camera')))) + + def test_collada_duck_poly(self): + f = os.path.join(self.datadir, "duck_polylist.dae") + mesh = collada.Collada(f, validate_output=True) + self.assertEqual(mesh.scene.id, 'VisualSceneNode') + self.assertIn('LOD3spShape-lib', mesh.geometries) + self.assertIn('directionalLightShape1-lib', mesh.lights) + self.assertIn('cameraShape1', mesh.cameras) + self.assertIn('file2', mesh.images) + self.assertIn('blinn3-fx', mesh.effects) + self.assertIn('blinn3', mesh.materials) + self.assertEqual(len(mesh.nodes), 0) + self.assertIn('VisualSceneNode', mesh.scenes) + + s = io.BytesIO() + mesh.write(s) + out = s.getvalue() + t = io.BytesIO(out) + mesh = collada.Collada(t, validate_output=True) + + self.assertEqual(mesh.scene.id, 'VisualSceneNode') + self.assertIn('LOD3spShape-lib', mesh.geometries) + self.assertIn('directionalLightShape1-lib', mesh.lights) + self.assertIn('cameraShape1', mesh.cameras) + self.assertIn('file2', mesh.images) + self.assertIn('blinn3-fx', mesh.effects) + self.assertIn('blinn3', mesh.materials) + self.assertEqual(len(mesh.nodes), 0) + self.assertIn('VisualSceneNode', mesh.scenes) + + def test_collada_duck_zip(self): + f = os.path.join(self.datadir, "duck.zip") + mesh = collada.Collada(f, validate_output=True) + self.assertEqual(mesh.scene.id, 'VisualSceneNode') + self.assertIn('LOD3spShape-lib', mesh.geometries) + self.assertIn('directionalLightShape1-lib', mesh.lights) + self.assertIn('cameraShape1', mesh.cameras) + self.assertIn('file2', mesh.images) + self.assertIn('blinn3-fx', mesh.effects) + self.assertIn('blinn3', mesh.materials) + self.assertEqual(len(mesh.nodes), 0) + self.assertIn('VisualSceneNode', mesh.scenes) + + def test_collada_saving(self): + mesh = collada.Collada(validate_output=True) + + self.assertEqual(len(mesh.geometries), 0) + self.assertEqual(len(mesh.controllers), 0) + self.assertEqual(len(mesh.lights), 0) + self.assertEqual(len(mesh.cameras), 0) + self.assertEqual(len(mesh.images), 0) + self.assertEqual(len(mesh.effects), 0) + self.assertEqual(len(mesh.materials), 0) + self.assertEqual(len(mesh.nodes), 0) + self.assertEqual(len(mesh.scenes), 0) + self.assertEqual(mesh.scene, None) + self.assertIsNotNone(str(mesh)) + + floatsource = collada.source.FloatSource("myfloatsource", numpy.array([0.1, 0.2, 0.3]), ('X', 'Y', 'Z')) + geometry1 = collada.geometry.Geometry(mesh, "geometry1", "mygeometry1", {"myfloatsource": floatsource}) + mesh.geometries.append(geometry1) + + linefloats = [1, 1, -1, 1, -1, -1, -1, -0.9999998, -1, -0.9999997, 1, -1, 1, 0.9999995, 1, 0.9999994, -1.000001, 1] + linefloatsrc = collada.source.FloatSource("mylinevertsource", numpy.array(linefloats), ('X', 'Y', 'Z')) + geometry2 = collada.geometry.Geometry(mesh, "geometry2", "mygeometry2", [linefloatsrc]) + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#mylinevertsource") + indices = numpy.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + lineset1 = geometry2.createLineSet(indices, input_list, "mymaterial2") + geometry2.primitives.append(lineset1) + mesh.geometries.append(geometry2) + + ambientlight = collada.light.AmbientLight("myambientlight", (1, 1, 1)) + pointlight = collada.light.PointLight("mypointlight", (1, 1, 1)) + mesh.lights.append(ambientlight) + mesh.lights.append(pointlight) + + camera1 = collada.camera.PerspectiveCamera("mycam1", 45.0, 0.01, 1000.0) + camera2 = collada.camera.PerspectiveCamera("mycam2", 45.0, 0.01, 1000.0) + mesh.cameras.append(camera1) + mesh.cameras.append(camera2) + + cimage1 = collada.material.CImage("mycimage1", "./whatever.tga", mesh) + cimage2 = collada.material.CImage("mycimage2", "./whatever.tga", mesh) + mesh.images.append(cimage1) + mesh.images.append(cimage2) + + effect1 = collada.material.Effect("myeffect1", [], "phong") + effect2 = collada.material.Effect("myeffect2", [], "phong") + mesh.effects.append(effect1) + mesh.effects.append(effect2) + + mat1 = collada.material.Material("mymaterial1", "mymat1", effect1) + mat2 = collada.material.Material("mymaterial2", "mymat2", effect2) + mesh.materials.append(mat1) + mesh.materials.append(mat2) + + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + mynode1 = collada.scene.Node('mynode1', children=[], transforms=[rotate, scale]) + mynode2 = collada.scene.Node('mynode2', children=[], transforms=[]) + mesh.nodes.append(mynode1) + mesh.nodes.append(mynode2) + + geomnode = collada.scene.GeometryNode(geometry2) + mynode3 = collada.scene.Node('mynode3', children=[geomnode], transforms=[]) + mynode4 = collada.scene.Node('mynode4', children=[], transforms=[]) + scene1 = collada.scene.Scene('myscene1', [mynode3]) + scene2 = collada.scene.Scene('myscene2', [mynode4]) + mesh.scenes.append(scene1) + mesh.scenes.append(scene2) + + mesh.scene = scene1 + + out = io.BytesIO() + mesh.write(out) + + toload = io.BytesIO(out.getvalue()) + + loaded_mesh = collada.Collada(toload, validate_output=True) + self.assertEqual(len(loaded_mesh.geometries), 2) + self.assertEqual(len(loaded_mesh.controllers), 0) + self.assertEqual(len(loaded_mesh.lights), 2) + self.assertEqual(len(loaded_mesh.cameras), 2) + self.assertEqual(len(loaded_mesh.images), 2) + self.assertEqual(len(loaded_mesh.effects), 2) + self.assertEqual(len(loaded_mesh.materials), 2) + self.assertEqual(len(loaded_mesh.nodes), 2) + self.assertEqual(len(loaded_mesh.scenes), 2) + self.assertEqual(loaded_mesh.scene.id, scene1.id) + + self.assertIn('geometry1', loaded_mesh.geometries) + self.assertIn('geometry2', loaded_mesh.geometries) + self.assertIn('mypointlight', loaded_mesh.lights) + self.assertIn('myambientlight', loaded_mesh.lights) + self.assertIn('mycam1', loaded_mesh.cameras) + self.assertIn('mycam2', loaded_mesh.cameras) + self.assertIn('mycimage1', loaded_mesh.images) + self.assertIn('mycimage2', loaded_mesh.images) + self.assertIn('myeffect1', loaded_mesh.effects) + self.assertIn('myeffect2', loaded_mesh.effects) + self.assertIn('mymaterial1', loaded_mesh.materials) + self.assertIn('mymaterial2', loaded_mesh.materials) + self.assertIn('mynode1', loaded_mesh.nodes) + self.assertIn('mynode2', loaded_mesh.nodes) + self.assertIn('myscene1', loaded_mesh.scenes) + self.assertIn('myscene2', loaded_mesh.scenes) + + linefloatsrc2 = collada.source.FloatSource("mylinevertsource2", numpy.array(linefloats), ('X', 'Y', 'Z')) + geometry3 = collada.geometry.Geometry(mesh, "geometry3", "mygeometry3", [linefloatsrc2]) + loaded_mesh.geometries.pop(0) + loaded_mesh.geometries.append(geometry3) + + dirlight = collada.light.DirectionalLight("mydirlight", (1, 1, 1)) + loaded_mesh.lights.pop(0) + loaded_mesh.lights.append(dirlight) + + camera3 = collada.camera.PerspectiveCamera("mycam3", 45.0, 0.01, 1000.0) + loaded_mesh.cameras.pop(0) + loaded_mesh.cameras.append(camera3) + + cimage3 = collada.material.CImage("mycimage3", "./whatever.tga", loaded_mesh) + loaded_mesh.images.pop(0) + loaded_mesh.images.append(cimage3) + + effect3 = collada.material.Effect("myeffect3", [], "phong") + loaded_mesh.effects.pop(0) + loaded_mesh.effects.append(effect3) + + mat3 = collada.material.Material("mymaterial3", "mymat3", effect3) + loaded_mesh.materials.pop(0) + loaded_mesh.materials.append(mat3) + + mynode5 = collada.scene.Node('mynode5', children=[], transforms=[]) + loaded_mesh.nodes.pop(0) + loaded_mesh.nodes.append(mynode5) + + mynode6 = collada.scene.Node('mynode6', children=[], transforms=[]) + scene3 = collada.scene.Scene('myscene3', [mynode6]) + loaded_mesh.scenes.pop(0) + loaded_mesh.scenes.append(scene3) + + loaded_mesh.scene = scene3 + + loaded_mesh.save() + + strdata = tostring(loaded_mesh.xmlnode.getroot()) + indata = io.BytesIO(strdata) + loaded_mesh2 = collada.Collada(indata, validate_output=True) + + self.assertEqual(loaded_mesh2.scene.id, scene3.id) + self.assertIn('geometry3', loaded_mesh2.geometries) + self.assertIn('geometry2', loaded_mesh2.geometries) + self.assertIn('mydirlight', loaded_mesh2.lights) + self.assertIn('mypointlight', loaded_mesh2.lights) + self.assertIn('mycam3', loaded_mesh2.cameras) + self.assertIn('mycam2', loaded_mesh2.cameras) + self.assertIn('mycimage3', loaded_mesh2.images) + self.assertIn('mycimage2', loaded_mesh2.images) + self.assertIn('myeffect3', loaded_mesh2.effects) + self.assertIn('myeffect2', loaded_mesh2.effects) + self.assertIn('mymaterial3', loaded_mesh2.materials) + self.assertIn('mymaterial2', loaded_mesh2.materials) + self.assertIn('mynode5', loaded_mesh2.nodes) + self.assertIn('mynode2', loaded_mesh2.nodes) + self.assertIn('myscene3', loaded_mesh2.scenes) + self.assertIn('myscene2', loaded_mesh2.scenes) + + def test_collada_attribute_replace(self): + mesh = collada.Collada(validate_output=True) + self.assertIsInstance(mesh.geometries, collada.util.IndexedList) + self.assertIsInstance(mesh.controllers, collada.util.IndexedList) + self.assertIsInstance(mesh.animations, collada.util.IndexedList) + self.assertIsInstance(mesh.lights, collada.util.IndexedList) + self.assertIsInstance(mesh.cameras, collada.util.IndexedList) + self.assertIsInstance(mesh.images, collada.util.IndexedList) + self.assertIsInstance(mesh.effects, collada.util.IndexedList) + self.assertIsInstance(mesh.materials, collada.util.IndexedList) + self.assertIsInstance(mesh.nodes, collada.util.IndexedList) + self.assertIsInstance(mesh.scenes, collada.util.IndexedList) + + mesh.geometries = [] + mesh.controllers = [] + mesh.animations = [] + mesh.lights = [] + mesh.cameras = [] + mesh.images = [] + mesh.effects = [] + mesh.materials = [] + mesh.nodes = [] + mesh.scenes = [] + + self.assertIsInstance(mesh.geometries, collada.util.IndexedList) + self.assertIsInstance(mesh.controllers, collada.util.IndexedList) + self.assertIsInstance(mesh.animations, collada.util.IndexedList) + self.assertIsInstance(mesh.lights, collada.util.IndexedList) + self.assertIsInstance(mesh.cameras, collada.util.IndexedList) + self.assertIsInstance(mesh.images, collada.util.IndexedList) + self.assertIsInstance(mesh.effects, collada.util.IndexedList) + self.assertIsInstance(mesh.materials, collada.util.IndexedList) + self.assertIsInstance(mesh.nodes, collada.util.IndexedList) + self.assertIsInstance(mesh.scenes, collada.util.IndexedList) + + def test_collada_tristrips(self): + f = os.path.join(self.datadir, "tristrips.dae") + mesh = collada.Collada(f, validate_output=True) + triangles = mesh.geometries[0].primitives[0] + self.assertEqual(20, len(triangles)) + + def test_collada_trifans(self): + f = os.path.join(self.datadir, "trifans.dae") + mesh = collada.Collada(f, validate_output=True) + triangles = mesh.geometries[0].primitives[0] + self.assertEqual(6, len(triangles)) + + def test_collada_empty_triangles(self): + f = os.path.join(self.datadir, "empty_triangles.dae") + mesh = collada.Collada(f, validate_output=True) + triangles = mesh.geometries[0].primitives[0] + self.assertEqual(0, len(triangles)) + + def test_collada_empty_triangles_with_multiple_ns(self): + f = os.path.join(self.datadir, "empty_triangles_with_multiple_ns.dae") + mesh = collada.Collada(f, validate_output=True) + triangles = mesh.geometries[0].primitives[0] + self.assertEqual(0, len(triangles)) + + def test_namespace(self): + """ + Test loading a file with a different namespace. + + Default namespace is: + http://www.collada.org/2005/11/COLLADASchema + + This test file has namespace: + http://www.collada.org/2008/03/COLLADASchema + """ + + # a 1.5 spec collada file with a different namespace + # check both the zipped ("zae") and plain text ("dae") versions + for name in ['wam.zae', 'wam.dae']: + # full path to test file + file_name = os.path.join(self.datadir, name) + # load the scene + mesh = collada.Collada(file_name, validate_output=True) + # scene should have 8 geometries + self.assertEqual(len(mesh.geometries), 8) + # scene should have one root node + self.assertEqual(len(mesh.scene.nodes), 1) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_geometry.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..de46ec645815629fd7fcc00137e921f3c121fbbf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_geometry.py @@ -0,0 +1,203 @@ +import numpy +import unittest + +import collada +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestGeometry(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_empty_geometry_saving(self): + floatsource = collada.source.FloatSource("myfloatsource", numpy.array([0.1, 0.2, 0.3]), ('X', 'Y', 'Z')) + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mygeometry", {"myfloatsource": floatsource}) + self.assertEqual(geometry.id, "geometry0") + self.assertEqual(geometry.name, "mygeometry") + self.assertEqual(len(geometry.primitives), 0) + self.assertDictEqual(geometry.sourceById, {"myfloatsource": floatsource}) + self.assertIsNotNone(str(geometry)) + + geometry.id = "geometry1" + geometry.name = "yourgeometry" + othersource1 = collada.source.FloatSource("yourfloatsource", numpy.array([0.4, 0.5, 0.6]), ('X', 'Y', 'Z')) + othersource2 = collada.source.FloatSource("hisfloatsource", numpy.array([0.7, 0.8, 0.9]), ('X', 'Y', 'Z')) + geometry.sourceById[othersource1.id] = othersource1 + geometry.sourceById[othersource2.id] = othersource2 + del geometry.sourceById[floatsource.id] + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(collada, {}, fromstring(tostring(geometry.xmlnode))) + self.assertEqual(loaded_geometry.id, "geometry1") + self.assertEqual(loaded_geometry.name, "yourgeometry") + self.assertEqual(len(loaded_geometry.primitives), 0) + self.assertIn(othersource1.id, loaded_geometry.sourceById) + self.assertIn(othersource2.id, loaded_geometry.sourceById) + self.assertNotIn(floatsource.id, loaded_geometry.sourceById) + + def test_geometry_lineset_adding_with_material(self): + linefloats = [1, 1, -1, 1, -1, -1, -1, -0.9999998, -1, -0.9999997, 1, -1, 1, 0.9999995, 1, 0.9999994, -1.000001, 1] + linefloatsrc = collada.source.FloatSource("mylinevertsource", numpy.array(linefloats), ('X', 'Y', 'Z')) + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mygeometry", [linefloatsrc]) + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#mylinevertsource") + indices = numpy.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + lineset1 = geometry.createLineSet(indices, input_list, "mymaterial") + lineset2 = geometry.createLineSet(indices, input_list, "mymaterial") + geometry.primitives.append(lineset1) + geometry.primitives.append(lineset2) + self.assertEqual(len(geometry.primitives), 2) + self.assertIsNotNone(str(lineset1)) + self.assertIsNotNone(str(input_list)) + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(geometry.xmlnode))) + self.assertEqual(len(loaded_geometry.primitives), 2) + + loaded_geometry.primitives.pop(0) + lineset3 = loaded_geometry.createLineSet(indices, input_list, "mymaterial") + + loaded_lineset = collada.lineset.LineSet.load(self.dummy, geometry.sourceById, fromstring(tostring(lineset3.xmlnode))) + self.assertEqual(len(loaded_lineset), 5) + + loaded_geometry.primitives.append(lineset3) + loaded_geometry.save() + loaded_geometry2 = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(loaded_geometry.xmlnode))) + + self.assertEqual(len(loaded_geometry2.primitives), 2) + self.assertEqual(loaded_geometry2.primitives[0].material, lineset2.material) + self.assertEqual(loaded_geometry2.primitives[1].material, lineset3.material) + + def test_geometry_lineset_adding_without_material(self): + linefloats = [1, 1, -1, 1, -1, -1, -1, -0.9999998, -1, -0.9999997, 1, -1, 1, 0.9999995, 1, 0.9999994, -1.000001, 1] + linefloatsrc = collada.source.FloatSource("mylinevertsource", numpy.array(linefloats), ('X', 'Y', 'Z')) + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mygeometry", [linefloatsrc]) + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#mylinevertsource") + indices = numpy.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + lineset1 = geometry.createLineSet(indices, input_list) + lineset2 = geometry.createLineSet(indices, input_list) + geometry.primitives.append(lineset1) + geometry.primitives.append(lineset2) + self.assertEqual(len(geometry.primitives), 2) + self.assertIsNotNone(str(lineset1)) + self.assertIsNotNone(str(input_list)) + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(geometry.xmlnode))) + self.assertEqual(len(loaded_geometry.primitives), 2) + + loaded_geometry.primitives.pop(0) + lineset3 = loaded_geometry.createLineSet(indices, input_list) + + loaded_lineset = collada.lineset.LineSet.load(self.dummy, geometry.sourceById, fromstring(tostring(lineset3.xmlnode))) + self.assertEqual(len(loaded_lineset), 5) + + loaded_geometry.primitives.append(lineset3) + loaded_geometry.save() + loaded_geometry2 = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(loaded_geometry.xmlnode))) + + self.assertEqual(len(loaded_geometry2.primitives), 2) + + def test_geometry_triangleset_adding(self): + vert_floats = [-50, 50, 50, 50, 50, 50, -50, -50, 50, 50, -50, 50, -50, 50, -50, 50, 50, -50, -50, -50, -50, 50, -50, -50] + normal_floats = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1] + vert_src = collada.source.FloatSource("cubeverts-array", numpy.array(vert_floats), ('X', 'Y', 'Z')) + normal_src = collada.source.FloatSource("cubenormals-array", numpy.array(normal_floats), ('X', 'Y', 'Z')) + self.assertEqual(len(vert_src), 8) + self.assertEqual(len(normal_src), 24) + + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mycube", [vert_src, normal_src], []) + + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#cubeverts-array") + input_list.addInput(1, 'NORMAL', "#cubenormals-array") + + indices = numpy.array([0, 0, 2, 1, 3, 2, 0, 0, 3, 2, 1, 3, 0, 4, 1, 5, 5, 6, 0, 4, 5, 6, 4, 7, 6, 8, 7, 9, 3, 10, 6, 8, 3, 10, 2, 11, 0, 12, + 4, 13, 6, 14, 0, 12, 6, 14, 2, 15, 3, 16, 7, 17, 5, 18, 3, 16, 5, 18, 1, 19, 5, 20, 7, 21, 6, 22, 5, 20, 6, 22, 4, 23]) + triangleset = geometry.createTriangleSet(indices, input_list) + self.assertIsNotNone(str(triangleset)) + + loaded_triangleset = collada.triangleset.TriangleSet.load(self.dummy, geometry.sourceById, fromstring(tostring(triangleset.xmlnode))) + self.assertEqual(len(loaded_triangleset), 12) + + geometry.primitives.append(triangleset) + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(geometry.xmlnode))) + self.assertEqual(len(loaded_geometry.primitives), 1) + self.assertEqual(len(loaded_geometry.primitives[0]), 12) + + def test_geometry_polylist_adding(self): + vert_floats = [-50, 50, 50, 50, 50, 50, -50, -50, 50, 50, -50, 50, -50, 50, -50, 50, 50, -50, -50, -50, -50, 50, -50, -50] + normal_floats = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1] + vert_src = collada.source.FloatSource("cubeverts-array", numpy.array(vert_floats), ('X', 'Y', 'Z')) + normal_src = collada.source.FloatSource("cubenormals-array", numpy.array(normal_floats), ('X', 'Y', 'Z')) + + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mycube", [vert_src, normal_src], []) + + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#cubeverts-array") + input_list.addInput(1, 'NORMAL', "#cubenormals-array") + + vcounts = numpy.array([4, 4, 4, 4, 4, 4]) + indices = numpy.array([0, 0, 2, 1, 3, 2, 1, 3, 0, 4, 1, 5, 5, 6, 4, 7, 6, 8, 7, 9, 3, 10, 2, 11, 0, 12, 4, 13, 6, 14, 2, + 15, 3, 16, 7, 17, 5, 18, 1, 19, 5, 20, 7, 21, 6, 22, 4, 23]) + polylist = geometry.createPolylist(indices, vcounts, input_list) + self.assertIsNotNone(str(polylist)) + + loaded_polylist = collada.polylist.Polylist.load(self.dummy, geometry.sourceById, fromstring(tostring(polylist.xmlnode))) + self.assertEqual(len(loaded_polylist), 6) + + geometry.primitives.append(polylist) + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(geometry.xmlnode))) + + self.assertEqual(len(loaded_geometry.primitives), 1) + self.assertEqual(len(loaded_geometry.primitives[0]), 6) + + def test_geometry_polygons_adding(self): + vert_floats = [-50, 50, 50, 50, 50, 50, -50, -50, 50, 50, -50, 50, -50, 50, -50, 50, 50, -50, -50, -50, -50, 50, -50, -50] + normal_floats = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1] + vert_src = collada.source.FloatSource("cubeverts-array", numpy.array(vert_floats), ('X', 'Y', 'Z')) + normal_src = collada.source.FloatSource("cubenormals-array", numpy.array(normal_floats), ('X', 'Y', 'Z')) + + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mycube", [vert_src, normal_src], []) + + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#cubeverts-array") + input_list.addInput(1, 'NORMAL', "#cubenormals-array") + + indices = [] + indices.append(numpy.array([0, 0, 2, 1, 3, 2, 1, 3], dtype=numpy.int32)) + indices.append(numpy.array([0, 4, 1, 5, 5, 6, 4, 7], dtype=numpy.int32)) + indices.append(numpy.array([6, 8, 7, 9, 3, 10, 2, 11], dtype=numpy.int32)) + indices.append(numpy.array([0, 12, 4, 13, 6, 14, 2, 15], dtype=numpy.int32)) + indices.append(numpy.array([3, 16, 7, 17, 5, 18, 1, 19], dtype=numpy.int32)) + indices.append(numpy.array([5, 20, 7, 21, 6, 22, 4, 23], dtype=numpy.int32)) + + polygons = geometry.createPolygons(indices, input_list) + self.assertIsNotNone(str(polygons)) + + loaded_polygons = collada.polygons.Polygons.load(self.dummy, geometry.sourceById, fromstring(tostring(polygons.xmlnode))) + self.assertEqual(len(loaded_polygons), 6) + + geometry.primitives.append(polygons) + geometry.save() + + loaded_geometry = collada.geometry.Geometry.load(self.dummy, {}, fromstring(tostring(geometry.xmlnode))) + + self.assertEqual(len(loaded_geometry.primitives), 1) + self.assertEqual(len(loaded_geometry.primitives[0]), 6) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_ignore.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_ignore.py new file mode 100644 index 0000000000000000000000000000000000000000..6fa67b3456e5b9e7bca8d49dede8304c4f47df71 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_ignore.py @@ -0,0 +1,88 @@ +import os +import unittest + +import collada +from collada.common import (DaeError, + DaeBrokenRefError, + DaeIncompleteError, + DaeMalformedError) + + +class TestColladaIgnore(unittest.TestCase): + """ + Check the `ignore` functionality for ignoring + parsing errors. + """ + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + self.datadir = os.path.join(os.path.dirname( + os.path.realpath(__file__)), "data") + + def test_incomplete(self): + # this has an incomplete error + f = os.path.join(self.datadir, "cube_tristrips.dae") + raised = False + try: + collada.Collada(f) + except DaeIncompleteError: + # this should have raised + raised = True + if not raised: + raise ValueError('should have raised an error!') + + raised = False + try: + collada.Collada( + f, ignore=[DaeMalformedError]) + except DaeIncompleteError: + raised = True + if not raised: + raise ValueError('should have raised an error') + + # should have loaded if we ignore the specific error + m = collada.Collada(f, ignore=[DaeIncompleteError]) + # should have one primitive + assert len(m.geometries) == 1 + assert len(m.geometries[0].primitives) == 1 + # should be an (n, 3) numpy array + assert m.geometries[0].primitives[0].normal.shape[1] == 3 + + # should have loaded if we ignore the parent error + m = collada.Collada(f, ignore=[DaeError]) + # should have one primitive + assert len(m.geometries) == 1 + assert len(m.geometries[0].primitives) == 1 + # should be an (n, 3) numpy array + assert m.geometries[0].primitives[0].normal.shape[1] == 3 + + def test_malformed(self): + # this has a malformed component + f = os.path.join(self.datadir, "earthCylindrical.DAE") + raised = False + try: + collada.Collada(f) + except DaeMalformedError: + # this should have raised + raised = True + if not raised: + raise ValueError('should have raised an error!') + + raised = False + try: + collada.Collada(f, ignore=[DaeMalformedError]) + except DaeError: + # this should have raised + raised = True + if not raised: + raise ValueError('should have raised an error!') + + # should't have crashed + collada.Collada(f, ignore=[DaeMalformedError, + DaeBrokenRefError]) + # should have also loaded using the parent class + collada.Collada(f, ignore=[DaeError]) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_iteration.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_iteration.py new file mode 100644 index 0000000000000000000000000000000000000000..45ebaedb17e12a860e3d3e6b6a8b7843bed2ead2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_iteration.py @@ -0,0 +1,131 @@ +import collada +import numpy +import unittest +from collada.xmlutil import etree +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestIteration(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_triangle_iterator_vert_normals(self): + mesh = collada.Collada(validate_output=True) + + vert_floats = [-50, 50, 50, 50, 50, 50, -50, -50, 50, 50, -50, 50, -50, 50, -50, 50, 50, -50, -50, -50, -50, 50, -50, -50] + normal_floats = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1] + vert_src = collada.source.FloatSource("cubeverts-array", numpy.array(vert_floats), ('X', 'Y', 'Z')) + normal_src = collada.source.FloatSource("cubenormals-array", numpy.array(normal_floats), ('X', 'Y', 'Z')) + geometry = collada.geometry.Geometry(mesh, "geometry0", "mycube", [vert_src, normal_src], []) + + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#cubeverts-array") + input_list.addInput(1, 'NORMAL', "#cubenormals-array") + + indices = numpy.array([0, 0, 2, 1, 3, 2, 0, 0, 3, 2, 1, 3, 0, 4, 1, 5, 5, 6, 0, 4, 5, 6, 4, 7, 6, 8, 7, 9, 3, 10, 6, 8, 3, 10, 2, 11, 0, 12, + 4, 13, 6, 14, 0, 12, 6, 14, 2, 15, 3, 16, 7, 17, 5, 18, 3, 16, 5, 18, 1, 19, 5, 20, 7, 21, 6, 22, 5, 20, 6, 22, 4, 23]) + triangleset = geometry.createTriangleSet(indices, input_list, "cubematerial") + geometry.primitives.append(triangleset) + mesh.geometries.append(geometry) + + geomnode = collada.scene.GeometryNode(geometry, []) + mynode = collada.scene.Node('mynode6', children=[geomnode], transforms=[]) + scene = collada.scene.Scene('myscene', [mynode]) + mesh.scenes.append(scene) + mesh.scene = scene + + mesh.save() + + geoms = list(mesh.scene.objects('geometry')) + self.assertEqual(len(geoms), 1) + + prims = list(geoms[0].primitives()) + self.assertEqual(len(prims), 1) + + tris = list(prims[0]) + self.assertEqual(len(tris), 12) + + self.assertEqual(list(tris[0].vertices[0]), [-50.0, 50.0, 50.0]) + self.assertEqual(list(tris[0].vertices[1]), [-50.0, -50.0, 50.0]) + self.assertEqual(list(tris[0].vertices[2]), [50.0, -50.0, 50.0]) + self.assertEqual(list(tris[0].normals[0]), [0.0, 0.0, 1.0]) + self.assertEqual(list(tris[0].normals[1]), [0.0, 0.0, 1.0]) + self.assertEqual(list(tris[0].normals[2]), [0.0, 0.0, 1.0]) + self.assertEqual(tris[0].texcoords, []) + self.assertEqual(tris[0].material, None) + self.assertEqual(list(tris[0].indices), [0, 2, 3]) + self.assertEqual(list(tris[0].normal_indices), [0, 1, 2]) + self.assertEqual(tris[0].texcoord_indices, []) + + def test_polylist_iterator_vert_normals(self): + mesh = collada.Collada(validate_output=True) + + vert_floats = [-50, 50, 50, 50, 50, 50, -50, -50, 50, 50, -50, 50, -50, 50, -50, 50, 50, -50, -50, -50, -50, 50, -50, -50] + normal_floats = [0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, -1, 0, 0, + -1, 0, 0, -1, 0, 0, -1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1] + vert_src = collada.source.FloatSource("cubeverts-array", numpy.array(vert_floats), ('X', 'Y', 'Z')) + normal_src = collada.source.FloatSource("cubenormals-array", numpy.array(normal_floats), ('X', 'Y', 'Z')) + + geometry = collada.geometry.Geometry(mesh, "geometry0", "mycube", [vert_src, normal_src], []) + + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#cubeverts-array") + input_list.addInput(1, 'NORMAL', "#cubenormals-array") + + vcounts = numpy.array([4, 4, 4, 4, 4, 4]) + indices = numpy.array([0, 0, 2, 1, 3, 2, 1, 3, 0, 4, 1, 5, 5, 6, 4, 7, 6, 8, 7, 9, 3, 10, 2, 11, 0, 12, 4, 13, 6, 14, 2, + 15, 3, 16, 7, 17, 5, 18, 1, 19, 5, 20, 7, 21, 6, 22, 4, 23]) + polylist = geometry.createPolylist(indices, vcounts, input_list, "cubematerial") + + geometry.primitives.append(polylist) + mesh.geometries.append(geometry) + + geomnode = collada.scene.GeometryNode(geometry, []) + mynode = collada.scene.Node('mynode6', children=[geomnode], transforms=[]) + scene = collada.scene.Scene('myscene', [mynode]) + mesh.scenes.append(scene) + mesh.scene = scene + + mesh.save() + + geoms = list(mesh.scene.objects('geometry')) + self.assertEqual(len(geoms), 1) + + prims = list(geoms[0].primitives()) + self.assertEqual(len(prims), 1) + + poly = list(prims[0]) + self.assertEqual(len(poly), 6) + + self.assertEqual(list(poly[0].vertices[0]), [-50.0, 50.0, 50.0]) + self.assertEqual(list(poly[0].vertices[1]), [-50.0, -50.0, 50.0]) + self.assertEqual(list(poly[0].vertices[2]), [50.0, -50.0, 50.0]) + self.assertEqual(list(poly[0].normals[0]), [0.0, 0.0, 1.0]) + self.assertEqual(list(poly[0].normals[1]), [0.0, 0.0, 1.0]) + self.assertEqual(list(poly[0].normals[2]), [0.0, 0.0, 1.0]) + self.assertEqual(poly[0].texcoords, []) + self.assertEqual(poly[0].material, None) + self.assertEqual(list(poly[0].indices), [0, 2, 3, 1]) + self.assertEqual(list(poly[0].normal_indices), [0, 1, 2, 3]) + self.assertEqual(poly[0].texcoord_indices, []) + + tris = list(poly[0].triangles()) + + self.assertEqual(list(tris[0].vertices[0]), [-50.0, 50.0, 50.0]) + self.assertEqual(list(tris[0].vertices[1]), [-50.0, -50.0, 50.0]) + self.assertEqual(list(tris[0].vertices[2]), [50.0, -50.0, 50.0]) + self.assertEqual(list(tris[0].normals[0]), [0.0, 0.0, 1.0]) + self.assertEqual(list(tris[0].normals[1]), [0.0, 0.0, 1.0]) + self.assertEqual(list(tris[0].normals[2]), [0.0, 0.0, 1.0]) + self.assertEqual(tris[0].texcoords, []) + self.assertEqual(tris[0].material, None) + self.assertEqual(list(tris[0].indices), [0, 2, 3]) + self.assertEqual(list(tris[0].normal_indices), [0, 1, 2]) + self.assertEqual(tris[0].texcoord_indices, []) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_light.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_light.py new file mode 100644 index 0000000000000000000000000000000000000000..3c9ac3904c10d3eee095e8d3faf6e1f16c625bb0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_light.py @@ -0,0 +1,107 @@ +import collada +import unittest +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestLight(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_directional_light_saving(self): + dirlight = collada.light.DirectionalLight("mydirlight", (1, 1, 1)) + self.assertEqual(dirlight.id, "mydirlight") + self.assertTupleEqual(dirlight.color, (1, 1, 1)) + self.assertTupleEqual(tuple(dirlight.direction), (0, 0, -1)) + self.assertIsNotNone(str(dirlight)) + dirlight.color = (0.1, 0.2, 0.3) + dirlight.id = "yourdirlight" + dirlight.save() + loaded_dirlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(dirlight.xmlnode))) + self.assertTrue(isinstance(loaded_dirlight, collada.light.DirectionalLight)) + self.assertTupleEqual(loaded_dirlight.color, (0.1, 0.2, 0.3)) + self.assertEqual(loaded_dirlight.id, "yourdirlight") + + def test_ambient_light_saving(self): + ambientlight = collada.light.AmbientLight("myambientlight", (1, 1, 1)) + self.assertEqual(ambientlight.id, "myambientlight") + self.assertTupleEqual(ambientlight.color, (1, 1, 1)) + self.assertIsNotNone(str(ambientlight)) + ambientlight.color = (0.1, 0.2, 0.3) + ambientlight.id = "yourambientlight" + ambientlight.save() + loaded_ambientlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(ambientlight.xmlnode))) + self.assertTrue(isinstance(loaded_ambientlight, collada.light.AmbientLight)) + self.assertTupleEqual(ambientlight.color, (0.1, 0.2, 0.3)) + self.assertEqual(ambientlight.id, "yourambientlight") + + def test_point_light_saving(self): + pointlight = collada.light.PointLight("mypointlight", (1, 1, 1)) + self.assertEqual(pointlight.id, "mypointlight") + self.assertTupleEqual(pointlight.color, (1, 1, 1)) + self.assertEqual(pointlight.quad_att, None) + self.assertEqual(pointlight.constant_att, None) + self.assertEqual(pointlight.linear_att, None) + self.assertEqual(pointlight.zfar, None) + self.assertIsNotNone(str(pointlight)) + + pointlight.color = (0.1, 0.2, 0.3) + pointlight.constant_att = 0.7 + pointlight.linear_att = 0.8 + pointlight.quad_att = 0.9 + pointlight.id = "yourpointlight" + pointlight.save() + loaded_pointlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(pointlight.xmlnode))) + self.assertTrue(isinstance(loaded_pointlight, collada.light.PointLight)) + self.assertTupleEqual(loaded_pointlight.color, (0.1, 0.2, 0.3)) + self.assertEqual(loaded_pointlight.constant_att, 0.7) + self.assertEqual(loaded_pointlight.linear_att, 0.8) + self.assertEqual(loaded_pointlight.quad_att, 0.9) + self.assertEqual(loaded_pointlight.zfar, None) + self.assertEqual(loaded_pointlight.id, "yourpointlight") + + loaded_pointlight.zfar = 0.2 + loaded_pointlight.save() + loaded_pointlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(loaded_pointlight.xmlnode))) + self.assertEqual(loaded_pointlight.zfar, 0.2) + + def test_spot_light_saving(self): + spotlight = collada.light.SpotLight("myspotlight", (1, 1, 1)) + self.assertEqual(spotlight.id, "myspotlight") + self.assertTupleEqual(spotlight.color, (1, 1, 1)) + self.assertEqual(spotlight.constant_att, None) + self.assertEqual(spotlight.linear_att, None) + self.assertEqual(spotlight.quad_att, None) + self.assertEqual(spotlight.falloff_ang, None) + self.assertEqual(spotlight.falloff_exp, None) + self.assertIsNotNone(str(spotlight)) + + spotlight.color = (0.1, 0.2, 0.3) + spotlight.constant_att = 0.7 + spotlight.linear_att = 0.8 + spotlight.quad_att = 0.9 + spotlight.id = "yourspotlight" + spotlight.save() + loaded_spotlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(spotlight.xmlnode))) + self.assertTrue(isinstance(loaded_spotlight, collada.light.SpotLight)) + self.assertTupleEqual(loaded_spotlight.color, (0.1, 0.2, 0.3)) + self.assertEqual(loaded_spotlight.constant_att, 0.7) + self.assertEqual(loaded_spotlight.linear_att, 0.8) + self.assertEqual(loaded_spotlight.quad_att, 0.9) + self.assertEqual(loaded_spotlight.falloff_ang, None) + self.assertEqual(loaded_spotlight.falloff_exp, None) + self.assertEqual(loaded_spotlight.id, "yourspotlight") + + loaded_spotlight.falloff_ang = 180 + loaded_spotlight.falloff_exp = 2 + loaded_spotlight.save() + loaded_spotlight = collada.light.Light.load(self.dummy, {}, fromstring(tostring(loaded_spotlight.xmlnode))) + self.assertEqual(loaded_spotlight.falloff_ang, 180) + self.assertEqual(loaded_spotlight.falloff_exp, 2) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_lineset.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_lineset.py new file mode 100644 index 0000000000000000000000000000000000000000..f71f19907a5763dce11df59e12a894a7aab44775 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_lineset.py @@ -0,0 +1,63 @@ +import numpy +from numpy.testing import assert_array_equal +import unittest + +import collada +from collada.xmlutil import etree +from collada.common import DaeIncompleteError + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestLineset(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_lineset_construction(self): + # An empty sources dict should raise an exception. + with self.assertRaises(DaeIncompleteError) as e: + collada.lineset.LineSet({}, None, None) + self.assertIn("at least one", e.exception.msg) + + # As should passing one without VERTEX defined as a key. + with self.assertRaises(DaeIncompleteError) as e: + collada.lineset.LineSet({"a": []}, None, None) + self.assertIn("requires vertex", e.exception.msg) + + # Adding an input list with vertex defined, but empty should raise an error. + with self.assertRaises(DaeIncompleteError) as e: + collada.lineset.LineSet({'VERTEX': []}, None, None) + self.assertIn("requires vertex", e.exception.msg) + + def test_empty_lineset_saving(self): + linefloats = [1, 1, -1, 1, -1, -1, -1, -0.9999998, -1, -0.9999997, 1, -1, 1, 0.9999995, 1, 0.9999994, -1.000001, 1] + linefloatsrc = collada.source.FloatSource("mylinevertsource", numpy.array(linefloats), ('X', 'Y', 'Z')) + geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mygeometry", [linefloatsrc]) + input_list = collada.source.InputList() + input_list.addInput(0, 'VERTEX', "#mylinevertsource") + indices = numpy.array([0, 1, 1, 2, 2, 3, 3, 4, 4, 5]) + lineset = geometry.createLineSet(indices, input_list, "mymaterial") + + # Check the initial values for the lineset. + self.assertIsNotNone(str(lineset)) + assert_array_equal(lineset.index, indices) + self.assertEqual(lineset.nlines, len(indices)) + self.assertEqual(lineset.material, "mymaterial") + + # Serialize and deserialize. + lineset.save() + loaded_lineset = collada.lineset.LineSet.load(collada, {'mylinevertsource': linefloatsrc}, fromstring(tostring(lineset.xmlnode))) + + # Check that the deserialized version has all of the same properties. + self.assertEqual(loaded_lineset.sources, lineset.sources) + self.assertEqual(loaded_lineset.material, lineset.material) + assert_array_equal(loaded_lineset.index, lineset.index) + assert_array_equal(loaded_lineset.indices, lineset.indices) + self.assertEqual(loaded_lineset.nindices, lineset.nindices) + self.assertEqual(loaded_lineset.nlines, lineset.nlines) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_material.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_material.py new file mode 100644 index 0000000000000000000000000000000000000000..bdbb59820c6a43236b32664f59ff44c192365c9e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_material.py @@ -0,0 +1,300 @@ +import os +import unittest + +import collada +from collada.xmlutil import etree +from collada.material import OPAQUE_MODE + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestMaterial(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(aux_file_loader=self.image_dummy_loader, + validate_output=True) + + self.dummy_cimage = collada.material.CImage("yourcimage", "./whatever.tga", self.dummy) + self.cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + self.dummy.images.append(self.dummy_cimage) + self.dummy.images.append(self.cimage) + self.othereffect = collada.material.Effect("othereffect", [], "phong") + self.dummy.effects.append(self.othereffect) + + def test_effect_saving(self): + effect = collada.material.Effect("myeffect", [], "phong", + emission=(0.1, 0.2, 0.3, 1.0), + ambient=(0.4, 0.5, 0.6, 1.0), + diffuse=(0.7, 0.8, 0.9, 0.5), + specular=(0.3, 0.2, 0.1, 1.0), + shininess=0.4, + reflective=(0.7, 0.6, 0.5, 1.0), + reflectivity=0.8, + transparent=(0.2, 0.4, 0.6, 1.0), + transparency=0.9) + + self.assertEqual(effect.id, "myeffect") + self.assertEqual(effect.shininess, 0.4) + self.assertEqual(effect.reflectivity, 0.8) + self.assertEqual(effect.transparency, 0.9) + self.assertTupleEqual(effect.emission, (0.1, 0.2, 0.3, 1.0)) + self.assertTupleEqual(effect.ambient, (0.4, 0.5, 0.6, 1.0)) + self.assertTupleEqual(effect.diffuse, (0.7, 0.8, 0.9, 0.5)) + self.assertTupleEqual(effect.specular, (0.3, 0.2, 0.1, 1.0)) + self.assertTupleEqual(effect.reflective, (0.7, 0.6, 0.5, 1.0)) + self.assertTupleEqual(effect.transparent, (0.2, 0.4, 0.6, 1.0)) + self.assertEqual(effect.double_sided, False) + self.assertEqual(effect.opaque_mode, OPAQUE_MODE.A_ONE) + self.assertIsNotNone(str(effect)) + + effect.id = "youreffect" + effect.shininess = 7.0 + effect.reflectivity = 2.0 + effect.transparency = 3.0 + effect.emission = (1.1, 1.2, 1.3, 1.0) + effect.ambient = (1.4, 1.5, 1.6, 1.0) + effect.diffuse = (1.7, 1.8, 1.9, 1.0) + effect.specular = (1.3, 1.2, 1.1, 1.0) + effect.reflective = (1.7, 1.6, 1.5, 0.3) + effect.transparent = (1.2, 1.4, 1.6, 1.0) + effect.opaque_mode = OPAQUE_MODE.RGB_ZERO + effect.double_sided = True + effect.save() + + loaded_effect = collada.material.Effect.load(self.dummy, {}, + fromstring(tostring(effect.xmlnode))) + + self.assertEqual(loaded_effect.id, "youreffect") + self.assertEqual(loaded_effect.shininess, 7.0) + self.assertEqual(loaded_effect.reflectivity, 2.0) + self.assertEqual(loaded_effect.transparency, 3.0) + self.assertTupleEqual(loaded_effect.emission, (1.1, 1.2, 1.3, 1.0)) + self.assertTupleEqual(loaded_effect.ambient, (1.4, 1.5, 1.6, 1.0)) + self.assertTupleEqual(loaded_effect.diffuse, (1.7, 1.8, 1.9, 1.0)) + self.assertTupleEqual(loaded_effect.specular, (1.3, 1.2, 1.1, 1.0)) + self.assertTupleEqual(loaded_effect.reflective, (1.7, 1.6, 1.5, 0.3)) + self.assertTupleEqual(loaded_effect.transparent, (1.2, 1.4, 1.6, 1.0)) + self.assertEqual(loaded_effect.opaque_mode, OPAQUE_MODE.RGB_ZERO) + self.assertEqual(loaded_effect.double_sided, True) + + def image_dummy_loader(self, fname): + return self.image_return + + def test_cimage_saving(self): + self.image_return = None + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + self.assertEqual(cimage.id, "mycimage") + self.assertEqual(cimage.path, "./whatever.tga") + cimage.id = "yourcimage" + cimage.path = "./next.tga" + cimage.save() + loaded_cimage = collada.material.CImage.load(self.dummy, {}, fromstring(tostring(cimage.xmlnode))) + self.assertEqual(loaded_cimage.id, "yourcimage") + self.assertEqual(loaded_cimage.path, "./next.tga") + with self.assertRaises(collada.DaeBrokenRefError): + loaded_cimage.data + self.assertEqual(loaded_cimage.data, '') + self.assertEqual(loaded_cimage.pilimage, None) + self.assertEqual(loaded_cimage.uintarray, None) + self.assertEqual(loaded_cimage.floatarray, None) + self.assertIsNotNone(str(cimage)) + + def test_cimage_data_loading(self): + data_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), "data") + texture_file_path = os.path.join(data_dir, "duckCM.tga") + self.assertTrue(os.path.isfile(texture_file_path), "Could not find data/duckCM.tga file for testing") + + texdata = open(texture_file_path, 'rb').read() + self.assertEqual(len(texdata), 786476) + + self.image_return = texdata + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + image_data = cimage.data + self.assertEqual(len(image_data), 786476) + + try: + from PIL import Image as pil + except ImportError: + pil = None + + if pil is not None: + pil_image = cimage.pilimage + self.assertTupleEqual(pil_image.size, (512, 512)) + self.assertEqual(pil_image.format, "TGA") + + numpy_uints = cimage.uintarray + self.assertTupleEqual(numpy_uints.shape, (512, 512, 3)) + self.assertTupleEqual(numpy_uints.shape, (512, 512, 3)) + + def test_surface_saving(self): + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + surface = collada.material.Surface("mysurface", cimage) + self.assertEqual(surface.id, "mysurface") + self.assertEqual(surface.image.id, "mycimage") + self.assertEqual(surface.format, "A8R8G8B8") + self.assertIsNotNone(str(surface)) + surface.id = "yoursurface" + surface.image = self.dummy_cimage + surface.format = "OtherFormat" + surface.save() + loaded_surface = collada.material.Surface.load(self.dummy, {}, fromstring(tostring(surface.xmlnode))) + self.assertEqual(loaded_surface.id, "yoursurface") + self.assertEqual(loaded_surface.image.id, "yourcimage") + self.assertEqual(loaded_surface.format, "OtherFormat") + + def test_surface_empty(self): + surface1 = """ + + file1-image + A8R8G8B8 + + """ + self.assertRaises(collada.DaeIncompleteError, collada.material.Surface.load, self.dummy, {}, fromstring(surface1)) + + surface2 = """ + + + file1-image + A8R8G8B8 + + + """ + self.assertRaises(collada.DaeBrokenRefError, collada.material.Surface.load, self.dummy, {}, fromstring(surface2)) + + surface3 = """ + + + + A8R8G8B8 + + + """ + self.assertRaises(collada.DaeBrokenRefError, collada.material.Surface.load, self.dummy, {}, fromstring(surface3)) + + def test_sampler2d_saving(self): + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + surface = collada.material.Surface("mysurface", cimage) + sampler2d = collada.material.Sampler2D("mysampler2d", surface) + self.assertEqual(sampler2d.id, "mysampler2d") + self.assertEqual(sampler2d.minfilter, None) + self.assertEqual(sampler2d.magfilter, None) + self.assertEqual(sampler2d.surface.id, "mysurface") + sampler2d = collada.material.Sampler2D("mysampler2d", surface, "LINEAR_MIPMAP_LINEAR", "LINEAR") + self.assertEqual(sampler2d.minfilter, "LINEAR_MIPMAP_LINEAR") + self.assertEqual(sampler2d.magfilter, "LINEAR") + self.assertIsNotNone(str(sampler2d)) + + other_surface = collada.material.Surface("yoursurface", cimage) + sampler2d.id = "yoursampler2d" + sampler2d.minfilter = "QUADRATIC_MIPMAP_WHAT" + sampler2d.magfilter = "QUADRATIC" + sampler2d.surface = other_surface + sampler2d.save() + + loaded_sampler2d = collada.material.Sampler2D.load(self.dummy, + {'yoursurface': other_surface}, fromstring(tostring(sampler2d.xmlnode))) + self.assertEqual(loaded_sampler2d.id, "yoursampler2d") + self.assertEqual(loaded_sampler2d.surface.id, "yoursurface") + self.assertEqual(loaded_sampler2d.minfilter, "QUADRATIC_MIPMAP_WHAT") + self.assertEqual(loaded_sampler2d.magfilter, "QUADRATIC") + + def test_map_saving(self): + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + surface = collada.material.Surface("mysurface", cimage) + sampler2d = collada.material.Sampler2D("mysampler2d", surface) + map = collada.material.Map(sampler2d, "TEX0") + self.assertEqual(map.sampler.id, "mysampler2d") + self.assertEqual(map.texcoord, "TEX0") + self.assertIsNotNone(str(map)) + + other_sampler2d = collada.material.Sampler2D("yoursampler2d", surface) + map.sampler = other_sampler2d + map.texcoord = "TEX1" + map.save() + + loaded_map = collada.material.Map.load( + self.dummy, + {'yoursampler2d': other_sampler2d}, fromstring(tostring(map.xmlnode))) + + assert loaded_map is not None + self.assertEqual(map.sampler.id, "yoursampler2d") + self.assertEqual(map.texcoord, "TEX1") + + def test_effect_with_params(self): + surface = collada.material.Surface("mysurface", self.cimage) + sampler2d = collada.material.Sampler2D("mysampler2d", surface) + effect = collada.material.Effect("myeffect", [surface, sampler2d], "phong", + emission=(0.1, 0.2, 0.3, 1.0), + ambient=(0.4, 0.5, 0.6, 1.0), + diffuse=(0.7, 0.8, 0.9, 1.0), + specular=(0.3, 0.2, 0.1, 1.0), + shininess=0.4, + reflective=(0.7, 0.6, 0.5, 1.0), + reflectivity=0.8, + transparent=(0.2, 0.4, 0.6, 1.0), + transparency=0.9, + opaque_mode=OPAQUE_MODE.A_ONE) + + other_cimage = collada.material.CImage("yourcimage", "./whatever.tga", self.dummy) + other_surface = collada.material.Surface("yoursurface", other_cimage) + other_sampler2d = collada.material.Sampler2D("yoursampler2d", other_surface) + other_map = collada.material.Map(other_sampler2d, "TEX0") + effect.params.pop() + effect.params.append(other_surface) + effect.params.append(other_sampler2d) + effect.diffuse = other_map + effect.transparent = other_map + effect.save() + + self.dummy.images.append(self.dummy_cimage) + loaded_effect = collada.material.Effect.load(self.dummy, {}, fromstring(tostring(effect.xmlnode))) + self.assertEqual(type(loaded_effect.diffuse), collada.material.Map) + self.assertEqual(type(loaded_effect.transparent), collada.material.Map) + self.assertEqual(len(loaded_effect.params), 3) + self.assertTrue(isinstance(loaded_effect.params[0], collada.material.Surface)) + self.assertEqual(loaded_effect.params[0].id, "mysurface") + self.assertTrue(isinstance(loaded_effect.params[1], collada.material.Surface)) + self.assertEqual(loaded_effect.params[1].id, "yoursurface") + self.assertTrue(isinstance(loaded_effect.params[2], collada.material.Sampler2D)) + self.assertEqual(loaded_effect.params[2].id, "yoursampler2d") + self.assertEqual(loaded_effect.opaque_mode, OPAQUE_MODE.A_ONE) + + def test_rgbzero(self): + effect = collada.material.Effect("myeffect", [], "phong", + opaque_mode=OPAQUE_MODE.RGB_ZERO) + + self.assertEqual(effect.opaque_mode, OPAQUE_MODE.RGB_ZERO) + self.assertEqual(effect.transparency, 0.0) + effect.save() + + loaded_effect = collada.material.Effect.load(self.dummy, {}, fromstring(tostring(effect.xmlnode))) + self.assertEqual(loaded_effect.opaque_mode, OPAQUE_MODE.RGB_ZERO) + + effect = collada.material.Effect("myeffect", [], "phong") + + self.assertEqual(effect.opaque_mode, OPAQUE_MODE.A_ONE) + self.assertEqual(effect.transparency, 1.0) + effect.save() + + def test_material_saving(self): + effect = collada.material.Effect("myeffect", [], "phong") + mat = collada.material.Material("mymaterial", "mymat", effect) + self.assertEqual(mat.id, "mymaterial") + self.assertEqual(mat.name, "mymat") + self.assertEqual(mat.effect, effect) + self.assertIsNotNone(str(mat)) + + mat.id = "yourmaterial" + mat.name = "yourmat" + mat.effect = self.othereffect + mat.save() + + loaded_mat = collada.material.Material.load(self.dummy, {}, fromstring(tostring(mat.xmlnode))) + self.assertEqual(loaded_mat.id, "yourmaterial") + self.assertEqual(loaded_mat.name, "yourmat") + self.assertEqual(loaded_mat.effect.id, self.othereffect.id) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_scene.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_scene.py new file mode 100644 index 0000000000000000000000000000000000000000..7af108fbdcd8a54fcdbfeb1fb271b4a4fd483077 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_scene.py @@ -0,0 +1,340 @@ +import numpy +import unittest + +import collada +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestScene(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + self.yourcam = collada.camera.PerspectiveCamera("yourcam", 45.0, 0.01, 1000.0) + self.dummy.cameras.append(self.yourcam) + + self.yourdirlight = collada.light.DirectionalLight("yourdirlight", (1, 1, 1)) + self.dummy.lights.append(self.yourdirlight) + + cimage = collada.material.CImage("mycimage", "./whatever.tga", self.dummy) + surface = collada.material.Surface("mysurface", cimage) + sampler2d = collada.material.Sampler2D("mysampler2d", surface) + mymap = collada.material.Map(sampler2d, "TEX0") + self.effect = collada.material.Effect("myeffect", [surface, sampler2d], "phong", + emission=(0.1, 0.2, 0.3), + ambient=(0.4, 0.5, 0.6), + diffuse=mymap, + specular=(0.3, 0.2, 0.1)) + self.effect2 = collada.material.Effect("youreffect", [], "phong", + emission=(0.1, 0.2, 0.3), + ambient=(0.4, 0.5, 0.6), + specular=(0.3, 0.2, 0.1)) + self.dummy.materials.append(self.effect) + self.dummy.materials.append(self.effect2) + + self.floatsource = collada.source.FloatSource("myfloatsource", numpy.array([0.1, 0.2, 0.3]), ('X', 'Y', 'Z')) + self.geometry = collada.geometry.Geometry(self.dummy, "geometry0", "mygeometry", {"myfloatsource": self.floatsource}) + self.geometry2 = collada.geometry.Geometry(self.dummy, "geometry1", "yourgeometry", {"myfloatsource": self.floatsource}) + self.dummy.geometries.append(self.geometry) + self.dummy.geometries.append(self.geometry2) + + def test_scene_light_node_saving(self): + dirlight = collada.light.DirectionalLight("mydirlight", (1, 1, 1)) + lightnode = collada.scene.LightNode(dirlight) + bindtest = list(lightnode.objects('light')) + self.assertEqual(lightnode.light, dirlight) + self.assertEqual(len(bindtest), 1) + self.assertEqual(bindtest[0].original, dirlight) + self.assertIsNotNone(str(lightnode)) + + lightnode.light = self.yourdirlight + lightnode.save() + + loadedlightnode = collada.scene.LightNode.load(self.dummy, fromstring(tostring(lightnode.xmlnode))) + self.assertEqual(loadedlightnode.light.id, 'yourdirlight') + + def test_scene_camera_node_saving(self): + cam = collada.camera.PerspectiveCamera("mycam", 45.0, 0.01, 1000.0) + camnode = collada.scene.CameraNode(cam) + bindtest = list(camnode.objects('camera')) + self.assertEqual(camnode.camera, cam) + self.assertEqual(len(bindtest), 1) + self.assertEqual(bindtest[0].original, cam) + self.assertIsNotNone(str(camnode)) + + camnode.camera = self.yourcam + camnode.save() + + loadedcamnode = collada.scene.CameraNode.load(self.dummy, fromstring(tostring(camnode.xmlnode))) + self.assertEqual(loadedcamnode.camera.id, 'yourcam') + + def test_scene_translate_node(self): + translate = collada.scene.TranslateTransform(0.1, 0.2, 0.3) + self.assertAlmostEqual(translate.x, 0.1) + self.assertAlmostEqual(translate.y, 0.2) + self.assertAlmostEqual(translate.z, 0.3) + self.assertIsNotNone(str(translate)) + loaded_translate = collada.scene.TranslateTransform.load(self.dummy, fromstring(tostring(translate.xmlnode))) + self.assertAlmostEqual(loaded_translate.x, 0.1) + self.assertAlmostEqual(loaded_translate.y, 0.2) + self.assertAlmostEqual(loaded_translate.z, 0.3) + + def test_scene_rotate_node(self): + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + self.assertAlmostEqual(rotate.x, 0.1) + self.assertAlmostEqual(rotate.y, 0.2) + self.assertAlmostEqual(rotate.z, 0.3) + self.assertAlmostEqual(rotate.angle, 90) + self.assertIsNotNone(str(rotate)) + loaded_rotate = collada.scene.RotateTransform.load(self.dummy, fromstring(tostring(rotate.xmlnode))) + self.assertAlmostEqual(loaded_rotate.x, 0.1) + self.assertAlmostEqual(loaded_rotate.y, 0.2) + self.assertAlmostEqual(loaded_rotate.z, 0.3) + self.assertAlmostEqual(loaded_rotate.angle, 90) + + def test_scene_scale_node(self): + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + self.assertAlmostEqual(scale.x, 0.1) + self.assertAlmostEqual(scale.y, 0.2) + self.assertAlmostEqual(scale.z, 0.3) + self.assertIsNotNone(str(scale)) + loaded_scale = collada.scene.ScaleTransform.load(self.dummy, fromstring(tostring(scale.xmlnode))) + self.assertAlmostEqual(loaded_scale.x, 0.1) + self.assertAlmostEqual(loaded_scale.y, 0.2) + self.assertAlmostEqual(loaded_scale.z, 0.3) + + def test_scene_matrix_node(self): + matrix = collada.scene.MatrixTransform(numpy.array([1.0, 0, 0, 2, 0, 1, 0, 3, 0, 0, 1, 4, 0, 0, 0, 1])) + self.assertAlmostEqual(matrix.matrix[0][0], 1.0) + self.assertIsNotNone(str(matrix)) + loaded_matrix = collada.scene.MatrixTransform.load(self.dummy, fromstring(tostring(matrix.xmlnode))) + self.assertAlmostEqual(loaded_matrix.matrix[0][0], 1.0) + + def test_scene_lookat_node(self): + eye = numpy.array([2.0, 0, 3]) + interest = numpy.array([0.0, 0, 0]) + upvector = numpy.array([0.0, 1, 0]) + lookat = collada.scene.LookAtTransform(eye, interest, upvector) + self.assertListEqual(list(lookat.eye), list(eye)) + self.assertListEqual(list(lookat.interest), list(interest)) + self.assertListEqual(list(lookat.upvector), list(upvector)) + self.assertIsNotNone(str(lookat)) + loaded_lookat = collada.scene.LookAtTransform.load(self.dummy, fromstring(tostring(lookat.xmlnode))) + self.assertListEqual(list(loaded_lookat.eye), list(eye)) + self.assertListEqual(list(loaded_lookat.interest), list(interest)) + self.assertListEqual(list(loaded_lookat.upvector), list(upvector)) + + def test_scene_node_combos(self): + emptynode = collada.scene.Node('myemptynode') + self.assertEqual(len(emptynode.children), 0) + self.assertEqual(len(emptynode.transforms), 0) + self.assertIsNotNone(str(emptynode)) + loadedempty = collada.scene.Node.load(self.dummy, fromstring(tostring(emptynode.xmlnode)), {}) + self.assertEqual(len(loadedempty.children), 0) + self.assertEqual(len(loadedempty.transforms), 0) + + justchildren = collada.scene.Node('myjustchildrennode', children=[emptynode]) + self.assertEqual(len(justchildren.children), 1) + self.assertEqual(len(justchildren.transforms), 0) + self.assertEqual(justchildren.children[0], emptynode) + loadedjustchildren = collada.scene.Node.load(self.dummy, fromstring(tostring(justchildren.xmlnode)), {}) + self.assertEqual(len(loadedjustchildren.children), 1) + self.assertEqual(len(loadedjustchildren.transforms), 0) + + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + justtransform = collada.scene.Node('myjusttransformnode', transforms=[scale]) + self.assertEqual(len(justtransform.children), 0) + self.assertEqual(len(justtransform.transforms), 1) + self.assertEqual(justtransform.transforms[0], scale) + loadedjusttransform = collada.scene.Node.load(self.dummy, fromstring(tostring(justtransform.xmlnode)), {}) + self.assertEqual(len(loadedjusttransform.children), 0) + self.assertEqual(len(loadedjusttransform.transforms), 1) + + both = collada.scene.Node('mybothnode', children=[justchildren, justtransform], transforms=[scale]) + self.assertEqual(len(both.children), 2) + self.assertEqual(len(both.transforms), 1) + self.assertEqual(both.transforms[0], scale) + self.assertEqual(both.children[0], justchildren) + self.assertEqual(both.children[1], justtransform) + collada.scene.Node.load(self.dummy, fromstring(tostring(both.xmlnode)), {}) + self.assertEqual(len(both.children), 2) + self.assertEqual(len(both.transforms), 1) + + def test_scene_node_saving(self): + myemptynode = collada.scene.Node('myemptynode') + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + mynode = collada.scene.Node('mynode', children=[myemptynode], transforms=[rotate, scale]) + self.assertEqual(mynode.id, 'mynode') + self.assertEqual(mynode.name, 'mynode') + self.assertEqual(mynode.children[0], myemptynode) + self.assertEqual(mynode.transforms[0], rotate) + self.assertEqual(mynode.transforms[1], scale) + + translate = collada.scene.TranslateTransform(0.1, 0.2, 0.3) + mynode.transforms.append(translate) + mynode.transforms.pop(0) + youremptynode = collada.scene.Node('youremptynode') + mynode.children.append(youremptynode) + mynode.id = 'yournode' + mynode.save() + + yournode = collada.scene.Node.load(self.dummy, fromstring(tostring(mynode.xmlnode)), {}) + self.assertEqual(yournode.id, 'yournode') + self.assertEqual(yournode.name, 'mynode') + self.assertEqual(len(yournode.children), 2) + self.assertEqual(len(yournode.transforms), 2) + self.assertEqual(yournode.children[0].id, 'myemptynode') + self.assertEqual(yournode.children[1].id, 'youremptynode') + self.assertTrue(isinstance(yournode.transforms[0], collada.scene.ScaleTransform)) + self.assertTrue(isinstance(yournode.transforms[1], collada.scene.TranslateTransform)) + + translate = collada.scene.TranslateTransform(0.1, 0.2, 0.3) + mynode.transforms.append(translate) + mynode.transforms.pop(0) + youremptynode = collada.scene.Node('youremptynode') + mynode.children.append(youremptynode) + mynode.id = 'yournode' + mynode.name = 'yourname' + mynode.save() + + yournode = collada.scene.Node.load(self.dummy, fromstring(tostring(mynode.xmlnode)), {}) + self.assertEqual(yournode.id, 'yournode') + self.assertEqual(yournode.name, 'yourname') + + myemptynode = collada.scene.Node('myemptynode') + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + mynode = collada.scene.Node('mynode', children=[myemptynode], transforms=[rotate, scale]) + self.assertEqual(mynode.id, 'mynode') + self.assertEqual(mynode.name, 'mynode') + mynode = collada.scene.Node('othernode', children=[myemptynode], transforms=[rotate, scale], name='othername') + self.assertEqual(mynode.id, 'othernode') + self.assertEqual(mynode.name, 'othername') + + def test_scene_material_node(self): + binding1 = ("TEX0", "TEXCOORD", "0") + binding2 = ("TEX1", "TEXCOORD", "1") + binding3 = ("TEX2", "TEXCOORD", "2") + matnode = collada.scene.MaterialNode("mygeommatref", self.effect, [binding1, binding2]) + + self.assertEqual(matnode.target, self.effect) + self.assertEqual(matnode.symbol, "mygeommatref") + self.assertListEqual(matnode.inputs, [binding1, binding2]) + self.assertIsNotNone(str(matnode)) + matnode.save() + self.assertEqual(matnode.target, self.effect) + self.assertEqual(matnode.symbol, "mygeommatref") + self.assertListEqual(matnode.inputs, [binding1, binding2]) + + matnode.symbol = 'yourgeommatref' + matnode.target = self.effect2 + matnode.inputs.append(binding3) + matnode.inputs.pop(0) + matnode.save() + + loaded_matnode = collada.scene.MaterialNode.load(self.dummy, fromstring(tostring(matnode.xmlnode))) + self.assertEqual(loaded_matnode.target.id, self.effect2.id) + self.assertEqual(loaded_matnode.symbol, "yourgeommatref") + self.assertListEqual(loaded_matnode.inputs, [binding2, binding3]) + + def test_scene_geometry_node(self): + binding = ("TEX0", "TEXCOORD", "0") + matnode = collada.scene.MaterialNode("mygeommatref", self.effect, [binding]) + geomnode = collada.scene.GeometryNode(self.geometry, [matnode]) + + bindtest = list(geomnode.objects('geometry')) + self.assertEqual(len(bindtest), 1) + self.assertEqual(bindtest[0].original, self.geometry) + self.assertEqual(geomnode.geometry, self.geometry) + self.assertListEqual(geomnode.materials, [matnode]) + self.assertIsNotNone(str(geomnode)) + geomnode.save() + bindtest = list(geomnode.objects('geometry')) + self.assertEqual(len(bindtest), 1) + self.assertEqual(bindtest[0].original, self.geometry) + self.assertEqual(geomnode.geometry, self.geometry) + self.assertListEqual(geomnode.materials, [matnode]) + + matnode2 = collada.scene.MaterialNode("yourgeommatref", self.effect, [binding]) + geomnode.materials.append(matnode2) + geomnode.materials.pop(0) + geomnode.geometry = self.geometry2 + geomnode.save() + + loaded_geomnode = collada.scene.loadNode(self.dummy, fromstring(tostring(geomnode.xmlnode)), {}) + self.assertEqual(loaded_geomnode.geometry.id, self.geometry2.id) + self.assertEqual(len(loaded_geomnode.materials), 1) + self.assertEqual(loaded_geomnode.materials[0].target, matnode2.target) + self.assertEqual(loaded_geomnode.materials[0].symbol, "yourgeommatref") + self.assertListEqual(loaded_geomnode.materials[0].inputs, [binding]) + + def test_scene_node_with_instances(self): + binding = ("TEX0", "TEXCOORD", "0") + matnode = collada.scene.MaterialNode("mygeommatref", self.effect, [binding]) + geomnode = collada.scene.GeometryNode(self.geometry, [matnode]) + camnode = collada.scene.CameraNode(self.yourcam) + lightnode = collada.scene.LightNode(self.yourdirlight) + myemptynode = collada.scene.Node('myemptynode') + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + mynode = collada.scene.Node('mynode', + children=[myemptynode, geomnode, camnode, lightnode], + transforms=[rotate, scale]) + + self.assertEqual(len(mynode.children), 4) + self.assertEqual(mynode.children[0], myemptynode) + self.assertEqual(mynode.children[1], geomnode) + self.assertEqual(mynode.children[2], camnode) + self.assertEqual(mynode.children[3], lightnode) + self.assertEqual(mynode.transforms[0], rotate) + self.assertEqual(mynode.transforms[1], scale) + + mynode.id = 'yournode' + mynode.children.pop(0) + mynode.save() + + yournode = collada.scene.Node.load(self.dummy, fromstring(tostring(mynode.xmlnode)), {}) + self.assertEqual(yournode.id, 'yournode') + self.assertEqual(len(yournode.children), 3) + self.assertEqual(len(yournode.transforms), 2) + self.assertEqual(yournode.children[0].geometry.id, self.geometry.id) + self.assertEqual(yournode.children[1].camera.id, self.yourcam.id) + self.assertEqual(yournode.children[2].light.id, self.yourdirlight.id) + self.assertTrue(isinstance(yournode.transforms[0], collada.scene.RotateTransform)) + self.assertTrue(isinstance(yournode.transforms[1], collada.scene.ScaleTransform)) + + def test_scene_with_nodes(self): + rotate = collada.scene.RotateTransform(0.1, 0.2, 0.3, 90) + scale = collada.scene.ScaleTransform(0.1, 0.2, 0.3) + mynode = collada.scene.Node('mynode', children=[], transforms=[rotate, scale]) + yournode = collada.scene.Node('yournode', children=[], transforms=[]) + othernode = collada.scene.Node('othernode', children=[], transforms=[]) + scene = collada.scene.Scene('myscene', [mynode, yournode, othernode]) + + self.assertEqual(scene.id, 'myscene') + self.assertEqual(len(scene.nodes), 3) + self.assertEqual(scene.nodes[0], mynode) + self.assertEqual(scene.nodes[1], yournode) + self.assertEqual(scene.nodes[2], othernode) + + scene.id = 'yourscene' + scene.nodes.pop(1) + anothernode = collada.scene.Node('anothernode') + scene.nodes.append(anothernode) + scene.save() + + loaded_scene = collada.scene.Scene.load(self.dummy, fromstring(tostring(scene.xmlnode))) + + self.assertEqual(loaded_scene.id, 'yourscene') + self.assertEqual(len(loaded_scene.nodes), 3) + self.assertEqual(loaded_scene.nodes[0].id, 'mynode') + self.assertEqual(loaded_scene.nodes[1].id, 'othernode') + self.assertEqual(loaded_scene.nodes[2].id, 'anothernode') + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_source.py b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_source.py new file mode 100644 index 0000000000000000000000000000000000000000..2b8aadeeea0ac97bebef1e21b685853470a615dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/collada/tests/test_source.py @@ -0,0 +1,70 @@ +import numpy +import unittest + +import collada +from collada.xmlutil import etree + +fromstring = etree.fromstring +tostring = etree.tostring + + +class TestSource(unittest.TestCase): + + def setUp(self): + self.dummy = collada.Collada(validate_output=True) + + def test_float_source_saving(self): + floatsource = collada.source.FloatSource("myfloatsource", numpy.array([0.1, 0.2, 0.3]), ('X', 'Y', 'X')) + self.assertEqual(floatsource.id, "myfloatsource") + self.assertEqual(len(floatsource), 1) + self.assertTupleEqual(floatsource.components, ('X', 'Y', 'X')) + self.assertIsNotNone(str(floatsource)) + floatsource.id = "yourfloatsource" + floatsource.components = ('S', 'T') + floatsource.data = numpy.array([0.4, 0.5, 0.6, 0.7, 0.8, 0.9]) + floatsource.save() + loaded_floatsource = collada.source.Source.load(self.dummy, {}, fromstring(tostring(floatsource.xmlnode))) + self.assertTrue(isinstance(loaded_floatsource, collada.source.FloatSource)) + self.assertEqual(floatsource.id, "yourfloatsource") + self.assertEqual(len(floatsource), 3) + self.assertTupleEqual(floatsource.components, ('S', 'T')) + + def test_idref_source_saving(self): + idrefsource = collada.source.IDRefSource("myidrefsource", + numpy.array(['Ref1', 'Ref2'], dtype=numpy.bytes_), + ('MORPH_TARGET',)) + self.assertEqual(idrefsource.id, "myidrefsource") + self.assertEqual(len(idrefsource), 2) + self.assertTupleEqual(idrefsource.components, ('MORPH_TARGET',)) + self.assertIsNotNone(str(idrefsource)) + idrefsource.id = "youridrefsource" + idrefsource.components = ('JOINT_TARGET', 'WHATEVER_TARGET') + idrefsource.data = numpy.array(['Ref5', 'Ref6', 'Ref7', 'Ref8', 'Ref9', 'Ref10'], dtype=numpy.bytes_) + idrefsource.save() + loaded_idrefsource = collada.source.Source.load(self.dummy, {}, fromstring(tostring(idrefsource.xmlnode))) + self.assertTrue(isinstance(loaded_idrefsource, collada.source.IDRefSource)) + self.assertEqual(loaded_idrefsource.id, "youridrefsource") + self.assertEqual(len(loaded_idrefsource), 3) + self.assertTupleEqual(loaded_idrefsource.components, ('JOINT_TARGET', 'WHATEVER_TARGET')) + + def test_name_source_saving(self): + namesource = collada.source.NameSource("mynamesource", + numpy.array(['Name1', 'Name2'], dtype=numpy.bytes_), + ('JOINT',)) + self.assertEqual(namesource.id, "mynamesource") + self.assertEqual(len(namesource), 2) + self.assertTupleEqual(namesource.components, ('JOINT',)) + self.assertIsNotNone(str(namesource)) + namesource.id = "yournamesource" + namesource.components = ('WEIGHT', 'WHATEVER') + namesource.data = numpy.array(['Name1', 'Name2', 'Name3', 'Name4', 'Name5', 'Name6'], dtype=numpy.bytes_) + namesource.save() + loaded_namesource = collada.source.Source.load(self.dummy, {}, fromstring(tostring(namesource.xmlnode))) + self.assertTrue(isinstance(loaded_namesource, collada.source.NameSource)) + self.assertEqual(loaded_namesource.id, "yournamesource") + self.assertEqual(len(loaded_namesource), 3) + self.assertTupleEqual(loaded_namesource.components, ('WEIGHT', 'WHATEVER')) + + +if __name__ == '__main__': + unittest.main() diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat b/data/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat new file mode 100644 index 0000000000000000000000000000000000000000..c8ee68989b53660ff2016bac41cd2d6fdc920fb4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/shell/Library/bin/conda.bat @@ -0,0 +1,3 @@ +:: Copyright (C) 2012 Anaconda, Inc +:: SPDX-License-Identifier: BSD-3-Clause +@CALL "%~dp0..\..\condabin\conda.bat" %* diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish new file mode 100644 index 0000000000000000000000000000000000000000..ea27d135ac1466eecde4d75b4d6305857ca490b0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/fish/conf.d/conda.fish @@ -0,0 +1,133 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +# +# INSTALL +# +# Run 'conda init fish' and restart your shell. +# + +if not set -q CONDA_SHLVL + set -gx CONDA_SHLVL 0 + set -g _CONDA_ROOT (dirname (dirname $CONDA_EXE)) + set -gx PATH $_CONDA_ROOT/condabin $PATH +end + +function __conda_add_prompt + if set -q CONDA_PROMPT_MODIFIER + set_color -o green + echo -n $CONDA_PROMPT_MODIFIER + set_color normal + end +end + +if functions -q fish_prompt + if not functions -q __fish_prompt_orig + functions -c fish_prompt __fish_prompt_orig + end + functions -e fish_prompt +else + function __fish_prompt_orig + end +end + +function return_last_status + return $argv +end + +function fish_prompt + set -l last_status $status + if set -q CONDA_LEFT_PROMPT + __conda_add_prompt + end + return_last_status $last_status + __fish_prompt_orig +end + +if functions -q fish_right_prompt + if not functions -q __fish_right_prompt_orig + functions -c fish_right_prompt __fish_right_prompt_orig + end + functions -e fish_right_prompt +else + function __fish_right_prompt_orig + end +end + +function fish_right_prompt + if not set -q CONDA_LEFT_PROMPT + __conda_add_prompt + end + __fish_right_prompt_orig +end + + +function conda --inherit-variable CONDA_EXE + if [ (count $argv) -lt 1 ] + $CONDA_EXE + else + set -l cmd $argv[1] + set -e argv[1] + switch $cmd + case activate deactivate + eval ($CONDA_EXE shell.fish $cmd $argv) + case install update upgrade remove uninstall + $CONDA_EXE $cmd $argv + and eval ($CONDA_EXE shell.fish reactivate) + case '*' + $CONDA_EXE $cmd $argv + end + end +end + + + + +# Autocompletions below + + +function __fish_conda_commands + conda commands +end + +function __fish_conda_env_commands + string replace -r '.*_([a-z]+)\.py$' '$1' $_CONDA_ROOT/lib/python*/site-packages/conda_env/cli/main_*.py +end + +function __fish_conda_envs + conda config --json --show envs_dirs | python -c "import json, os, sys; from os.path import isdir, join; print('\n'.join(d for ed in json.load(sys.stdin)['envs_dirs'] if isdir(ed) for d in os.listdir(ed) if isdir(join(ed, d))))" +end + +function __fish_conda_packages + conda list | awk 'NR > 3 {print $1}' +end + +function __fish_conda_needs_command + set cmd (commandline -opc) + if [ (count $cmd) -eq 1 -a $cmd[1] = conda ] + return 0 + end + return 1 +end + +function __fish_conda_using_command + set cmd (commandline -opc) + if [ (count $cmd) -gt 1 ] + if [ $argv[1] = $cmd[2] ] + return 0 + end + end + return 1 +end + +# Conda commands +complete -f -c conda -n __fish_conda_needs_command -a '(__fish_conda_commands)' +complete -f -c conda -n '__fish_conda_using_command env' -a '(__fish_conda_env_commands)' + +# Commands that need environment as parameter +complete -f -c conda -n '__fish_conda_using_command activate' -a '(__fish_conda_envs)' + +# Commands that need package as parameter +complete -f -c conda -n '__fish_conda_using_command remove' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command uninstall' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command upgrade' -a '(__fish_conda_packages)' +complete -f -c conda -n '__fish_conda_using_command update' -a '(__fish_conda_packages)' diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh new file mode 100644 index 0000000000000000000000000000000000000000..7e48cc9cfd8408d6d8665c02ac8f39d0b783fa53 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.csh @@ -0,0 +1,55 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +if (! $?_CONDA_EXE) then + set _CONDA_EXE="${PWD}/conda/shell/bin/conda" +else + if ("$_CONDA_EXE" == "") then + set _CONDA_EXE="${PWD}/conda/shell/bin/conda" + endif +endif + +if ("`alias conda`" == "") then + if ($?_CONDA_EXE) then + # _CONDA_PFX is named so as not to cause confusion with CONDA_PREFIX + # If nested backticks were possible we wouldn't use any variables here. + set _CONDA_PFX=`dirname "${_CONDA_EXE}"` + set _CONDA_PFX=`dirname "${_CONDA_PFX}"` + alias conda source "${_CONDA_PFX}/etc/profile.d/conda.csh" + # And for good measure, get rid of it afterwards. + unset _CONDA_PFX + else + alias conda source "${PWD}/conda/shell/etc/profile.d/conda.csh" + endif + setenv CONDA_SHLVL 0 + if (! $?prompt) then + set prompt="" + endif +else + switch ( "${1}" ) + case "activate": + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh activate '${2}' ${argv[3-]})`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + case "deactivate": + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh deactivate '${2}' ${argv[3-]})`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + case "install" | "update" | "upgrade" | "remove" | "uninstall": + $_CONDA_EXE $argv[1-] + set ask_conda="`(setenv prompt '${prompt}' ; '${_CONDA_EXE}' shell.csh reactivate)`" + set conda_tmp_status=$status + if( $conda_tmp_status != 0 ) exit ${conda_tmp_status} + eval "${ask_conda}" + rehash + breaksw + default: + $_CONDA_EXE $argv[1-] + breaksw + endsw +endif diff --git a/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a24b3a97f2489a2be04b0810d324efaa8f4cbf7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/conda/shell/etc/profile.d/conda.sh @@ -0,0 +1,74 @@ +# Copyright (C) 2012 Anaconda, Inc +# SPDX-License-Identifier: BSD-3-Clause +__conda_exe() ( + if [ -n "${_CE_M:+x}" ] && [ -n "${_CE_CONDA:+x}" ]; then + # only use _CE_M/_CE_CONDA when defined to avoid issues when run with `set -u` + "$CONDA_EXE" $_CE_M $_CE_CONDA "$@" + else + "$CONDA_EXE" "$@" + fi +) + +__conda_hashr() { + if [ -n "${ZSH_VERSION:+x}" ]; then + \rehash + elif [ -n "${POSH_VERSION:+x}" ]; then + : # pass + else + \hash -r + fi +} + +__conda_activate() { + if [ -n "${CONDA_PS1_BACKUP:+x}" ]; then + # Handle transition from shell activated with conda <= 4.3 to a subsequent activation + # after conda updated to >= 4.4. See issue #6173. + PS1="$CONDA_PS1_BACKUP" + \unset CONDA_PS1_BACKUP + fi + \local ask_conda + ask_conda="$(PS1="${PS1:-}" __conda_exe shell.posix "$@")" || \return + \eval "$ask_conda" + __conda_hashr +} + +__conda_reactivate() { + # FUTURE: conda 25.9, remove this function + echo "'__conda_reactivate' is deprecated and will be removed in 25.9. Use '__conda_activate reactivate' instead." 1>&2 + __conda_activate reactivate +} + +conda() { + \local cmd="${1-__missing__}" + case "$cmd" in + activate|deactivate) + __conda_activate "$@" + ;; + install|update|upgrade|remove|uninstall) + __conda_exe "$@" || \return + __conda_activate reactivate + ;; + *) + __conda_exe "$@" + ;; + esac +} + +if [ -z "${CONDA_SHLVL+x}" ]; then + \export CONDA_SHLVL=0 + # In dev-mode CONDA_EXE is python.exe and on Windows + # it is in a different relative location to condabin. + if [ -n "${_CE_CONDA:+x}" ] && [ -n "${WINDIR+x}" ]; then + PATH="$(\dirname "$CONDA_EXE")/condabin${PATH:+":${PATH}"}" + else + PATH="$(\dirname "$(\dirname "$CONDA_EXE")")/condabin${PATH:+":${PATH}"}" + fi + \export PATH + + # We're not allowing PS1 to be unbound. It must at least be set. + # However, we're not exporting it, which can cause problems when starting a second shell + # via a first shell (i.e. starting zsh from bash). + if [ -z "${PS1+x}" ]; then + PS1= + fi +fi diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..798f20725ffef867334ee189edbea212ee300880 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f2f0bdba2737d3f47b25faa11352c0393271b4f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/hooks.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/hooks.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc2e8f89153f46b3d791394e9078bffa042725c3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/conda_anaconda_telemetry/__pycache__/hooks.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..49ee1f8e9fa958cef4ea904f94e1f0d470a9068a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a687a70318e31c4318205b3b6a05fe08595f719 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/array.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/array.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a2831931660cdcdfe84ca3ff10a3bbfee86e5e5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/array.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/chunk.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/chunk.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd2a3f46614828d89cd27172f0dc3d9c609bd337 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/chunk.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/convert.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/convert.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36d70b1b1ae30c4bc78c4264ceff245df43fd889 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/convert.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/dechunk.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/dechunk.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1640b747aa861401e96a84eb6c06d0df5d0c3f46 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/dechunk.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/enum_util.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/enum_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e68e6a3b6931649dc1eeddf8511c8360da2fd28 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/enum_util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/typecheck.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/typecheck.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a2c0a1506d97d68b4a0985e31143db368908ab1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/typecheck.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/types.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fa3ce098a195e03a4be059234e2d0199395749f1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/__pycache__/types.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__init__.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe33fcef1e18d2a4b92287e434cf6b1257e4274f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__init__.py @@ -0,0 +1,5 @@ +from __future__ import annotations + +from contourpy.util._build_config import build_config + +__all__ = ["build_config"] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..58aae32763b5aa1eb80aff4b954a3f5bd38cdf1f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/_build_config.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/_build_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4dbcd0743ea1af5a0291dad9c0cc7720c2c1b2bd Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/_build_config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_renderer.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_renderer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..330c8f353ecfb1c47fb66fb8d49254245b641eb9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_renderer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_util.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e96fbfd7b385e657dc70b110047d5d5a644d20f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/bokeh_util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/data.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/data.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1d94dd229f047c7d186fa245a0bc153f2a29eda Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/data.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_renderer.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_renderer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2e765d93910c78fa374d3f20bde92b7cb37c002 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_renderer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_util.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70c371bd2402751fc1ccdc3b43f436436e911151 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/mpl_util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/renderer.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/renderer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2ffcf189c2eabd745e9831109dc44e6d9ed4be3f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/__pycache__/renderer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/_build_config.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/_build_config.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5822d90efff74b4a732ed56506961e7fb27ff6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/_build_config.py @@ -0,0 +1,60 @@ +# _build_config.py.in is converted into _build_config.py during the meson build process. + +from __future__ import annotations + + +def build_config() -> dict[str, str]: + """ + Return a dictionary containing build configuration settings. + + All dictionary keys and values are strings, for example ``False`` is + returned as ``"False"``. + + .. versionadded:: 1.1.0 + """ + return dict( + # Python settings + python_version="3.13", + python_install_dir=r"/usr/local/lib/python3.13/site-packages/", + python_path=r"/tmp/build-env-3d4ff6rd/bin/python", + + # Package versions + contourpy_version="1.3.3", + meson_version="1.8.2", + mesonpy_version="0.18.0", + pybind11_version="3.0.0", + + # Misc meson settings + meson_backend="ninja", + build_dir=r"/project/.mesonpy-cga074fa/lib/contourpy/util", + source_dir=r"/project/lib/contourpy/util", + cross_build="False", + + # Build options + build_options=r"-Dbuildtype=release -Db_ndebug=if-release -Db_vscrt=md -Dvsenv=True --native-file=/project/.mesonpy-cga074fa/meson-python-native-file.ini", + buildtype="release", + cpp_std="c++17", + debug="False", + optimization="3", + vsenv="True", + b_ndebug="if-release", + b_vscrt="from_buildtype", + + # C++ compiler + compiler_name="gcc", + compiler_version="14.2.1", + linker_id="ld.bfd", + compile_command="c++", + + # Host machine + host_cpu="x86_64", + host_cpu_family="x86_64", + host_cpu_endian="little", + host_cpu_system="linux", + + # Build machine, same as host machine if not a cross_build + build_cpu="x86_64", + build_cpu_family="x86_64", + build_cpu_endian="little", + build_cpu_system="linux", + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_renderer.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..f80e93e9e4e2deb8372c8ac29e04a9e86096f4cb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_renderer.py @@ -0,0 +1,339 @@ +from __future__ import annotations + +import io +from typing import TYPE_CHECKING, Any + +from bokeh.io import export_png, export_svg, show +from bokeh.io.export import get_screenshot_as_png +from bokeh.layouts import gridplot +from bokeh.models.annotations.labels import Label +from bokeh.palettes import Category10 +from bokeh.plotting import figure +import numpy as np + +from contourpy.enum_util import as_fill_type, as_line_type +from contourpy.util.bokeh_util import filled_to_bokeh, lines_to_bokeh +from contourpy.util.renderer import Renderer + +if TYPE_CHECKING: + from bokeh.core.enums import OutputBackendType + from bokeh.models import GridPlot + from bokeh.palettes import Palette + from numpy.typing import ArrayLike + from selenium.webdriver.remote.webdriver import WebDriver + + from contourpy import FillType, LineType + from contourpy._contourpy import FillReturn, LineReturn + + +class BokehRenderer(Renderer): + """Utility renderer using Bokeh to render a grid of plots over the same (x, y) range. + + Args: + nrows (int, optional): Number of rows of plots, default ``1``. + ncols (int, optional): Number of columns of plots, default ``1``. + figsize (tuple(float, float), optional): Figure size in inches (assuming 100 dpi), default + ``(9, 9)``. + show_frame (bool, optional): Whether to show frame and axes ticks, default ``True``. + want_svg (bool, optional): Whether output is required in SVG format or not, default + ``False``. + + Warning: + :class:`~.BokehRenderer`, unlike :class:`~.MplRenderer`, needs to be told in advance if + output to SVG format will be required later, otherwise it will assume PNG output. + """ + _figures: list[figure] + _layout: GridPlot + _palette: Palette + _want_svg: bool + + def __init__( + self, + nrows: int = 1, + ncols: int = 1, + figsize: tuple[float, float] = (9, 9), + show_frame: bool = True, + want_svg: bool = False, + ) -> None: + self._want_svg = want_svg + self._palette = Category10[10] + + total_size = 100*np.asarray(figsize, dtype=int) # Assuming 100 dpi. + + nfigures = nrows*ncols + self._figures = [] + backend: OutputBackendType = "svg" if self._want_svg else "canvas" + for _ in range(nfigures): + fig = figure(output_backend=backend) + fig.xgrid.visible = False + fig.ygrid.visible = False + self._figures.append(fig) + if not show_frame: + fig.outline_line_color = None + fig.axis.visible = False + + self._layout = gridplot( + self._figures, ncols=ncols, toolbar_location=None, # type: ignore[arg-type] + width=total_size[0] // ncols, height=total_size[1] // nrows) + + def _convert_color(self, color: str) -> str: + if isinstance(color, str) and color[0] == "C": + index = int(color[1:]) + color = self._palette[index] + return color + + def _get_figure(self, ax: figure | int) -> figure: + if isinstance(ax, int): + ax = self._figures[ax] + return ax + + def filled( + self, + filled: FillReturn, + fill_type: FillType | str, + ax: figure | int = 0, + color: str = "C0", + alpha: float = 0.7, + ) -> None: + """Plot filled contours on a single plot. + + Args: + filled (sequence of arrays): Filled contour data as returned by + :meth:`~.ContourGenerator.filled`. + fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` data as returned + by :attr:`~.ContourGenerator.fill_type`, or a string equivalent. + ax (int or Bokeh Figure, optional): Which plot to use, default ``0``. + color (str, optional): Color to plot with. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``Category10`` palette. Default ``"C0"``. + alpha (float, optional): Opacity to plot with, default ``0.7``. + """ + fill_type = as_fill_type(fill_type) + fig = self._get_figure(ax) + color = self._convert_color(color) + xs, ys = filled_to_bokeh(filled, fill_type) + if len(xs) > 0: + fig.multi_polygons(xs=[xs], ys=[ys], color=color, fill_alpha=alpha, line_width=0) # type: ignore[arg-type] + + def grid( + self, + x: ArrayLike, + y: ArrayLike, + ax: figure | int = 0, + color: str = "black", + alpha: float = 0.1, + point_color: str | None = None, + quad_as_tri_alpha: float = 0, + ) -> None: + """Plot quad grid lines on a single plot. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + ax (int or Bokeh Figure, optional): Which plot to use, default ``0``. + color (str, optional): Color to plot grid lines, default ``"black"``. + alpha (float, optional): Opacity to plot lines with, default ``0.1``. + point_color (str, optional): Color to plot grid points or ``None`` if grid points + should not be plotted, default ``None``. + quad_as_tri_alpha (float, optional): Opacity to plot ``quad_as_tri`` grid, default + ``0``. + + Colors may be a string color or the letter ``"C"`` followed by an integer in the range + ``"C0"`` to ``"C9"`` to use a color from the ``Category10`` palette. + + Warning: + ``quad_as_tri_alpha > 0`` plots all quads as though they are unmasked. + """ + fig = self._get_figure(ax) + x, y = self._grid_as_2d(x, y) + xs = list(x) + list(x.T) + ys = list(y) + list(y.T) + kwargs = {"line_color": color, "alpha": alpha} + fig.multi_line(xs, ys, **kwargs) + if quad_as_tri_alpha > 0: + # Assumes no quad mask. + xmid = (0.25*(x[:-1, :-1] + x[1:, :-1] + x[:-1, 1:] + x[1:, 1:])).ravel() + ymid = (0.25*(y[:-1, :-1] + y[1:, :-1] + y[:-1, 1:] + y[1:, 1:])).ravel() + fig.multi_line( + list(np.stack((x[:-1, :-1].ravel(), xmid, x[1:, 1:].ravel()), axis=1)), + list(np.stack((y[:-1, :-1].ravel(), ymid, y[1:, 1:].ravel()), axis=1)), + **kwargs) + fig.multi_line( + list(np.stack((x[:-1, 1:].ravel(), xmid, x[1:, :-1].ravel()), axis=1)), + list(np.stack((y[:-1, 1:].ravel(), ymid, y[1:, :-1].ravel()), axis=1)), + **kwargs) + if point_color is not None: + fig.scatter( + x=x.ravel(), y=y.ravel(), fill_color=color, line_color=None, alpha=alpha, + marker="circle", size=8) + + def lines( + self, + lines: LineReturn, + line_type: LineType | str, + ax: figure | int = 0, + color: str = "C0", + alpha: float = 1.0, + linewidth: float = 1, + ) -> None: + """Plot contour lines on a single plot. + + Args: + lines (sequence of arrays): Contour line data as returned by + :meth:`~.ContourGenerator.lines`. + line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` data as returned + by :attr:`~.ContourGenerator.line_type`, or a string equivalent. + ax (int or Bokeh Figure, optional): Which plot to use, default ``0``. + color (str, optional): Color to plot lines. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``Category10`` palette. Default ``"C0"``. + alpha (float, optional): Opacity to plot lines with, default ``1.0``. + linewidth (float, optional): Width of lines, default ``1``. + + Note: + Assumes all lines are open line strips not closed line loops. + """ + line_type = as_line_type(line_type) + fig = self._get_figure(ax) + color = self._convert_color(color) + xs, ys = lines_to_bokeh(lines, line_type) + if xs is not None: + assert ys is not None + fig.line(xs, ys, line_color=color, line_alpha=alpha, line_width=linewidth) + + def mask( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike | np.ma.MaskedArray[Any, Any], + ax: figure | int = 0, + color: str = "black", + ) -> None: + """Plot masked out grid points as circles on a single plot. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + z (masked array of shape (ny, nx): z-values. + ax (int or Bokeh Figure, optional): Which plot to use, default ``0``. + color (str, optional): Circle color, default ``"black"``. + """ + mask = np.ma.getmask(z) + if mask is np.ma.nomask: + return + fig = self._get_figure(ax) + color = self._convert_color(color) + x, y = self._grid_as_2d(x, y) + fig.scatter(x[mask], y[mask], fill_color=color, marker="circle", size=10) + + def save( + self, + filename: str, + transparent: bool = False, + *, + webdriver: WebDriver | None = None, + ) -> None: + """Save plots to SVG or PNG file. + + Args: + filename (str): Filename to save to. + transparent (bool, optional): Whether background should be transparent, default + ``False``. + webdriver (WebDriver, optional): Selenium WebDriver instance to use to create the image. + + .. versionadded:: 1.1.1 + + Warning: + To output to SVG file, ``want_svg=True`` must have been passed to the constructor. + """ + if transparent: + for fig in self._figures: + fig.background_fill_color = None + fig.border_fill_color = None + + if self._want_svg: + export_svg(self._layout, filename=filename, webdriver=webdriver) + else: + export_png(self._layout, filename=filename, webdriver=webdriver) + + def save_to_buffer(self, *, webdriver: WebDriver | None = None) -> io.BytesIO: + """Save plots to an ``io.BytesIO`` buffer. + + Args: + webdriver (WebDriver, optional): Selenium WebDriver instance to use to create the image. + + .. versionadded:: 1.1.1 + + Return: + BytesIO: PNG image buffer. + """ + image = get_screenshot_as_png(self._layout, driver=webdriver) + buffer = io.BytesIO() + image.save(buffer, "png") + return buffer + + def show(self) -> None: + """Show plots in web browser, in usual Bokeh manner. + """ + show(self._layout) + + def title(self, title: str, ax: figure | int = 0, color: str | None = None) -> None: + """Set the title of a single plot. + + Args: + title (str): Title text. + ax (int or Bokeh Figure, optional): Which plot to set the title of, default ``0``. + color (str, optional): Color to set title. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``Category10`` palette. Default ``None`` which is ``black``. + """ + fig = self._get_figure(ax) + fig.title = title + fig.title.align = "center" # type: ignore[attr-defined] + if color is not None: + fig.title.text_color = self._convert_color(color) # type: ignore[attr-defined] + + def z_values( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + ax: figure | int = 0, + color: str = "green", + fmt: str = ".1f", + quad_as_tri: bool = False, + ) -> None: + """Show ``z`` values on a single plot. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + z (array-like of shape (ny, nx): z-values. + ax (int or Bokeh Figure, optional): Which plot to use, default ``0``. + color (str, optional): Color of added text. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``Category10`` palette. Default ``"green"``. + fmt (str, optional): Format to display z-values, default ``".1f"``. + quad_as_tri (bool, optional): Whether to show z-values at the ``quad_as_tri`` centres + of quads. + + Warning: + ``quad_as_tri=True`` shows z-values for all quads, even if masked. + """ + fig = self._get_figure(ax) + color = self._convert_color(color) + x, y = self._grid_as_2d(x, y) + z = np.asarray(z) + ny, nx = z.shape + kwargs = {"text_color": color, "text_align": "center", "text_baseline": "middle"} + for j in range(ny): + for i in range(nx): + label = Label(x=x[j, i], y=y[j, i], text=f"{z[j, i]:{fmt}}", **kwargs) # type: ignore[arg-type] + fig.add_layout(label) + if quad_as_tri: + for j in range(ny-1): + for i in range(nx-1): + xx = np.mean(x[j:j+2, i:i+2]) + yy = np.mean(y[j:j+2, i:i+2]) + zz = np.mean(z[j:j+2, i:i+2]) + fig.add_layout(Label(x=xx, y=yy, text=f"{zz:{fmt}}", **kwargs)) # type: ignore[arg-type] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_util.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_util.py new file mode 100644 index 0000000000000000000000000000000000000000..e75eb844536b26dfe90de08bb65328e5d2e5ba1c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/bokeh_util.py @@ -0,0 +1,74 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, cast + +from contourpy import FillType, LineType +from contourpy.array import offsets_from_codes +from contourpy.convert import convert_lines +from contourpy.dechunk import dechunk_lines + +if TYPE_CHECKING: + from contourpy._contourpy import ( + CoordinateArray, + FillReturn, + LineReturn, + LineReturn_ChunkCombinedNan, + ) + + +def filled_to_bokeh( + filled: FillReturn, + fill_type: FillType, +) -> tuple[list[list[CoordinateArray]], list[list[CoordinateArray]]]: + xs: list[list[CoordinateArray]] = [] + ys: list[list[CoordinateArray]] = [] + if fill_type in (FillType.OuterOffset, FillType.ChunkCombinedOffset, + FillType.OuterCode, FillType.ChunkCombinedCode): + have_codes = fill_type in (FillType.OuterCode, FillType.ChunkCombinedCode) + + for points, offsets in zip(*filled): + if points is None: + continue + if have_codes: + offsets = offsets_from_codes(offsets) + xs.append([]) # New outer with zero or more holes. + ys.append([]) + for i in range(len(offsets)-1): + xys = points[offsets[i]:offsets[i+1]] + xs[-1].append(xys[:, 0]) + ys[-1].append(xys[:, 1]) + elif fill_type in (FillType.ChunkCombinedCodeOffset, FillType.ChunkCombinedOffsetOffset): + for points, codes_or_offsets, outer_offsets in zip(*filled): + if points is None: + continue + for j in range(len(outer_offsets)-1): + if fill_type == FillType.ChunkCombinedCodeOffset: + codes = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]] + offsets = offsets_from_codes(codes) + outer_offsets[j] + else: + offsets = codes_or_offsets[outer_offsets[j]:outer_offsets[j+1]+1] + xs.append([]) # New outer with zero or more holes. + ys.append([]) + for k in range(len(offsets)-1): + xys = points[offsets[k]:offsets[k+1]] + xs[-1].append(xys[:, 0]) + ys[-1].append(xys[:, 1]) + else: + raise RuntimeError(f"Conversion of FillType {fill_type} to Bokeh is not implemented") + + return xs, ys + + +def lines_to_bokeh( + lines: LineReturn, + line_type: LineType, +) -> tuple[CoordinateArray | None, CoordinateArray | None]: + lines = convert_lines(lines, line_type, LineType.ChunkCombinedNan) + lines = dechunk_lines(lines, LineType.ChunkCombinedNan) + if TYPE_CHECKING: + lines = cast(LineReturn_ChunkCombinedNan, lines) + points = lines[0][0] + if points is None: + return None, None + else: + return points[:, 0], points[:, 1] diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/data.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/data.py new file mode 100644 index 0000000000000000000000000000000000000000..5fa75486958c8277430f149daf872e859de8e000 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/data.py @@ -0,0 +1,78 @@ +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + from contourpy._contourpy import CoordinateArray + + +def simple( + shape: tuple[int, int], want_mask: bool = False, +) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]: + """Return simple test data consisting of the sum of two gaussians. + + Args: + shape (tuple(int, int)): 2D shape of data to return. + want_mask (bool, optional): Whether test data should be masked or not, default ``False``. + + Return: + Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if + ``want_mask=True``. + """ + ny, nx = shape + x = np.arange(nx, dtype=np.float64) + y = np.arange(ny, dtype=np.float64) + x, y = np.meshgrid(x, y) + + xscale = nx - 1.0 + yscale = ny - 1.0 + + # z is sum of 2D gaussians. + amp = np.asarray([1.0, -1.0, 0.8, -0.9, 0.7]) + mid = np.asarray([[0.4, 0.2], [0.3, 0.8], [0.9, 0.75], [0.7, 0.3], [0.05, 0.7]]) + width = np.asarray([0.4, 0.2, 0.2, 0.2, 0.1]) + + z = np.zeros_like(x) + for i in range(len(amp)): + z += amp[i]*np.exp(-((x/xscale - mid[i, 0])**2 + (y/yscale - mid[i, 1])**2) / width[i]**2) + + if want_mask: + mask = np.logical_or( + ((x/xscale - 1.0)**2 / 0.2 + (y/yscale - 0.0)**2 / 0.1) < 1.0, + ((x/xscale - 0.2)**2 / 0.02 + (y/yscale - 0.45)**2 / 0.08) < 1.0, + ) + z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call] + + return x, y, z + + +def random( + shape: tuple[int, int], seed: int = 2187, mask_fraction: float = 0.0, +) -> tuple[CoordinateArray, CoordinateArray, CoordinateArray | np.ma.MaskedArray[Any, Any]]: + """Return random test data in the range 0 to 1. + + Args: + shape (tuple(int, int)): 2D shape of data to return. + seed (int, optional): Seed for random number generator, default 2187. + mask_fraction (float, optional): Fraction of elements to mask, default 0. + + Return: + Tuple of 3 arrays: ``x``, ``y``, ``z`` test data, ``z`` will be masked if + ``mask_fraction`` is greater than zero. + """ + ny, nx = shape + x = np.arange(nx, dtype=np.float64) + y = np.arange(ny, dtype=np.float64) + x, y = np.meshgrid(x, y) + + rng = np.random.default_rng(seed) + z = rng.uniform(size=shape) + + if mask_fraction > 0.0: + mask_fraction = min(mask_fraction, 0.99) + mask = rng.uniform(size=shape) < mask_fraction + z = np.ma.array(z, mask=mask) # type: ignore[no-untyped-call] + + return x, y, z diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_renderer.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..7c39b31ae882a05f7239b0483775576595121115 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_renderer.py @@ -0,0 +1,535 @@ +from __future__ import annotations + +import io +from itertools import pairwise +from typing import TYPE_CHECKING, Any, cast + +import matplotlib.collections as mcollections +import matplotlib.pyplot as plt +import numpy as np + +from contourpy import FillType, LineType +from contourpy.convert import convert_filled, convert_lines +from contourpy.enum_util import as_fill_type, as_line_type +from contourpy.util.mpl_util import filled_to_mpl_paths, lines_to_mpl_paths +from contourpy.util.renderer import Renderer + +if TYPE_CHECKING: + from collections.abc import Sequence + + from matplotlib.axes import Axes + from matplotlib.figure import Figure + from numpy.typing import ArrayLike + + import contourpy._contourpy as cpy + + +class MplRenderer(Renderer): + """Utility renderer using Matplotlib to render a grid of plots over the same (x, y) range. + + Args: + nrows (int, optional): Number of rows of plots, default ``1``. + ncols (int, optional): Number of columns of plots, default ``1``. + figsize (tuple(float, float), optional): Figure size in inches, default ``(9, 9)``. + show_frame (bool, optional): Whether to show frame and axes ticks, default ``True``. + backend (str, optional): Matplotlib backend to use or ``None`` for default backend. + Default ``None``. + gridspec_kw (dict, optional): Gridspec keyword arguments to pass to ``plt.subplots``, + default None. + """ + _axes: Sequence[Axes] + _fig: Figure + _want_tight: bool + + def __init__( + self, + nrows: int = 1, + ncols: int = 1, + figsize: tuple[float, float] = (9, 9), + show_frame: bool = True, + backend: str | None = None, + gridspec_kw: dict[str, Any] | None = None, + ) -> None: + if backend is not None: + import matplotlib as mpl + mpl.use(backend) + + kwargs: dict[str, Any] = {"figsize": figsize, "squeeze": False, + "sharex": True, "sharey": True} + if gridspec_kw is not None: + kwargs["gridspec_kw"] = gridspec_kw + else: + kwargs["subplot_kw"] = {"aspect": "equal"} + + self._fig, axes = plt.subplots(nrows, ncols, **kwargs) + self._axes = axes.flatten() + if not show_frame: + for ax in self._axes: + ax.axis("off") + + self._want_tight = True + + def __del__(self) -> None: + if hasattr(self, "_fig"): + plt.close(self._fig) + + def _autoscale(self) -> None: + # Using axes._need_autoscale attribute if need to autoscale before rendering after adding + # lines/filled. Only want to autoscale once per axes regardless of how many lines/filled + # added. + for ax in self._axes: + if getattr(ax, "_need_autoscale", False): + ax.autoscale_view(tight=True) + ax._need_autoscale = False # type: ignore[attr-defined] + if self._want_tight and len(self._axes) > 1: + self._fig.tight_layout() + + def _get_ax(self, ax: Axes | int) -> Axes: + if isinstance(ax, int): + ax = self._axes[ax] + return ax + + def filled( + self, + filled: cpy.FillReturn, + fill_type: FillType | str, + ax: Axes | int = 0, + color: str = "C0", + alpha: float = 0.7, + ) -> None: + """Plot filled contours on a single Axes. + + Args: + filled (sequence of arrays): Filled contour data as returned by + :meth:`~.ContourGenerator.filled`. + fill_type (FillType or str): Type of :meth:`~.ContourGenerator.filled` data as returned + by :attr:`~.ContourGenerator.fill_type`, or string equivalent + ax (int or Maplotlib Axes, optional): Which axes to plot on, default ``0``. + color (str, optional): Color to plot with. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``tab10`` colormap. Default ``"C0"``. + alpha (float, optional): Opacity to plot with, default ``0.7``. + """ + fill_type = as_fill_type(fill_type) + ax = self._get_ax(ax) + paths = filled_to_mpl_paths(filled, fill_type) + collection = mcollections.PathCollection( + paths, facecolors=color, edgecolors="none", lw=0, alpha=alpha) + ax.add_collection(collection) + ax._need_autoscale = True # type: ignore[attr-defined] + + def grid( + self, + x: ArrayLike, + y: ArrayLike, + ax: Axes | int = 0, + color: str = "black", + alpha: float = 0.1, + point_color: str | None = None, + quad_as_tri_alpha: float = 0, + ) -> None: + """Plot quad grid lines on a single Axes. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``. + color (str, optional): Color to plot grid lines, default ``"black"``. + alpha (float, optional): Opacity to plot lines with, default ``0.1``. + point_color (str, optional): Color to plot grid points or ``None`` if grid points + should not be plotted, default ``None``. + quad_as_tri_alpha (float, optional): Opacity to plot ``quad_as_tri`` grid, default 0. + + Colors may be a string color or the letter ``"C"`` followed by an integer in the range + ``"C0"`` to ``"C9"`` to use a color from the ``tab10`` colormap. + + Warning: + ``quad_as_tri_alpha > 0`` plots all quads as though they are unmasked. + """ + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + kwargs: dict[str, Any] = {"color": color, "alpha": alpha} + ax.plot(x, y, x.T, y.T, **kwargs) + if quad_as_tri_alpha > 0: + # Assumes no quad mask. + xmid = 0.25*(x[:-1, :-1] + x[1:, :-1] + x[:-1, 1:] + x[1:, 1:]) + ymid = 0.25*(y[:-1, :-1] + y[1:, :-1] + y[:-1, 1:] + y[1:, 1:]) + kwargs["alpha"] = quad_as_tri_alpha + ax.plot( + np.stack((x[:-1, :-1], xmid, x[1:, 1:])).reshape((3, -1)), + np.stack((y[:-1, :-1], ymid, y[1:, 1:])).reshape((3, -1)), + np.stack((x[1:, :-1], xmid, x[:-1, 1:])).reshape((3, -1)), + np.stack((y[1:, :-1], ymid, y[:-1, 1:])).reshape((3, -1)), + **kwargs) + if point_color is not None: + ax.plot(x, y, color=point_color, alpha=alpha, marker="o", lw=0) + ax._need_autoscale = True # type: ignore[attr-defined] + + def lines( + self, + lines: cpy.LineReturn, + line_type: LineType | str, + ax: Axes | int = 0, + color: str = "C0", + alpha: float = 1.0, + linewidth: float = 1, + ) -> None: + """Plot contour lines on a single Axes. + + Args: + lines (sequence of arrays): Contour line data as returned by + :meth:`~.ContourGenerator.lines`. + line_type (LineType or str): Type of :meth:`~.ContourGenerator.lines` data as returned + by :attr:`~.ContourGenerator.line_type`, or string equivalent. + ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``. + color (str, optional): Color to plot lines. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``tab10`` colormap. Default ``"C0"``. + alpha (float, optional): Opacity to plot lines with, default ``1.0``. + linewidth (float, optional): Width of lines, default ``1``. + """ + line_type = as_line_type(line_type) + ax = self._get_ax(ax) + paths = lines_to_mpl_paths(lines, line_type) + collection = mcollections.PathCollection( + paths, facecolors="none", edgecolors=color, lw=linewidth, alpha=alpha) + ax.add_collection(collection) + ax._need_autoscale = True # type: ignore[attr-defined] + + def mask( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike | np.ma.MaskedArray[Any, Any], + ax: Axes | int = 0, + color: str = "black", + ) -> None: + """Plot masked out grid points as circles on a single Axes. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + z (masked array of shape (ny, nx): z-values. + ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``. + color (str, optional): Circle color, default ``"black"``. + """ + mask = np.ma.getmask(z) + if mask is np.ma.nomask: + return + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + ax.plot(x[mask], y[mask], "o", c=color) + + def save(self, filename: str, transparent: bool = False) -> None: + """Save plots to SVG or PNG file. + + Args: + filename (str): Filename to save to. + transparent (bool, optional): Whether background should be transparent, default + ``False``. + """ + self._autoscale() + self._fig.savefig(filename, transparent=transparent) + + def save_to_buffer(self) -> io.BytesIO: + """Save plots to an ``io.BytesIO`` buffer. + + Return: + BytesIO: PNG image buffer. + """ + self._autoscale() + buf = io.BytesIO() + self._fig.savefig(buf, format="png") + buf.seek(0) + return buf + + def show(self) -> None: + """Show plots in an interactive window, in the usual Matplotlib manner. + """ + self._autoscale() + plt.show() + + def title(self, title: str, ax: Axes | int = 0, color: str | None = None) -> None: + """Set the title of a single Axes. + + Args: + title (str): Title text. + ax (int or Matplotlib Axes, optional): Which Axes to set the title of, default ``0``. + color (str, optional): Color to set title. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``tab10`` colormap. Default is ``None`` which uses Matplotlib's default title color + that depends on the stylesheet in use. + """ + if color: + self._get_ax(ax).set_title(title, color=color) + else: + self._get_ax(ax).set_title(title) + + def z_values( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + ax: Axes | int = 0, + color: str = "green", + fmt: str = ".1f", + quad_as_tri: bool = False, + ) -> None: + """Show ``z`` values on a single Axes. + + Args: + x (array-like of shape (ny, nx) or (nx,)): The x-coordinates of the grid points. + y (array-like of shape (ny, nx) or (ny,)): The y-coordinates of the grid points. + z (array-like of shape (ny, nx): z-values. + ax (int or Matplotlib Axes, optional): Which Axes to plot on, default ``0``. + color (str, optional): Color of added text. May be a string color or the letter ``"C"`` + followed by an integer in the range ``"C0"`` to ``"C9"`` to use a color from the + ``tab10`` colormap. Default ``"green"``. + fmt (str, optional): Format to display z-values, default ``".1f"``. + quad_as_tri (bool, optional): Whether to show z-values at the ``quad_as_tri`` centers + of quads. + + Warning: + ``quad_as_tri=True`` shows z-values for all quads, even if masked. + """ + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + z = np.asarray(z) + ny, nx = z.shape + for j in range(ny): + for i in range(nx): + ax.text(x[j, i], y[j, i], f"{z[j, i]:{fmt}}", ha="center", va="center", + color=color, clip_on=True) + if quad_as_tri: + for j in range(ny-1): + for i in range(nx-1): + xx = np.mean(x[j:j+2, i:i+2], dtype=np.float64) + yy = np.mean(y[j:j+2, i:i+2], dtype=np.float64) + zz = np.mean(z[j:j+2, i:i+2]) + ax.text(xx, yy, f"{zz:{fmt}}", ha="center", va="center", color=color, + clip_on=True) + + +class MplTestRenderer(MplRenderer): + """Test renderer implemented using Matplotlib. + + No whitespace around plots and no spines/ticks displayed. + Uses Agg backend, so can only save to file/buffer, cannot call ``show()``. + """ + def __init__( + self, + nrows: int = 1, + ncols: int = 1, + figsize: tuple[float, float] = (9, 9), + ) -> None: + gridspec = { + "left": 0.01, + "right": 0.99, + "top": 0.99, + "bottom": 0.01, + "wspace": 0.01, + "hspace": 0.01, + } + super().__init__( + nrows, ncols, figsize, show_frame=True, backend="Agg", gridspec_kw=gridspec, + ) + + for ax in self._axes: + ax.set_xmargin(0.0) + ax.set_ymargin(0.0) + ax.set_xticks([]) + ax.set_yticks([]) + + self._want_tight = False + + +class MplDebugRenderer(MplRenderer): + """Debug renderer implemented using Matplotlib. + + Extends ``MplRenderer`` to add extra information to help in debugging such as markers, arrows, + text, etc. + """ + def __init__( + self, + nrows: int = 1, + ncols: int = 1, + figsize: tuple[float, float] = (9, 9), + show_frame: bool = True, + ) -> None: + super().__init__(nrows, ncols, figsize, show_frame) + + def _arrow( + self, + ax: Axes, + line_start: cpy.CoordinateArray, + line_end: cpy.CoordinateArray, + color: str, + alpha: float, + arrow_size: float, + ) -> None: + mid = 0.5*(line_start + line_end) + along = line_end - line_start + along /= np.sqrt(np.dot(along, along)) # Unit vector. + right = np.asarray((along[1], -along[0])) + arrow = np.stack(( + mid - (along*0.5 - right)*arrow_size, + mid + along*0.5*arrow_size, + mid - (along*0.5 + right)*arrow_size, + )) + ax.plot(arrow[:, 0], arrow[:, 1], "-", c=color, alpha=alpha) + + def filled( + self, + filled: cpy.FillReturn, + fill_type: FillType | str, + ax: Axes | int = 0, + color: str = "C1", + alpha: float = 0.7, + line_color: str = "C0", + line_alpha: float = 0.7, + point_color: str = "C0", + start_point_color: str = "red", + arrow_size: float = 0.1, + ) -> None: + fill_type = as_fill_type(fill_type) + super().filled(filled, fill_type, ax, color, alpha) + + if line_color is None and point_color is None: + return + + ax = self._get_ax(ax) + filled = convert_filled(filled, fill_type, FillType.ChunkCombinedOffset) + + # Lines. + if line_color is not None: + for points, offsets in zip(*filled): + if points is None: + continue + for start, end in pairwise(offsets): + xys = points[start:end] + ax.plot(xys[:, 0], xys[:, 1], c=line_color, alpha=line_alpha) + + if arrow_size > 0.0: + n = len(xys) + for i in range(n-1): + self._arrow(ax, xys[i], xys[i+1], line_color, line_alpha, arrow_size) + + # Points. + if point_color is not None: + for points, offsets in zip(*filled): + if points is None: + continue + mask = np.ones(offsets[-1], dtype=bool) + mask[offsets[1:]-1] = False # Exclude end points. + if start_point_color is not None: + start_indices = offsets[:-1] + mask[start_indices] = False # Exclude start points. + ax.plot( + points[:, 0][mask], points[:, 1][mask], "o", c=point_color, alpha=line_alpha) + + if start_point_color is not None: + ax.plot(points[:, 0][start_indices], points[:, 1][start_indices], "o", + c=start_point_color, alpha=line_alpha) + + def lines( + self, + lines: cpy.LineReturn, + line_type: LineType | str, + ax: Axes | int = 0, + color: str = "C0", + alpha: float = 1.0, + linewidth: float = 1, + point_color: str = "C0", + start_point_color: str = "red", + arrow_size: float = 0.1, + ) -> None: + line_type = as_line_type(line_type) + super().lines(lines, line_type, ax, color, alpha, linewidth) + + if arrow_size == 0.0 and point_color is None: + return + + ax = self._get_ax(ax) + separate_lines = convert_lines(lines, line_type, LineType.Separate) + if TYPE_CHECKING: + separate_lines = cast(cpy.LineReturn_Separate, separate_lines) + + if arrow_size > 0.0: + for line in separate_lines: + for i in range(len(line)-1): + self._arrow(ax, line[i], line[i+1], color, alpha, arrow_size) + + if point_color is not None: + for line in separate_lines: + start_index = 0 + end_index = len(line) + if start_point_color is not None: + ax.plot(line[0, 0], line[0, 1], "o", c=start_point_color, alpha=alpha) + start_index = 1 + if line[0][0] == line[-1][0] and line[0][1] == line[-1][1]: + end_index -= 1 + ax.plot(line[start_index:end_index, 0], line[start_index:end_index, 1], "o", + c=color, alpha=alpha) + + def point_numbers( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + ax: Axes | int = 0, + color: str = "red", + ) -> None: + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + z = np.asarray(z) + ny, nx = z.shape + for j in range(ny): + for i in range(nx): + quad = i + j*nx + ax.text(x[j, i], y[j, i], str(quad), ha="right", va="top", color=color, + clip_on=True) + + def quad_numbers( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + ax: Axes | int = 0, + color: str = "blue", + ) -> None: + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + z = np.asarray(z) + ny, nx = z.shape + for j in range(1, ny): + for i in range(1, nx): + quad = i + j*nx + xmid = x[j-1:j+1, i-1:i+1].mean() + ymid = y[j-1:j+1, i-1:i+1].mean() + ax.text(xmid, ymid, str(quad), ha="center", va="center", color=color, clip_on=True) + + def z_levels( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + lower_level: float, + upper_level: float | None = None, + ax: Axes | int = 0, + color: str = "green", + ) -> None: + ax = self._get_ax(ax) + x, y = self._grid_as_2d(x, y) + z = np.asarray(z) + ny, nx = z.shape + for j in range(ny): + for i in range(nx): + zz = z[j, i] + if upper_level is not None and zz > upper_level: + z_level = 2 + elif zz > lower_level: + z_level = 1 + else: + z_level = 0 + ax.text(x[j, i], y[j, i], str(z_level), ha="left", va="bottom", color=color, + clip_on=True) diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_util.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_util.py new file mode 100644 index 0000000000000000000000000000000000000000..d8587798c499a9ab898ee6cb54738be7e41bf7cf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/mpl_util.py @@ -0,0 +1,77 @@ +from __future__ import annotations + +from itertools import pairwise +from typing import TYPE_CHECKING, cast + +import matplotlib.path as mpath +import numpy as np + +from contourpy import FillType, LineType +from contourpy.array import codes_from_offsets + +if TYPE_CHECKING: + from contourpy._contourpy import FillReturn, LineReturn, LineReturn_Separate + + +def filled_to_mpl_paths(filled: FillReturn, fill_type: FillType) -> list[mpath.Path]: + if fill_type in (FillType.OuterCode, FillType.ChunkCombinedCode): + paths = [mpath.Path(points, codes) for points, codes in zip(*filled) if points is not None] + elif fill_type in (FillType.OuterOffset, FillType.ChunkCombinedOffset): + paths = [mpath.Path(points, codes_from_offsets(offsets)) + for points, offsets in zip(*filled) if points is not None] + elif fill_type == FillType.ChunkCombinedCodeOffset: + paths = [] + for points, codes, outer_offsets in zip(*filled): + if points is None: + continue + points = np.split(points, outer_offsets[1:-1]) + codes = np.split(codes, outer_offsets[1:-1]) + paths += [mpath.Path(p, c) for p, c in zip(points, codes)] + elif fill_type == FillType.ChunkCombinedOffsetOffset: + paths = [] + for points, offsets, outer_offsets in zip(*filled): + if points is None: + continue + for i in range(len(outer_offsets)-1): + offs = offsets[outer_offsets[i]:outer_offsets[i+1]+1] + pts = points[offs[0]:offs[-1]] + paths += [mpath.Path(pts, codes_from_offsets(offs - offs[0]))] + else: + raise RuntimeError(f"Conversion of FillType {fill_type} to MPL Paths is not implemented") + return paths + + +def lines_to_mpl_paths(lines: LineReturn, line_type: LineType) -> list[mpath.Path]: + if line_type == LineType.Separate: + if TYPE_CHECKING: + lines = cast(LineReturn_Separate, lines) + paths = [] + for line in lines: + # Drawing as Paths so that they can be closed correctly. + closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1] + paths.append(mpath.Path(line, closed=closed)) + elif line_type in (LineType.SeparateCode, LineType.ChunkCombinedCode): + paths = [mpath.Path(points, codes) for points, codes in zip(*lines) if points is not None] + elif line_type == LineType.ChunkCombinedOffset: + paths = [] + for points, offsets in zip(*lines): + if points is None: + continue + for i in range(len(offsets)-1): + line = points[offsets[i]:offsets[i+1]] + closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1] + paths.append(mpath.Path(line, closed=closed)) + elif line_type == LineType.ChunkCombinedNan: + paths = [] + for points in lines[0]: + if points is None: + continue + nan_offsets = np.nonzero(np.isnan(points[:, 0]))[0] + nan_offsets = np.concatenate([[-1], nan_offsets, [len(points)]]) + for s, e in pairwise(nan_offsets): + line = points[s+1:e] + closed = line[0, 0] == line[-1, 0] and line[0, 1] == line[-1, 1] + paths.append(mpath.Path(line, closed=closed)) + else: + raise RuntimeError(f"Conversion of LineType {line_type} to MPL Paths is not implemented") + return paths diff --git a/data/miniconda3/lib/python3.13/site-packages/contourpy/util/renderer.py b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/renderer.py new file mode 100644 index 0000000000000000000000000000000000000000..716569f776c4df9197a36f40e9f0a5e176292114 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/contourpy/util/renderer.py @@ -0,0 +1,166 @@ +from __future__ import annotations + +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING, Any + +import numpy as np + +if TYPE_CHECKING: + import io + + from numpy.typing import ArrayLike + + from contourpy._contourpy import CoordinateArray, FillReturn, FillType, LineReturn, LineType + + +class Renderer(ABC): + """Abstract base class for renderers.""" + + def _grid_as_2d(self, x: ArrayLike, y: ArrayLike) -> tuple[CoordinateArray, CoordinateArray]: + x = np.asarray(x) + y = np.asarray(y) + if x.ndim == 1: + x, y = np.meshgrid(x, y) + return x, y + + @abstractmethod + def filled( + self, + filled: FillReturn, + fill_type: FillType | str, + ax: Any = 0, + color: str = "C0", + alpha: float = 0.7, + ) -> None: + pass + + @abstractmethod + def grid( + self, + x: ArrayLike, + y: ArrayLike, + ax: Any = 0, + color: str = "black", + alpha: float = 0.1, + point_color: str | None = None, + quad_as_tri_alpha: float = 0, + ) -> None: + pass + + @abstractmethod + def lines( + self, + lines: LineReturn, + line_type: LineType | str, + ax: Any = 0, + color: str = "C0", + alpha: float = 1.0, + linewidth: float = 1, + ) -> None: + pass + + @abstractmethod + def mask( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike | np.ma.MaskedArray[Any, Any], + ax: Any = 0, + color: str = "black", + ) -> None: + pass + + def multi_filled( + self, + multi_filled: list[FillReturn], + fill_type: FillType | str, + ax: Any = 0, + color: str | None = None, + **kwargs: Any, + ) -> None: + """Plot multiple sets of filled contours on a single axes. + + Args: + multi_filled (list of filled contour arrays): Multiple filled contour sets as returned + by :meth:`.ContourGenerator.multi_filled`. + fill_type (FillType or str): Type of filled data as returned by + :attr:`~.ContourGenerator.fill_type`, or string equivalent. + ax (int or Renderer-specific axes or figure object, optional): Which axes to plot on, + default ``0``. + color (str or None, optional): If a string color then this same color is used for all + filled contours. If ``None``, the default, then the filled contour sets use colors + from the ``tab10`` colormap in order, wrapping around to the beginning if more than + 10 sets of filled contours are rendered. + kwargs: All other keyword argument are passed on to + :meth:`.Renderer.filled` unchanged. + + .. versionadded:: 1.3.0 + """ + if color is not None: + kwargs["color"] = color + for i, filled in enumerate(multi_filled): + if color is None: + kwargs["color"] = f"C{i % 10}" + self.filled(filled, fill_type, ax, **kwargs) + + def multi_lines( + self, + multi_lines: list[LineReturn], + line_type: LineType | str, + ax: Any = 0, + color: str | None = None, + **kwargs: Any, + ) -> None: + """Plot multiple sets of contour lines on a single axes. + + Args: + multi_lines (list of contour line arrays): Multiple contour line sets as returned by + :meth:`.ContourGenerator.multi_lines`. + line_type (LineType or str): Type of line data as returned by + :attr:`~.ContourGenerator.line_type`, or string equivalent. + ax (int or Renderer-specific axes or figure object, optional): Which axes to plot on, + default ``0``. + color (str or None, optional): If a string color then this same color is used for all + lines. If ``None``, the default, then the line sets use colors from the ``tab10`` + colormap in order, wrapping around to the beginning if more than 10 sets of lines + are rendered. + kwargs: All other keyword argument are passed on to + :meth:`Renderer.lines` unchanged. + + .. versionadded:: 1.3.0 + """ + if color is not None: + kwargs["color"] = color + for i, lines in enumerate(multi_lines): + if color is None: + kwargs["color"] = f"C{i % 10}" + self.lines(lines, line_type, ax, **kwargs) + + @abstractmethod + def save(self, filename: str, transparent: bool = False) -> None: + pass + + @abstractmethod + def save_to_buffer(self) -> io.BytesIO: + pass + + @abstractmethod + def show(self) -> None: + pass + + @abstractmethod + def title(self, title: str, ax: Any = 0, color: str | None = None) -> None: + pass + + @abstractmethod + def z_values( + self, + x: ArrayLike, + y: ArrayLike, + z: ArrayLike, + ax: Any = 0, + color: str = "green", + fmt: str = ".1f", + quad_as_tri: bool = False, + ) -> None: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f886268f9c57119c372120dfbbd7c150becf789 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__about__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..119efc97d73c26c536b2e24c147a5edcb332f389 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6a1b067faa89178e345fe424fef0df6f760b50b9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3b1dc3a29d86a264cc9b281ec94c375cd02c1f1a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/fernet.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2c2a5edd0caaf023bed1013414d818cf60f975ba Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b9f1187011bdaa0720bc462564582393700f3d4a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +""" +Hazardous Materials + +This is a "Hazardous Materials" module. You should ONLY use it if you're +100% absolutely sure that you know what you're doing because this module +is full of land mines, dragons, and dinosaurs with laser guns. +""" diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ba6b3aa4b2b34a61639640f08d41355ccec987d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ed70db8a49dbfe10a619ddf53f39be35635a0cd5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/__pycache__/_oid.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/_oid.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/_oid.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf138d4f80b8e83e0657577e338270df18fcdcd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/_oid.py @@ -0,0 +1,356 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import ( + ObjectIdentifier as ObjectIdentifier, +) +from cryptography.hazmat.primitives import hashes + + +class ExtensionOID: + SUBJECT_DIRECTORY_ATTRIBUTES = ObjectIdentifier("2.5.29.9") + SUBJECT_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.14") + KEY_USAGE = ObjectIdentifier("2.5.29.15") + PRIVATE_KEY_USAGE_PERIOD = ObjectIdentifier("2.5.29.16") + SUBJECT_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.17") + ISSUER_ALTERNATIVE_NAME = ObjectIdentifier("2.5.29.18") + BASIC_CONSTRAINTS = ObjectIdentifier("2.5.29.19") + NAME_CONSTRAINTS = ObjectIdentifier("2.5.29.30") + CRL_DISTRIBUTION_POINTS = ObjectIdentifier("2.5.29.31") + CERTIFICATE_POLICIES = ObjectIdentifier("2.5.29.32") + POLICY_MAPPINGS = ObjectIdentifier("2.5.29.33") + AUTHORITY_KEY_IDENTIFIER = ObjectIdentifier("2.5.29.35") + POLICY_CONSTRAINTS = ObjectIdentifier("2.5.29.36") + EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37") + FRESHEST_CRL = ObjectIdentifier("2.5.29.46") + INHIBIT_ANY_POLICY = ObjectIdentifier("2.5.29.54") + ISSUING_DISTRIBUTION_POINT = ObjectIdentifier("2.5.29.28") + AUTHORITY_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.1") + SUBJECT_INFORMATION_ACCESS = ObjectIdentifier("1.3.6.1.5.5.7.1.11") + OCSP_NO_CHECK = ObjectIdentifier("1.3.6.1.5.5.7.48.1.5") + TLS_FEATURE = ObjectIdentifier("1.3.6.1.5.5.7.1.24") + CRL_NUMBER = ObjectIdentifier("2.5.29.20") + DELTA_CRL_INDICATOR = ObjectIdentifier("2.5.29.27") + PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier( + "1.3.6.1.4.1.11129.2.4.2" + ) + PRECERT_POISON = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.3") + SIGNED_CERTIFICATE_TIMESTAMPS = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.5") + MS_CERTIFICATE_TEMPLATE = ObjectIdentifier("1.3.6.1.4.1.311.21.7") + ADMISSIONS = ObjectIdentifier("1.3.36.8.3.3") + + +class OCSPExtensionOID: + NONCE = ObjectIdentifier("1.3.6.1.5.5.7.48.1.2") + ACCEPTABLE_RESPONSES = ObjectIdentifier("1.3.6.1.5.5.7.48.1.4") + + +class CRLEntryExtensionOID: + CERTIFICATE_ISSUER = ObjectIdentifier("2.5.29.29") + CRL_REASON = ObjectIdentifier("2.5.29.21") + INVALIDITY_DATE = ObjectIdentifier("2.5.29.24") + + +class NameOID: + COMMON_NAME = ObjectIdentifier("2.5.4.3") + COUNTRY_NAME = ObjectIdentifier("2.5.4.6") + LOCALITY_NAME = ObjectIdentifier("2.5.4.7") + STATE_OR_PROVINCE_NAME = ObjectIdentifier("2.5.4.8") + STREET_ADDRESS = ObjectIdentifier("2.5.4.9") + ORGANIZATION_IDENTIFIER = ObjectIdentifier("2.5.4.97") + ORGANIZATION_NAME = ObjectIdentifier("2.5.4.10") + ORGANIZATIONAL_UNIT_NAME = ObjectIdentifier("2.5.4.11") + SERIAL_NUMBER = ObjectIdentifier("2.5.4.5") + SURNAME = ObjectIdentifier("2.5.4.4") + GIVEN_NAME = ObjectIdentifier("2.5.4.42") + TITLE = ObjectIdentifier("2.5.4.12") + INITIALS = ObjectIdentifier("2.5.4.43") + GENERATION_QUALIFIER = ObjectIdentifier("2.5.4.44") + X500_UNIQUE_IDENTIFIER = ObjectIdentifier("2.5.4.45") + DN_QUALIFIER = ObjectIdentifier("2.5.4.46") + PSEUDONYM = ObjectIdentifier("2.5.4.65") + USER_ID = ObjectIdentifier("0.9.2342.19200300.100.1.1") + DOMAIN_COMPONENT = ObjectIdentifier("0.9.2342.19200300.100.1.25") + EMAIL_ADDRESS = ObjectIdentifier("1.2.840.113549.1.9.1") + JURISDICTION_COUNTRY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.3") + JURISDICTION_LOCALITY_NAME = ObjectIdentifier("1.3.6.1.4.1.311.60.2.1.1") + JURISDICTION_STATE_OR_PROVINCE_NAME = ObjectIdentifier( + "1.3.6.1.4.1.311.60.2.1.2" + ) + BUSINESS_CATEGORY = ObjectIdentifier("2.5.4.15") + POSTAL_ADDRESS = ObjectIdentifier("2.5.4.16") + POSTAL_CODE = ObjectIdentifier("2.5.4.17") + INN = ObjectIdentifier("1.2.643.3.131.1.1") + OGRN = ObjectIdentifier("1.2.643.100.1") + SNILS = ObjectIdentifier("1.2.643.100.3") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +class SignatureAlgorithmOID: + RSA_WITH_MD5 = ObjectIdentifier("1.2.840.113549.1.1.4") + RSA_WITH_SHA1 = ObjectIdentifier("1.2.840.113549.1.1.5") + # This is an alternate OID for RSA with SHA1 that is occasionally seen + _RSA_WITH_SHA1 = ObjectIdentifier("1.3.14.3.2.29") + RSA_WITH_SHA224 = ObjectIdentifier("1.2.840.113549.1.1.14") + RSA_WITH_SHA256 = ObjectIdentifier("1.2.840.113549.1.1.11") + RSA_WITH_SHA384 = ObjectIdentifier("1.2.840.113549.1.1.12") + RSA_WITH_SHA512 = ObjectIdentifier("1.2.840.113549.1.1.13") + RSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.13") + RSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.14") + RSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.15") + RSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.16") + RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") + ECDSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10045.4.1") + ECDSA_WITH_SHA224 = ObjectIdentifier("1.2.840.10045.4.3.1") + ECDSA_WITH_SHA256 = ObjectIdentifier("1.2.840.10045.4.3.2") + ECDSA_WITH_SHA384 = ObjectIdentifier("1.2.840.10045.4.3.3") + ECDSA_WITH_SHA512 = ObjectIdentifier("1.2.840.10045.4.3.4") + ECDSA_WITH_SHA3_224 = ObjectIdentifier("2.16.840.1.101.3.4.3.9") + ECDSA_WITH_SHA3_256 = ObjectIdentifier("2.16.840.1.101.3.4.3.10") + ECDSA_WITH_SHA3_384 = ObjectIdentifier("2.16.840.1.101.3.4.3.11") + ECDSA_WITH_SHA3_512 = ObjectIdentifier("2.16.840.1.101.3.4.3.12") + DSA_WITH_SHA1 = ObjectIdentifier("1.2.840.10040.4.3") + DSA_WITH_SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.3.1") + DSA_WITH_SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.3.2") + DSA_WITH_SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.3.3") + DSA_WITH_SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.3.4") + ED25519 = ObjectIdentifier("1.3.101.112") + ED448 = ObjectIdentifier("1.3.101.113") + GOSTR3411_94_WITH_3410_2001 = ObjectIdentifier("1.2.643.2.2.3") + GOSTR3410_2012_WITH_3411_2012_256 = ObjectIdentifier("1.2.643.7.1.1.3.2") + GOSTR3410_2012_WITH_3411_2012_512 = ObjectIdentifier("1.2.643.7.1.1.3.3") + + +_SIG_OIDS_TO_HASH: dict[ObjectIdentifier, hashes.HashAlgorithm | None] = { + SignatureAlgorithmOID.RSA_WITH_MD5: hashes.MD5(), + SignatureAlgorithmOID.RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID._RSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.RSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.RSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.RSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.RSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.RSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.RSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.RSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.RSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.ECDSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA384: hashes.SHA384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA512: hashes.SHA512(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_224: hashes.SHA3_224(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_256: hashes.SHA3_256(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_384: hashes.SHA3_384(), + SignatureAlgorithmOID.ECDSA_WITH_SHA3_512: hashes.SHA3_512(), + SignatureAlgorithmOID.DSA_WITH_SHA1: hashes.SHA1(), + SignatureAlgorithmOID.DSA_WITH_SHA224: hashes.SHA224(), + SignatureAlgorithmOID.DSA_WITH_SHA256: hashes.SHA256(), + SignatureAlgorithmOID.ED25519: None, + SignatureAlgorithmOID.ED448: None, + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: None, + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: None, +} + + +class HashAlgorithmOID: + SHA1 = ObjectIdentifier("1.3.14.3.2.26") + SHA224 = ObjectIdentifier("2.16.840.1.101.3.4.2.4") + SHA256 = ObjectIdentifier("2.16.840.1.101.3.4.2.1") + SHA384 = ObjectIdentifier("2.16.840.1.101.3.4.2.2") + SHA512 = ObjectIdentifier("2.16.840.1.101.3.4.2.3") + SHA3_224 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.224") + SHA3_256 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.256") + SHA3_384 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.384") + SHA3_512 = ObjectIdentifier("1.3.6.1.4.1.37476.3.2.1.99.7.512") + SHA3_224_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.7") + SHA3_256_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.8") + SHA3_384_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.9") + SHA3_512_NIST = ObjectIdentifier("2.16.840.1.101.3.4.2.10") + + +class PublicKeyAlgorithmOID: + DSA = ObjectIdentifier("1.2.840.10040.4.1") + EC_PUBLIC_KEY = ObjectIdentifier("1.2.840.10045.2.1") + RSAES_PKCS1_v1_5 = ObjectIdentifier("1.2.840.113549.1.1.1") + RSASSA_PSS = ObjectIdentifier("1.2.840.113549.1.1.10") + X25519 = ObjectIdentifier("1.3.101.110") + X448 = ObjectIdentifier("1.3.101.111") + ED25519 = ObjectIdentifier("1.3.101.112") + ED448 = ObjectIdentifier("1.3.101.113") + + +class ExtendedKeyUsageOID: + SERVER_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.1") + CLIENT_AUTH = ObjectIdentifier("1.3.6.1.5.5.7.3.2") + CODE_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.3") + EMAIL_PROTECTION = ObjectIdentifier("1.3.6.1.5.5.7.3.4") + TIME_STAMPING = ObjectIdentifier("1.3.6.1.5.5.7.3.8") + OCSP_SIGNING = ObjectIdentifier("1.3.6.1.5.5.7.3.9") + ANY_EXTENDED_KEY_USAGE = ObjectIdentifier("2.5.29.37.0") + SMARTCARD_LOGON = ObjectIdentifier("1.3.6.1.4.1.311.20.2.2") + KERBEROS_PKINIT_KDC = ObjectIdentifier("1.3.6.1.5.2.3.5") + IPSEC_IKE = ObjectIdentifier("1.3.6.1.5.5.7.3.17") + BUNDLE_SECURITY = ObjectIdentifier("1.3.6.1.5.5.7.3.35") + CERTIFICATE_TRANSPARENCY = ObjectIdentifier("1.3.6.1.4.1.11129.2.4.4") + + +class OtherNameFormOID: + PERMANENT_IDENTIFIER = ObjectIdentifier("1.3.6.1.5.5.7.8.3") + HW_MODULE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.4") + DNS_SRV = ObjectIdentifier("1.3.6.1.5.5.7.8.7") + NAI_REALM = ObjectIdentifier("1.3.6.1.5.5.7.8.8") + SMTP_UTF8_MAILBOX = ObjectIdentifier("1.3.6.1.5.5.7.8.9") + ACP_NODE_NAME = ObjectIdentifier("1.3.6.1.5.5.7.8.10") + BUNDLE_EID = ObjectIdentifier("1.3.6.1.5.5.7.8.11") + + +class AuthorityInformationAccessOID: + CA_ISSUERS = ObjectIdentifier("1.3.6.1.5.5.7.48.2") + OCSP = ObjectIdentifier("1.3.6.1.5.5.7.48.1") + + +class SubjectInformationAccessOID: + CA_REPOSITORY = ObjectIdentifier("1.3.6.1.5.5.7.48.5") + + +class CertificatePoliciesOID: + CPS_QUALIFIER = ObjectIdentifier("1.3.6.1.5.5.7.2.1") + CPS_USER_NOTICE = ObjectIdentifier("1.3.6.1.5.5.7.2.2") + ANY_POLICY = ObjectIdentifier("2.5.29.32.0") + + +class AttributeOID: + CHALLENGE_PASSWORD = ObjectIdentifier("1.2.840.113549.1.9.7") + UNSTRUCTURED_NAME = ObjectIdentifier("1.2.840.113549.1.9.2") + + +_OID_NAMES = { + NameOID.COMMON_NAME: "commonName", + NameOID.COUNTRY_NAME: "countryName", + NameOID.LOCALITY_NAME: "localityName", + NameOID.STATE_OR_PROVINCE_NAME: "stateOrProvinceName", + NameOID.STREET_ADDRESS: "streetAddress", + NameOID.ORGANIZATION_NAME: "organizationName", + NameOID.ORGANIZATIONAL_UNIT_NAME: "organizationalUnitName", + NameOID.SERIAL_NUMBER: "serialNumber", + NameOID.SURNAME: "surname", + NameOID.GIVEN_NAME: "givenName", + NameOID.TITLE: "title", + NameOID.GENERATION_QUALIFIER: "generationQualifier", + NameOID.X500_UNIQUE_IDENTIFIER: "x500UniqueIdentifier", + NameOID.DN_QUALIFIER: "dnQualifier", + NameOID.PSEUDONYM: "pseudonym", + NameOID.USER_ID: "userID", + NameOID.DOMAIN_COMPONENT: "domainComponent", + NameOID.EMAIL_ADDRESS: "emailAddress", + NameOID.JURISDICTION_COUNTRY_NAME: "jurisdictionCountryName", + NameOID.JURISDICTION_LOCALITY_NAME: "jurisdictionLocalityName", + NameOID.JURISDICTION_STATE_OR_PROVINCE_NAME: ( + "jurisdictionStateOrProvinceName" + ), + NameOID.BUSINESS_CATEGORY: "businessCategory", + NameOID.POSTAL_ADDRESS: "postalAddress", + NameOID.POSTAL_CODE: "postalCode", + NameOID.INN: "INN", + NameOID.OGRN: "OGRN", + NameOID.SNILS: "SNILS", + NameOID.UNSTRUCTURED_NAME: "unstructuredName", + SignatureAlgorithmOID.RSA_WITH_MD5: "md5WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA1: "sha1WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA224: "sha224WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA256: "sha256WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA384: "sha384WithRSAEncryption", + SignatureAlgorithmOID.RSA_WITH_SHA512: "sha512WithRSAEncryption", + SignatureAlgorithmOID.RSASSA_PSS: "rsassaPss", + SignatureAlgorithmOID.ECDSA_WITH_SHA1: "ecdsa-with-SHA1", + SignatureAlgorithmOID.ECDSA_WITH_SHA224: "ecdsa-with-SHA224", + SignatureAlgorithmOID.ECDSA_WITH_SHA256: "ecdsa-with-SHA256", + SignatureAlgorithmOID.ECDSA_WITH_SHA384: "ecdsa-with-SHA384", + SignatureAlgorithmOID.ECDSA_WITH_SHA512: "ecdsa-with-SHA512", + SignatureAlgorithmOID.DSA_WITH_SHA1: "dsa-with-sha1", + SignatureAlgorithmOID.DSA_WITH_SHA224: "dsa-with-sha224", + SignatureAlgorithmOID.DSA_WITH_SHA256: "dsa-with-sha256", + SignatureAlgorithmOID.ED25519: "ed25519", + SignatureAlgorithmOID.ED448: "ed448", + SignatureAlgorithmOID.GOSTR3411_94_WITH_3410_2001: ( + "GOST R 34.11-94 with GOST R 34.10-2001" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_256: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (256 bit)" + ), + SignatureAlgorithmOID.GOSTR3410_2012_WITH_3411_2012_512: ( + "GOST R 34.10-2012 with GOST R 34.11-2012 (512 bit)" + ), + HashAlgorithmOID.SHA1: "sha1", + HashAlgorithmOID.SHA224: "sha224", + HashAlgorithmOID.SHA256: "sha256", + HashAlgorithmOID.SHA384: "sha384", + HashAlgorithmOID.SHA512: "sha512", + HashAlgorithmOID.SHA3_224: "sha3_224", + HashAlgorithmOID.SHA3_256: "sha3_256", + HashAlgorithmOID.SHA3_384: "sha3_384", + HashAlgorithmOID.SHA3_512: "sha3_512", + HashAlgorithmOID.SHA3_224_NIST: "sha3_224", + HashAlgorithmOID.SHA3_256_NIST: "sha3_256", + HashAlgorithmOID.SHA3_384_NIST: "sha3_384", + HashAlgorithmOID.SHA3_512_NIST: "sha3_512", + PublicKeyAlgorithmOID.DSA: "dsaEncryption", + PublicKeyAlgorithmOID.EC_PUBLIC_KEY: "id-ecPublicKey", + PublicKeyAlgorithmOID.RSAES_PKCS1_v1_5: "rsaEncryption", + PublicKeyAlgorithmOID.X25519: "X25519", + PublicKeyAlgorithmOID.X448: "X448", + ExtendedKeyUsageOID.SERVER_AUTH: "serverAuth", + ExtendedKeyUsageOID.CLIENT_AUTH: "clientAuth", + ExtendedKeyUsageOID.CODE_SIGNING: "codeSigning", + ExtendedKeyUsageOID.EMAIL_PROTECTION: "emailProtection", + ExtendedKeyUsageOID.TIME_STAMPING: "timeStamping", + ExtendedKeyUsageOID.OCSP_SIGNING: "OCSPSigning", + ExtendedKeyUsageOID.SMARTCARD_LOGON: "msSmartcardLogin", + ExtendedKeyUsageOID.KERBEROS_PKINIT_KDC: "pkInitKDC", + ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES: "subjectDirectoryAttributes", + ExtensionOID.SUBJECT_KEY_IDENTIFIER: "subjectKeyIdentifier", + ExtensionOID.KEY_USAGE: "keyUsage", + ExtensionOID.PRIVATE_KEY_USAGE_PERIOD: "privateKeyUsagePeriod", + ExtensionOID.SUBJECT_ALTERNATIVE_NAME: "subjectAltName", + ExtensionOID.ISSUER_ALTERNATIVE_NAME: "issuerAltName", + ExtensionOID.BASIC_CONSTRAINTS: "basicConstraints", + ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS: ( + "signedCertificateTimestampList" + ), + ExtensionOID.PRECERT_POISON: "ctPoison", + ExtensionOID.MS_CERTIFICATE_TEMPLATE: "msCertificateTemplate", + ExtensionOID.ADMISSIONS: "Admissions", + CRLEntryExtensionOID.CRL_REASON: "cRLReason", + CRLEntryExtensionOID.INVALIDITY_DATE: "invalidityDate", + CRLEntryExtensionOID.CERTIFICATE_ISSUER: "certificateIssuer", + ExtensionOID.NAME_CONSTRAINTS: "nameConstraints", + ExtensionOID.CRL_DISTRIBUTION_POINTS: "cRLDistributionPoints", + ExtensionOID.CERTIFICATE_POLICIES: "certificatePolicies", + ExtensionOID.POLICY_MAPPINGS: "policyMappings", + ExtensionOID.AUTHORITY_KEY_IDENTIFIER: "authorityKeyIdentifier", + ExtensionOID.POLICY_CONSTRAINTS: "policyConstraints", + ExtensionOID.EXTENDED_KEY_USAGE: "extendedKeyUsage", + ExtensionOID.FRESHEST_CRL: "freshestCRL", + ExtensionOID.INHIBIT_ANY_POLICY: "inhibitAnyPolicy", + ExtensionOID.ISSUING_DISTRIBUTION_POINT: "issuingDistributionPoint", + ExtensionOID.AUTHORITY_INFORMATION_ACCESS: "authorityInfoAccess", + ExtensionOID.SUBJECT_INFORMATION_ACCESS: "subjectInfoAccess", + ExtensionOID.OCSP_NO_CHECK: "OCSPNoCheck", + ExtensionOID.CRL_NUMBER: "cRLNumber", + ExtensionOID.DELTA_CRL_INDICATOR: "deltaCRLIndicator", + ExtensionOID.TLS_FEATURE: "TLSFeature", + AuthorityInformationAccessOID.OCSP: "OCSP", + AuthorityInformationAccessOID.CA_ISSUERS: "caIssuers", + SubjectInformationAccessOID.CA_REPOSITORY: "caRepository", + CertificatePoliciesOID.CPS_QUALIFIER: "id-qt-cps", + CertificatePoliciesOID.CPS_USER_NOTICE: "id-qt-unotice", + OCSPExtensionOID.NONCE: "OCSPNonce", + AttributeOID.CHALLENGE_PASSWORD: "challengePassword", +} diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..be683736e61a4252bd530fcc4b4b23998254dbc3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__init__.py @@ -0,0 +1,10 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.asn1.asn1 import encode_der, sequence + +__all__ = [ + "encode_der", + "sequence", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..524594bcb67df028508cc44a0c7fada6f3288765 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3899ca08300c9410d2cef7a2c7194bd6e4a25b85 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/__pycache__/asn1.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/asn1.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/asn1.py new file mode 100644 index 0000000000000000000000000000000000000000..dedad6f2a67986dac4aca0a4eb633f2cc373f45a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/asn1/asn1.py @@ -0,0 +1,116 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import dataclasses +import sys +import typing + +if sys.version_info < (3, 11): + import typing_extensions + + # We use the `include_extras` parameter of `get_type_hints`, which was + # added in Python 3.9. This can be replaced by the `typing` version + # once the min version is >= 3.9 + if sys.version_info < (3, 9): + get_type_hints = typing_extensions.get_type_hints + else: + get_type_hints = typing.get_type_hints +else: + get_type_hints = typing.get_type_hints + +from cryptography.hazmat.bindings._rust import declarative_asn1 + +T = typing.TypeVar("T", covariant=True) +U = typing.TypeVar("U") + + +encode_der = declarative_asn1.encode_der + + +def _normalize_field_type( + field_type: typing.Any, field_name: str +) -> declarative_asn1.AnnotatedType: + annotation = declarative_asn1.Annotation() + + if hasattr(field_type, "__asn1_root__"): + annotated_root = field_type.__asn1_root__ + if not isinstance(annotated_root, declarative_asn1.AnnotatedType): + raise TypeError(f"unsupported root type: {annotated_root}") + return annotated_root + else: + rust_field_type = declarative_asn1.non_root_python_to_rust(field_type) + + return declarative_asn1.AnnotatedType(rust_field_type, annotation) + + +def _annotate_fields( + raw_fields: dict[str, type], +) -> dict[str, declarative_asn1.AnnotatedType]: + fields = {} + for field_name, field_type in raw_fields.items(): + # Recursively normalize the field type into something that the + # Rust code can understand. + annotated_field_type = _normalize_field_type(field_type, field_name) + fields[field_name] = annotated_field_type + + return fields + + +def _register_asn1_sequence(cls: type[U]) -> None: + raw_fields = get_type_hints(cls, include_extras=True) + root = declarative_asn1.AnnotatedType( + declarative_asn1.Type.Sequence(cls, _annotate_fields(raw_fields)), + declarative_asn1.Annotation(), + ) + + setattr(cls, "__asn1_root__", root) + + +# Due to https://github.com/python/mypy/issues/19731, we can't define an alias +# for `dataclass_transform` that conditionally points to `typing` or +# `typing_extensions` depending on the Python version (like we do for +# `get_type_hints`). +# We work around it by making the whole decorated class conditional on the +# Python version. +if sys.version_info < (3, 11): + + @typing_extensions.dataclass_transform(kw_only_default=True) + def sequence(cls: type[U]) -> type[U]: + # We use `dataclasses.dataclass` to add an __init__ method + # to the class with keyword-only parameters. + if sys.version_info >= (3, 10): + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + # `match_args` was added in Python 3.10 and defaults + # to True + match_args=False, + # `kw_only` was added in Python 3.10 and defaults to + # False + kw_only=True, + )(cls) + else: + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + )(cls) + _register_asn1_sequence(dataclass_cls) + return dataclass_cls + +else: + + @typing.dataclass_transform(kw_only_default=True) + def sequence(cls: type[U]) -> type[U]: + # Only add an __init__ method, with keyword-only + # parameters. + dataclass_cls = dataclasses.dataclass( + repr=False, + eq=False, + match_args=False, + kw_only=True, + )(cls) + _register_asn1_sequence(dataclass_cls) + return dataclass_cls diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b4400aa037451d10d6bcadd455dcf98f9b72e221 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__init__.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from typing import Any + + +def default_backend() -> Any: + from cryptography.hazmat.backends.openssl.backend import backend + + return backend diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f88db57ea95ce206ded4b4939cb5ed3a867b9556 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..51b04476cbb7f4a98051f2fc55bcc1aa35e22d05 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.backends.openssl.backend import backend + +__all__ = ["backend"] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e2a183773744765704bb2f6c4bcd07604d909269 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22f6af3aff312e8e786cfce3f6919ed553da47d3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/__pycache__/backend.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/backend.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/backend.py new file mode 100644 index 0000000000000000000000000000000000000000..248b8c5234257af0a3d329d8ec0589d9c906500a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/backends/openssl/backend.py @@ -0,0 +1,302 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.bindings.openssl import binding +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.asymmetric.padding import ( + MGF1, + OAEP, + PSS, + PKCS1v15, +) +from cryptography.hazmat.primitives.ciphers import ( + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.algorithms import ( + AES, +) +from cryptography.hazmat.primitives.ciphers.modes import ( + CBC, + Mode, +) + + +class Backend: + """ + OpenSSL API binding interfaces. + """ + + name = "openssl" + + # TripleDES encryption is disallowed/deprecated throughout 2023 in + # FIPS 140-3. To keep it simple we denylist any use of TripleDES (TDEA). + _fips_ciphers = (AES,) + # Sometimes SHA1 is still permissible. That logic is contained + # within the various *_supported methods. + _fips_hashes = ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, + hashes.SHAKE128, + hashes.SHAKE256, + ) + _fips_ecdh_curves = ( + ec.SECP224R1, + ec.SECP256R1, + ec.SECP384R1, + ec.SECP521R1, + ) + _fips_rsa_min_key_size = 2048 + _fips_rsa_min_public_exponent = 65537 + _fips_dsa_min_modulus = 1 << 2048 + _fips_dh_min_key_size = 2048 + _fips_dh_min_modulus = 1 << _fips_dh_min_key_size + + def __init__(self) -> None: + self._binding = binding.Binding() + self._ffi = self._binding.ffi + self._lib = self._binding.lib + self._fips_enabled = rust_openssl.is_fips_enabled() + + def __repr__(self) -> str: + return ( + f"" + ) + + def openssl_assert(self, ok: bool) -> None: + return binding._openssl_assert(ok) + + def _enable_fips(self) -> None: + # This function enables FIPS mode for OpenSSL 3.0.0 on installs that + # have the FIPS provider installed properly. + rust_openssl.enable_fips(rust_openssl._providers) + assert rust_openssl.is_fips_enabled() + self._fips_enabled = rust_openssl.is_fips_enabled() + + def openssl_version_text(self) -> str: + """ + Friendly string name of the loaded OpenSSL library. This is not + necessarily the same version as it was compiled against. + + Example: OpenSSL 3.2.1 30 Jan 2024 + """ + return rust_openssl.openssl_version_text() + + def openssl_version_number(self) -> int: + return rust_openssl.openssl_version() + + def hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and not isinstance(algorithm, self._fips_hashes): + return False + + return rust_openssl.hashes.hash_supported(algorithm) + + def signature_hash_supported( + self, algorithm: hashes.HashAlgorithm + ) -> bool: + # Dedicated check for hashing algorithm use in message digest for + # signatures, e.g. RSA PKCS#1 v1.5 SHA1 (sha1WithRSAEncryption). + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + return self.hash_supported(algorithm) + + def scrypt_supported(self) -> bool: + if self._fips_enabled: + return False + else: + return hasattr(rust_openssl.kdf.Scrypt, "derive") + + def argon2_supported(self) -> bool: + if self._fips_enabled: + return False + else: + return hasattr(rust_openssl.kdf.Argon2id, "derive") + + def hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + # FIPS mode still allows SHA1 for HMAC + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return True + if rust_openssl.CRYPTOGRAPHY_IS_AWSLC: + return isinstance( + algorithm, + ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA512_224, + hashes.SHA512_256, + ), + ) + return self.hash_supported(algorithm) + + def cipher_supported(self, cipher: CipherAlgorithm, mode: Mode) -> bool: + if self._fips_enabled: + # FIPS mode requires AES. TripleDES is disallowed/deprecated in + # FIPS 140-3. + if not isinstance(cipher, self._fips_ciphers): + return False + + return rust_openssl.ciphers.cipher_supported(cipher, mode) + + def pbkdf2_hmac_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + return self.hmac_supported(algorithm) + + def _consume_errors(self) -> list[rust_openssl.OpenSSLError]: + return rust_openssl.capture_error_stack() + + def _oaep_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if self._fips_enabled and isinstance(algorithm, hashes.SHA1): + return False + + return isinstance( + algorithm, + ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ) + + def rsa_padding_supported(self, padding: AsymmetricPadding) -> bool: + if isinstance(padding, PKCS1v15): + return True + elif isinstance(padding, PSS) and isinstance(padding._mgf, MGF1): + # FIPS 186-4 only allows salt length == digest length for PSS + # It is technically acceptable to set an explicit salt length + # equal to the digest length and this will incorrectly fail, but + # since we don't do that in the tests and this method is + # private, we'll ignore that until we need to do otherwise. + if ( + self._fips_enabled + and padding._salt_length != PSS.DIGEST_LENGTH + ): + return False + return self.hash_supported(padding._mgf._algorithm) + elif isinstance(padding, OAEP) and isinstance(padding._mgf, MGF1): + return self._oaep_hash_supported( + padding._mgf._algorithm + ) and self._oaep_hash_supported(padding._algorithm) + else: + return False + + def rsa_encryption_supported(self, padding: AsymmetricPadding) -> bool: + if self._fips_enabled and isinstance(padding, PKCS1v15): + return False + else: + return self.rsa_padding_supported(padding) + + def dsa_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not self._fips_enabled + ) + + def dsa_hash_supported(self, algorithm: hashes.HashAlgorithm) -> bool: + if not self.dsa_supported(): + return False + return self.signature_hash_supported(algorithm) + + def cmac_algorithm_supported(self, algorithm) -> bool: + return self.cipher_supported( + algorithm, CBC(b"\x00" * algorithm.block_size) + ) + + def elliptic_curve_supported(self, curve: ec.EllipticCurve) -> bool: + if self._fips_enabled and not isinstance( + curve, self._fips_ecdh_curves + ): + return False + + return rust_openssl.ec.curve_supported(curve) + + def elliptic_curve_signature_algorithm_supported( + self, + signature_algorithm: ec.EllipticCurveSignatureAlgorithm, + curve: ec.EllipticCurve, + ) -> bool: + # We only support ECDSA right now. + if not isinstance(signature_algorithm, ec.ECDSA): + return False + + return self.elliptic_curve_supported(curve) and ( + isinstance(signature_algorithm.algorithm, asym_utils.Prehashed) + or self.hash_supported(signature_algorithm.algorithm) + ) + + def elliptic_curve_exchange_algorithm_supported( + self, algorithm: ec.ECDH, curve: ec.EllipticCurve + ) -> bool: + return self.elliptic_curve_supported(curve) and isinstance( + algorithm, ec.ECDH + ) + + def dh_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def dh_x942_serialization_supported(self) -> bool: + return self._lib.Cryptography_HAS_EVP_PKEY_DHX == 1 + + def x25519_supported(self) -> bool: + return not self._fips_enabled + + def x448_supported(self) -> bool: + if self._fips_enabled: + return False + return ( + not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL + and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def ed25519_supported(self) -> bool: + return not self._fips_enabled + + def ed448_supported(self) -> bool: + if self._fips_enabled: + return False + return ( + not rust_openssl.CRYPTOGRAPHY_IS_LIBRESSL + and not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + def ecdsa_deterministic_supported(self) -> bool: + return ( + rust_openssl.CRYPTOGRAPHY_OPENSSL_320_OR_GREATER + and not self._fips_enabled + ) + + def poly1305_supported(self) -> bool: + return not self._fips_enabled + + def pkcs7_supported(self) -> bool: + return ( + not rust_openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not rust_openssl.CRYPTOGRAPHY_IS_AWSLC + ) + + +backend = Backend() diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2da07f2bd0a5e9cc295653d4227a961b391551ed Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..2f4eef4ead80ad7c006ddf7c4b28fcd48ad6fa33 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/__init__.pyi @@ -0,0 +1,37 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import padding +from cryptography.utils import Buffer + +class PKCS7PaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class ANSIX923PaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class PKCS7UnpaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class ANSIX923UnpaddingContext(padding.PaddingContext): + def __init__(self, block_size: int) -> None: ... + def update(self, data: Buffer) -> bytes: ... + def finalize(self) -> bytes: ... + +class ObjectIdentifier: + def __init__(self, value: str) -> None: ... + @property + def dotted_string(self) -> str: ... + @property + def _name(self) -> str: ... + +T = typing.TypeVar("T") diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi new file mode 100644 index 0000000000000000000000000000000000000000..80100082acd30b6bc69e5b8ab0972d77a33dc11a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/_openssl.pyi @@ -0,0 +1,8 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +lib = typing.Any +ffi = typing.Any diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3b5f208ecf09aa661854e6983507b0e7b1ef15cb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/asn1.pyi @@ -0,0 +1,7 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +def decode_dss_signature(signature: bytes) -> tuple[int, int]: ... +def encode_dss_signature(r: int, s: int) -> bytes: ... +def parse_spki_for_data(data: bytes) -> bytes: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi new file mode 100644 index 0000000000000000000000000000000000000000..8563c11f1043fa634d0d6776e73209e92e5824e7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/declarative_asn1.pyi @@ -0,0 +1,32 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. +import typing + +def encode_der(value: typing.Any) -> bytes: ... +def non_root_python_to_rust(cls: type) -> Type: ... + +# Type is a Rust enum with tuple variants. For now, we express the type +# annotations like this: +class Type: + Sequence: typing.ClassVar[type] + PyInt: typing.ClassVar[type] + +class Annotation: + def __new__( + cls, + ) -> Annotation: ... + +class AnnotatedType: + inner: Type + annotation: Annotation + + def __new__(cls, inner: Type, annotation: Annotation) -> AnnotatedType: ... + +class AnnotatedTypeObject: + annotated_type: AnnotatedType + value: typing.Any + + def __new__( + cls, annotated_type: AnnotatedType, value: typing.Any + ) -> AnnotatedTypeObject: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi new file mode 100644 index 0000000000000000000000000000000000000000..09f46b1e817f806873c4a4bdd7b8466046b5f64d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/exceptions.pyi @@ -0,0 +1,17 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +class _Reasons: + BACKEND_MISSING_INTERFACE: _Reasons + UNSUPPORTED_HASH: _Reasons + UNSUPPORTED_CIPHER: _Reasons + UNSUPPORTED_PADDING: _Reasons + UNSUPPORTED_MGF: _Reasons + UNSUPPORTED_PUBLIC_KEY_ALGORITHM: _Reasons + UNSUPPORTED_ELLIPTIC_CURVE: _Reasons + UNSUPPORTED_SERIALIZATION: _Reasons + UNSUPPORTED_X509: _Reasons + UNSUPPORTED_EXCHANGE_ALGORITHM: _Reasons + UNSUPPORTED_DIFFIE_HELLMAN: _Reasons + UNSUPPORTED_MAC: _Reasons diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi new file mode 100644 index 0000000000000000000000000000000000000000..103e96c1f117ed06924569fadb6a2b680fbd5456 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/ocsp.pyi @@ -0,0 +1,117 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import datetime +from collections.abc import Iterator + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes +from cryptography.x509 import ocsp + +class OCSPRequest: + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + @property + def extensions(self) -> x509.Extensions: ... + +class OCSPResponse: + @property + def responses(self) -> Iterator[OCSPSingleResponse]: ... + @property + def response_status(self) -> ocsp.OCSPResponseStatus: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_response_bytes(self) -> bytes: ... + @property + def certificates(self) -> list[x509.Certificate]: ... + @property + def responder_key_hash(self) -> bytes | None: ... + @property + def responder_name(self) -> x509.Name | None: ... + @property + def produced_at(self) -> datetime.datetime: ... + @property + def produced_at_utc(self) -> datetime.datetime: ... + @property + def certificate_status(self) -> ocsp.OCSPCertStatus: ... + @property + def revocation_time(self) -> datetime.datetime | None: ... + @property + def revocation_time_utc(self) -> datetime.datetime | None: ... + @property + def revocation_reason(self) -> x509.ReasonFlags | None: ... + @property + def this_update(self) -> datetime.datetime: ... + @property + def this_update_utc(self) -> datetime.datetime: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def single_extensions(self) -> x509.Extensions: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + +class OCSPSingleResponse: + @property + def certificate_status(self) -> ocsp.OCSPCertStatus: ... + @property + def revocation_time(self) -> datetime.datetime | None: ... + @property + def revocation_time_utc(self) -> datetime.datetime | None: ... + @property + def revocation_reason(self) -> x509.ReasonFlags | None: ... + @property + def this_update(self) -> datetime.datetime: ... + @property + def this_update_utc(self) -> datetime.datetime: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def issuer_key_hash(self) -> bytes: ... + @property + def issuer_name_hash(self) -> bytes: ... + @property + def hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def serial_number(self) -> int: ... + +def load_der_ocsp_request(data: bytes) -> ocsp.OCSPRequest: ... +def load_der_ocsp_response(data: bytes) -> ocsp.OCSPResponse: ... +def create_ocsp_request( + builder: ocsp.OCSPRequestBuilder, +) -> ocsp.OCSPRequest: ... +def create_ocsp_response( + status: ocsp.OCSPResponseStatus, + builder: ocsp.OCSPResponseBuilder | None, + private_key: PrivateKeyTypes | None, + hash_algorithm: hashes.HashAlgorithm | None, +) -> ocsp.OCSPResponse: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5fb3cb2403c0cd9b39059f0030036037f8ae0094 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/__init__.pyi @@ -0,0 +1,75 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.bindings._rust.openssl import ( + aead, + ciphers, + cmac, + dh, + dsa, + ec, + ed448, + ed25519, + hashes, + hmac, + kdf, + keys, + poly1305, + rsa, + x448, + x25519, +) + +__all__ = [ + "aead", + "ciphers", + "cmac", + "dh", + "dsa", + "ec", + "ed448", + "ed25519", + "hashes", + "hmac", + "kdf", + "keys", + "openssl_version", + "openssl_version_text", + "poly1305", + "raise_openssl_error", + "rsa", + "x448", + "x25519", +] + +CRYPTOGRAPHY_IS_LIBRESSL: bool +CRYPTOGRAPHY_IS_BORINGSSL: bool +CRYPTOGRAPHY_IS_AWSLC: bool +CRYPTOGRAPHY_OPENSSL_300_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_309_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_320_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_330_OR_GREATER: bool +CRYPTOGRAPHY_OPENSSL_350_OR_GREATER: bool + +class Providers: ... + +_legacy_provider_loaded: bool +_providers: Providers + +def openssl_version() -> int: ... +def openssl_version_text() -> str: ... +def raise_openssl_error() -> typing.NoReturn: ... +def capture_error_stack() -> list[OpenSSLError]: ... +def is_fips_enabled() -> bool: ... +def enable_fips(providers: Providers) -> None: ... + +class OpenSSLError: + @property + def lib(self) -> int: ... + @property + def reason(self) -> int: ... + @property + def reason_text(self) -> bytes: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi new file mode 100644 index 0000000000000000000000000000000000000000..831fcd1469d563a87b7db8db50a1bbdb590f866f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/aead.pyi @@ -0,0 +1,107 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from collections.abc import Sequence + +from cryptography.utils import Buffer + +class AESGCM: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + +class ChaCha20Poly1305: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key() -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + +class AESCCM: + def __init__(self, key: Buffer, tag_length: int = 16) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + +class AESSIV: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + ) -> bytes: ... + def decrypt( + self, + data: Buffer, + associated_data: Sequence[Buffer] | None, + ) -> bytes: ... + +class AESOCB3: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + +class AESGCMSIV: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_key(bit_length: int) -> bytes: ... + def encrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... + def decrypt( + self, + nonce: Buffer, + data: Buffer, + associated_data: Buffer | None, + ) -> bytes: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi new file mode 100644 index 0000000000000000000000000000000000000000..a48fb017ff562b3d26fa849ebf0c0f9dafb36aaf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ciphers.pyi @@ -0,0 +1,38 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import ciphers +from cryptography.hazmat.primitives.ciphers import modes + +@typing.overload +def create_encryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag +) -> ciphers.AEADEncryptionContext: ... +@typing.overload +def create_encryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None +) -> ciphers.CipherContext: ... +@typing.overload +def create_decryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.ModeWithAuthenticationTag +) -> ciphers.AEADDecryptionContext: ... +@typing.overload +def create_decryption_ctx( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode | None +) -> ciphers.CipherContext: ... +def cipher_supported( + algorithm: ciphers.CipherAlgorithm, mode: modes.Mode +) -> bool: ... +def _advance( + ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int +) -> None: ... +def _advance_aad( + ctx: ciphers.AEADEncryptionContext | ciphers.AEADDecryptionContext, n: int +) -> None: ... + +class CipherContext: ... +class AEADEncryptionContext: ... +class AEADDecryptionContext: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9c03508bc89bf087e24c684802eeec344d76bb9e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/cmac.pyi @@ -0,0 +1,18 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import ciphers + +class CMAC: + def __init__( + self, + algorithm: ciphers.BlockCipherAlgorithm, + backend: typing.Any = None, + ) -> None: ... + def update(self, data: bytes) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, signature: bytes) -> None: ... + def copy(self) -> CMAC: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi new file mode 100644 index 0000000000000000000000000000000000000000..08733d745c3ddc994f358193dd4b79ce359583d8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dh.pyi @@ -0,0 +1,51 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import dh + +MIN_MODULUS_SIZE: int + +class DHPrivateKey: ... +class DHPublicKey: ... +class DHParameters: ... + +class DHPrivateNumbers: + def __init__(self, x: int, public_numbers: DHPublicNumbers) -> None: ... + def private_key(self, backend: typing.Any = None) -> dh.DHPrivateKey: ... + @property + def x(self) -> int: ... + @property + def public_numbers(self) -> DHPublicNumbers: ... + +class DHPublicNumbers: + def __init__( + self, y: int, parameter_numbers: DHParameterNumbers + ) -> None: ... + def public_key(self, backend: typing.Any = None) -> dh.DHPublicKey: ... + @property + def y(self) -> int: ... + @property + def parameter_numbers(self) -> DHParameterNumbers: ... + +class DHParameterNumbers: + def __init__(self, p: int, g: int, q: int | None = None) -> None: ... + def parameters(self, backend: typing.Any = None) -> dh.DHParameters: ... + @property + def p(self) -> int: ... + @property + def g(self) -> int: ... + @property + def q(self) -> int | None: ... + +def generate_parameters( + generator: int, key_size: int, backend: typing.Any = None +) -> dh.DHParameters: ... +def from_pem_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: ... +def from_der_parameters( + data: bytes, backend: typing.Any = None +) -> dh.DHParameters: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..0922a4c4041a90b1e884f56522f82bced398c80e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/dsa.pyi @@ -0,0 +1,41 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import dsa + +class DSAPrivateKey: ... +class DSAPublicKey: ... +class DSAParameters: ... + +class DSAPrivateNumbers: + def __init__(self, x: int, public_numbers: DSAPublicNumbers) -> None: ... + @property + def x(self) -> int: ... + @property + def public_numbers(self) -> DSAPublicNumbers: ... + def private_key(self, backend: typing.Any = None) -> dsa.DSAPrivateKey: ... + +class DSAPublicNumbers: + def __init__( + self, y: int, parameter_numbers: DSAParameterNumbers + ) -> None: ... + @property + def y(self) -> int: ... + @property + def parameter_numbers(self) -> DSAParameterNumbers: ... + def public_key(self, backend: typing.Any = None) -> dsa.DSAPublicKey: ... + +class DSAParameterNumbers: + def __init__(self, p: int, q: int, g: int) -> None: ... + @property + def p(self) -> int: ... + @property + def q(self) -> int: ... + @property + def g(self) -> int: ... + def parameters(self, backend: typing.Any = None) -> dsa.DSAParameters: ... + +def generate_parameters(key_size: int) -> dsa.DSAParameters: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi new file mode 100644 index 0000000000000000000000000000000000000000..5c3b7bf6e4a9bafac1423bd3936ebc347885a950 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ec.pyi @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import ec + +class ECPrivateKey: ... +class ECPublicKey: ... + +class EllipticCurvePrivateNumbers: + def __init__( + self, private_value: int, public_numbers: EllipticCurvePublicNumbers + ) -> None: ... + def private_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePrivateKey: ... + @property + def private_value(self) -> int: ... + @property + def public_numbers(self) -> EllipticCurvePublicNumbers: ... + +class EllipticCurvePublicNumbers: + def __init__(self, x: int, y: int, curve: ec.EllipticCurve) -> None: ... + def public_key( + self, backend: typing.Any = None + ) -> ec.EllipticCurvePublicKey: ... + @property + def x(self) -> int: ... + @property + def y(self) -> int: ... + @property + def curve(self) -> ec.EllipticCurve: ... + def __eq__(self, other: object) -> bool: ... + +def curve_supported(curve: ec.EllipticCurve) -> bool: ... +def generate_private_key( + curve: ec.EllipticCurve, backend: typing.Any = None +) -> ec.EllipticCurvePrivateKey: ... +def from_private_numbers( + numbers: ec.EllipticCurvePrivateNumbers, +) -> ec.EllipticCurvePrivateKey: ... +def from_public_numbers( + numbers: ec.EllipticCurvePublicNumbers, +) -> ec.EllipticCurvePublicKey: ... +def from_public_bytes( + curve: ec.EllipticCurve, data: bytes +) -> ec.EllipticCurvePublicKey: ... +def derive_private_key( + private_value: int, curve: ec.EllipticCurve +) -> ec.EllipticCurvePrivateKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..f85b3d1b2361832095a00ba9b67675ad365339dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed25519.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed25519 +from cryptography.utils import Buffer + +class Ed25519PrivateKey: ... +class Ed25519PublicKey: ... + +def generate_key() -> ed25519.Ed25519PrivateKey: ... +def from_private_bytes(data: Buffer) -> ed25519.Ed25519PrivateKey: ... +def from_public_bytes(data: bytes) -> ed25519.Ed25519PublicKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c8ca0ecb156b9d9a7e69cf10bf71f187362f3315 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/ed448.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import ed448 +from cryptography.utils import Buffer + +class Ed448PrivateKey: ... +class Ed448PublicKey: ... + +def generate_key() -> ed448.Ed448PrivateKey: ... +def from_private_bytes(data: Buffer) -> ed448.Ed448PrivateKey: ... +def from_public_bytes(data: bytes) -> ed448.Ed448PublicKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi new file mode 100644 index 0000000000000000000000000000000000000000..6bfd295af88964a4a09c59ecafcce3d0890ff350 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hashes.pyi @@ -0,0 +1,28 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.utils import Buffer + +class Hash(hashes.HashContext): + def __init__( + self, algorithm: hashes.HashAlgorithm, backend: typing.Any = None + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def copy(self) -> Hash: ... + +def hash_supported(algorithm: hashes.HashAlgorithm) -> bool: ... + +class XOFHash: + def __init__(self, algorithm: hashes.ExtendableOutputFunction) -> None: ... + @property + def algorithm(self) -> hashes.ExtendableOutputFunction: ... + def update(self, data: Buffer) -> None: ... + def squeeze(self, length: int) -> bytes: ... + def copy(self) -> XOFHash: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3883d1b1a920b0f118a6e9c6084f9532a5484bec --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/hmac.pyi @@ -0,0 +1,22 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives import hashes +from cryptography.utils import Buffer + +class HMAC(hashes.HashContext): + def __init__( + self, + key: Buffer, + algorithm: hashes.HashAlgorithm, + backend: typing.Any = None, + ) -> None: ... + @property + def algorithm(self) -> hashes.HashAlgorithm: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, signature: bytes) -> None: ... + def copy(self) -> HMAC: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi new file mode 100644 index 0000000000000000000000000000000000000000..9e2d8d99055af7e8ca3879b66e47bfbdc5ca942c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/kdf.pyi @@ -0,0 +1,72 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.hashes import HashAlgorithm +from cryptography.utils import Buffer + +def derive_pbkdf2_hmac( + key_material: Buffer, + algorithm: HashAlgorithm, + salt: bytes, + iterations: int, + length: int, +) -> bytes: ... + +class Scrypt: + def __init__( + self, + salt: bytes, + length: int, + n: int, + r: int, + p: int, + backend: typing.Any = None, + ) -> None: ... + def derive(self, key_material: Buffer) -> bytes: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class Argon2id: + def __init__( + self, + *, + salt: bytes, + length: int, + iterations: int, + lanes: int, + memory_cost: int, + ad: bytes | None = None, + secret: bytes | None = None, + ) -> None: ... + def derive(self, key_material: bytes) -> bytes: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + def derive_phc_encoded(self, key_material: bytes) -> str: ... + @classmethod + def verify_phc_encoded( + cls, key_material: bytes, phc_encoded: str, secret: bytes | None = None + ) -> None: ... + +class HKDF: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + salt: bytes | None, + info: bytes | None, + backend: typing.Any = None, + ): ... + def derive(self, key_material: Buffer) -> bytes: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... + +class HKDFExpand: + def __init__( + self, + algorithm: HashAlgorithm, + length: int, + info: bytes | None, + backend: typing.Any = None, + ): ... + def derive(self, key_material: Buffer) -> bytes: ... + def verify(self, key_material: bytes, expected_key: bytes) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi new file mode 100644 index 0000000000000000000000000000000000000000..404057e037408dd1979afc482768430b8b478646 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/keys.pyi @@ -0,0 +1,34 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric.types import ( + PrivateKeyTypes, + PublicKeyTypes, +) +from cryptography.utils import Buffer + +def load_der_private_key( + data: Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: ... +def load_pem_private_key( + data: Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> PrivateKeyTypes: ... +def load_der_public_key( + data: bytes, + backend: typing.Any = None, +) -> PublicKeyTypes: ... +def load_pem_public_key( + data: bytes, + backend: typing.Any = None, +) -> PublicKeyTypes: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi new file mode 100644 index 0000000000000000000000000000000000000000..45a2a39f689071b5d544d8495bfd5bd57d4ab6e4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/poly1305.pyi @@ -0,0 +1,15 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.utils import Buffer + +class Poly1305: + def __init__(self, key: Buffer) -> None: ... + @staticmethod + def generate_tag(key: Buffer, data: Buffer) -> bytes: ... + @staticmethod + def verify_tag(key: Buffer, data: Buffer, tag: bytes) -> None: ... + def update(self, data: Buffer) -> None: ... + def finalize(self) -> bytes: ... + def verify(self, tag: bytes) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef7752ddb79db62489bcf71df933fdefd83c0f9d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/rsa.pyi @@ -0,0 +1,55 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing + +from cryptography.hazmat.primitives.asymmetric import rsa + +class RSAPrivateKey: ... +class RSAPublicKey: ... + +class RSAPrivateNumbers: + def __init__( + self, + p: int, + q: int, + d: int, + dmp1: int, + dmq1: int, + iqmp: int, + public_numbers: RSAPublicNumbers, + ) -> None: ... + @property + def p(self) -> int: ... + @property + def q(self) -> int: ... + @property + def d(self) -> int: ... + @property + def dmp1(self) -> int: ... + @property + def dmq1(self) -> int: ... + @property + def iqmp(self) -> int: ... + @property + def public_numbers(self) -> RSAPublicNumbers: ... + def private_key( + self, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, + ) -> rsa.RSAPrivateKey: ... + +class RSAPublicNumbers: + def __init__(self, e: int, n: int) -> None: ... + @property + def n(self) -> int: ... + @property + def e(self) -> int: ... + def public_key(self, backend: typing.Any = None) -> rsa.RSAPublicKey: ... + +def generate_private_key( + public_exponent: int, + key_size: int, +) -> rsa.RSAPrivateKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi new file mode 100644 index 0000000000000000000000000000000000000000..38d2adddb1017030139f2cb2411dc43101a7448e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x25519.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x25519 +from cryptography.utils import Buffer + +class X25519PrivateKey: ... +class X25519PublicKey: ... + +def generate_key() -> x25519.X25519PrivateKey: ... +def from_private_bytes(data: Buffer) -> x25519.X25519PrivateKey: ... +def from_public_bytes(data: bytes) -> x25519.X25519PublicKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi new file mode 100644 index 0000000000000000000000000000000000000000..3ac098091af514639889486723710f851cd93e6b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/openssl/x448.pyi @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.primitives.asymmetric import x448 +from cryptography.utils import Buffer + +class X448PrivateKey: ... +class X448PublicKey: ... + +def generate_key() -> x448.X448PrivateKey: ... +def from_private_bytes(data: Buffer) -> x448.X448PrivateKey: ... +def from_public_bytes(data: bytes) -> x448.X448PublicKey: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi new file mode 100644 index 0000000000000000000000000000000000000000..b25becb6bdef7ce259dcb40f34aa9386774437ca --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs12.pyi @@ -0,0 +1,52 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import typing +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes +from cryptography.hazmat.primitives.serialization import ( + KeySerializationEncryption, +) +from cryptography.hazmat.primitives.serialization.pkcs12 import ( + PKCS12KeyAndCertificates, + PKCS12PrivateKeyTypes, +) +from cryptography.utils import Buffer + +class PKCS12Certificate: + def __init__( + self, cert: x509.Certificate, friendly_name: bytes | None + ) -> None: ... + @property + def friendly_name(self) -> bytes | None: ... + @property + def certificate(self) -> x509.Certificate: ... + +def load_key_and_certificates( + data: Buffer, + password: Buffer | None, + backend: typing.Any = None, +) -> tuple[ + PrivateKeyTypes | None, + x509.Certificate | None, + list[x509.Certificate], +]: ... +def load_pkcs12( + data: bytes, + password: bytes | None, + backend: typing.Any = None, +) -> PKCS12KeyAndCertificates: ... +def serialize_java_truststore( + certs: Iterable[PKCS12Certificate], + encryption_algorithm: KeySerializationEncryption, +) -> bytes: ... +def serialize_key_and_certificates( + name: bytes | None, + key: PKCS12PrivateKeyTypes | None, + cert: x509.Certificate | None, + cas: Iterable[x509.Certificate | PKCS12Certificate] | None, + encryption_algorithm: KeySerializationEncryption, +) -> bytes: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi new file mode 100644 index 0000000000000000000000000000000000000000..358b135865a89a6675706e0fd880d3eabdb081b5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/pkcs7.pyi @@ -0,0 +1,50 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.serialization import pkcs7 + +def serialize_certificates( + certs: list[x509.Certificate], + encoding: serialization.Encoding, +) -> bytes: ... +def encrypt_and_serialize( + builder: pkcs7.PKCS7EnvelopeBuilder, + content_encryption_algorithm: pkcs7.ContentEncryptionAlgorithm, + encoding: serialization.Encoding, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def sign_and_serialize( + builder: pkcs7.PKCS7SignatureBuilder, + encoding: serialization.Encoding, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_der( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_pem( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def decrypt_smime( + data: bytes, + certificate: x509.Certificate, + private_key: rsa.RSAPrivateKey, + options: Iterable[pkcs7.PKCS7Options], +) -> bytes: ... +def load_pem_pkcs7_certificates( + data: bytes, +) -> list[x509.Certificate]: ... +def load_der_pkcs7_certificates( + data: bytes, +) -> list[x509.Certificate]: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi new file mode 100644 index 0000000000000000000000000000000000000000..c6c6d0bbe12916b4299d08398493c5da8f762ae7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/test_support.pyi @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography import x509 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.serialization import pkcs7 +from cryptography.utils import Buffer + +class TestCertificate: + not_after_tag: int + not_before_tag: int + issuer_value_tags: list[int] + subject_value_tags: list[int] + +def test_parse_certificate(data: bytes) -> TestCertificate: ... +def pkcs7_verify( + encoding: serialization.Encoding, + sig: bytes, + msg: Buffer | None, + certs: list[x509.Certificate], + options: list[pkcs7.PKCS7Options], +) -> None: ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi new file mode 100644 index 0000000000000000000000000000000000000000..83c3441b24dc67b895195aa5ce6dea30c8b67e5d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/_rust/x509.pyi @@ -0,0 +1,301 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +import datetime +import typing +from collections.abc import Iterator + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.ec import ECDSA +from cryptography.hazmat.primitives.asymmetric.padding import PSS, PKCS1v15 +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, + PrivateKeyTypes, +) +from cryptography.x509 import certificate_transparency + +def load_pem_x509_certificate( + data: bytes, backend: typing.Any = None +) -> x509.Certificate: ... +def load_der_x509_certificate( + data: bytes, backend: typing.Any = None +) -> x509.Certificate: ... +def load_pem_x509_certificates( + data: bytes, +) -> list[x509.Certificate]: ... +def load_pem_x509_crl( + data: bytes, backend: typing.Any = None +) -> x509.CertificateRevocationList: ... +def load_der_x509_crl( + data: bytes, backend: typing.Any = None +) -> x509.CertificateRevocationList: ... +def load_pem_x509_csr( + data: bytes, backend: typing.Any = None +) -> x509.CertificateSigningRequest: ... +def load_der_x509_csr( + data: bytes, backend: typing.Any = None +) -> x509.CertificateSigningRequest: ... +def encode_name_bytes(name: x509.Name) -> bytes: ... +def encode_extension_value(extension: x509.ExtensionType) -> bytes: ... +def create_x509_certificate( + builder: x509.CertificateBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.Certificate: ... +def create_x509_csr( + builder: x509.CertificateSigningRequestBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.CertificateSigningRequest: ... +def create_x509_crl( + builder: x509.CertificateRevocationListBuilder, + private_key: PrivateKeyTypes, + hash_algorithm: hashes.HashAlgorithm | None, + rsa_padding: PKCS1v15 | PSS | None, + ecdsa_deterministic: bool | None, +) -> x509.CertificateRevocationList: ... + +class Sct: + @property + def version(self) -> certificate_transparency.Version: ... + @property + def log_id(self) -> bytes: ... + @property + def timestamp(self) -> datetime.datetime: ... + @property + def entry_type(self) -> certificate_transparency.LogEntryType: ... + @property + def signature_hash_algorithm(self) -> hashes.HashAlgorithm: ... + @property + def signature_algorithm( + self, + ) -> certificate_transparency.SignatureAlgorithm: ... + @property + def signature(self) -> bytes: ... + @property + def extension_bytes(self) -> bytes: ... + +class Certificate: + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... + @property + def serial_number(self) -> int: ... + @property + def version(self) -> x509.Version: ... + def public_key(self) -> CertificatePublicKeyTypes: ... + @property + def public_key_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def not_valid_before(self) -> datetime.datetime: ... + @property + def not_valid_before_utc(self) -> datetime.datetime: ... + @property + def not_valid_after(self) -> datetime.datetime: ... + @property + def not_valid_after_utc(self) -> datetime.datetime: ... + @property + def issuer(self) -> x509.Name: ... + @property + def subject(self) -> x509.Name: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certificate_bytes(self) -> bytes: ... + @property + def tbs_precertificate_bytes(self) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + def verify_directly_issued_by(self, issuer: Certificate) -> None: ... + +class RevokedCertificate: ... + +class CertificateRevocationList: + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + def fingerprint(self, algorithm: hashes.HashAlgorithm) -> bytes: ... + def get_revoked_certificate_by_serial_number( + self, serial_number: int + ) -> x509.RevokedCertificate | None: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def issuer(self) -> x509.Name: ... + @property + def next_update(self) -> datetime.datetime | None: ... + @property + def next_update_utc(self) -> datetime.datetime | None: ... + @property + def last_update(self) -> datetime.datetime: ... + @property + def last_update_utc(self) -> datetime.datetime: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certlist_bytes(self) -> bytes: ... + def __eq__(self, other: object) -> bool: ... + def __len__(self) -> int: ... + @typing.overload + def __getitem__(self, idx: int) -> x509.RevokedCertificate: ... + @typing.overload + def __getitem__(self, idx: slice) -> list[x509.RevokedCertificate]: ... + def __iter__(self) -> Iterator[x509.RevokedCertificate]: ... + def is_signature_valid( + self, public_key: CertificateIssuerPublicKeyTypes + ) -> bool: ... + +class CertificateSigningRequest: + def __eq__(self, other: object) -> bool: ... + def __hash__(self) -> int: ... + def public_key(self) -> CertificatePublicKeyTypes: ... + @property + def subject(self) -> x509.Name: ... + @property + def signature_hash_algorithm( + self, + ) -> hashes.HashAlgorithm | None: ... + @property + def signature_algorithm_oid(self) -> x509.ObjectIdentifier: ... + @property + def signature_algorithm_parameters( + self, + ) -> PSS | PKCS1v15 | ECDSA | None: ... + @property + def extensions(self) -> x509.Extensions: ... + @property + def attributes(self) -> x509.Attributes: ... + def public_bytes(self, encoding: serialization.Encoding) -> bytes: ... + @property + def signature(self) -> bytes: ... + @property + def tbs_certrequest_bytes(self) -> bytes: ... + @property + def is_signature_valid(self) -> bool: ... + +class PolicyBuilder: + def time(self, time: datetime.datetime) -> PolicyBuilder: ... + def store(self, store: Store) -> PolicyBuilder: ... + def max_chain_depth(self, max_chain_depth: int) -> PolicyBuilder: ... + def extension_policies( + self, *, ca_policy: ExtensionPolicy, ee_policy: ExtensionPolicy + ) -> PolicyBuilder: ... + def build_client_verifier(self) -> ClientVerifier: ... + def build_server_verifier( + self, subject: x509.verification.Subject + ) -> ServerVerifier: ... + +class Policy: + @property + def max_chain_depth(self) -> int: ... + @property + def subject(self) -> x509.verification.Subject | None: ... + @property + def validation_time(self) -> datetime.datetime: ... + @property + def extended_key_usage(self) -> x509.ObjectIdentifier: ... + @property + def minimum_rsa_modulus(self) -> int: ... + +class Criticality: + CRITICAL: Criticality + AGNOSTIC: Criticality + NON_CRITICAL: Criticality + +T = typing.TypeVar("T", contravariant=True, bound=x509.ExtensionType) + +MaybeExtensionValidatorCallback = typing.Callable[ + [ + Policy, + x509.Certificate, + T | None, + ], + None, +] + +PresentExtensionValidatorCallback = typing.Callable[ + [Policy, x509.Certificate, T], + None, +] + +class ExtensionPolicy: + @staticmethod + def permit_all() -> ExtensionPolicy: ... + @staticmethod + def webpki_defaults_ca() -> ExtensionPolicy: ... + @staticmethod + def webpki_defaults_ee() -> ExtensionPolicy: ... + def require_not_present( + self, extension_type: type[x509.ExtensionType] + ) -> ExtensionPolicy: ... + def may_be_present( + self, + extension_type: type[T], + criticality: Criticality, + validator: MaybeExtensionValidatorCallback[T] | None, + ) -> ExtensionPolicy: ... + def require_present( + self, + extension_type: type[T], + criticality: Criticality, + validator: PresentExtensionValidatorCallback[T] | None, + ) -> ExtensionPolicy: ... + +class VerifiedClient: + @property + def subjects(self) -> list[x509.GeneralName] | None: ... + @property + def chain(self) -> list[x509.Certificate]: ... + +class ClientVerifier: + @property + def policy(self) -> Policy: ... + @property + def store(self) -> Store: ... + def verify( + self, + leaf: x509.Certificate, + intermediates: list[x509.Certificate], + ) -> VerifiedClient: ... + +class ServerVerifier: + @property + def policy(self) -> Policy: ... + @property + def store(self) -> Store: ... + def verify( + self, + leaf: x509.Certificate, + intermediates: list[x509.Certificate], + ) -> list[x509.Certificate]: ... + +class Store: + def __init__(self, certs: list[x509.Certificate]) -> None: ... + +class VerificationError(Exception): ... diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c3275bc7f2e6c1817440d1edda73c703dca86afe Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b8e38e2cee5d0840c50bc591329b005fc7dba4d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/_conditional.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e8f64480ea0bf772e143d0977182062800efabad Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/__pycache__/binding.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py new file mode 100644 index 0000000000000000000000000000000000000000..063bcf5bfcc9b90850e1d19bb9e775637b9829ca --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/_conditional.py @@ -0,0 +1,207 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + + +def cryptography_has_set_cert_cb() -> list[str]: + return [ + "SSL_CTX_set_cert_cb", + "SSL_set_cert_cb", + ] + + +def cryptography_has_ssl_st() -> list[str]: + return [ + "SSL_ST_BEFORE", + "SSL_ST_OK", + "SSL_ST_INIT", + "SSL_ST_RENEGOTIATE", + ] + + +def cryptography_has_tls_st() -> list[str]: + return [ + "TLS_ST_BEFORE", + "TLS_ST_OK", + ] + + +def cryptography_has_ssl_sigalgs() -> list[str]: + return [ + "SSL_CTX_set1_sigalgs_list", + ] + + +def cryptography_has_psk() -> list[str]: + return [ + "SSL_CTX_use_psk_identity_hint", + "SSL_CTX_set_psk_server_callback", + "SSL_CTX_set_psk_client_callback", + ] + + +def cryptography_has_psk_tlsv13() -> list[str]: + return [ + "SSL_CTX_set_psk_find_session_callback", + "SSL_CTX_set_psk_use_session_callback", + "Cryptography_SSL_SESSION_new", + "SSL_CIPHER_find", + "SSL_SESSION_set1_master_key", + "SSL_SESSION_set_cipher", + "SSL_SESSION_set_protocol_version", + ] + + +def cryptography_has_custom_ext() -> list[str]: + return [ + "SSL_CTX_add_client_custom_ext", + "SSL_CTX_add_server_custom_ext", + "SSL_extension_supported", + ] + + +def cryptography_has_tlsv13_functions() -> list[str]: + return [ + "SSL_CTX_set_ciphersuites", + ] + + +def cryptography_has_tlsv13_hs_functions() -> list[str]: + return [ + "SSL_VERIFY_POST_HANDSHAKE", + "SSL_verify_client_post_handshake", + "SSL_CTX_set_post_handshake_auth", + "SSL_set_post_handshake_auth", + "SSL_SESSION_get_max_early_data", + "SSL_write_early_data", + "SSL_read_early_data", + "SSL_CTX_set_max_early_data", + ] + + +def cryptography_has_ssl_verify_client_post_handshake() -> list[str]: + return [ + "SSL_verify_client_post_handshake", + ] + + +def cryptography_has_engine() -> list[str]: + return [ + "ENGINE_by_id", + "ENGINE_init", + "ENGINE_finish", + "ENGINE_get_default_RAND", + "ENGINE_set_default_RAND", + "ENGINE_unregister_RAND", + "ENGINE_ctrl_cmd", + "ENGINE_free", + "ENGINE_get_name", + "ENGINE_ctrl_cmd_string", + "ENGINE_load_builtin_engines", + "ENGINE_load_private_key", + "ENGINE_load_public_key", + "SSL_CTX_set_client_cert_engine", + ] + + +def cryptography_has_verified_chain() -> list[str]: + return [ + "SSL_get0_verified_chain", + ] + + +def cryptography_has_srtp() -> list[str]: + return [ + "SSL_CTX_set_tlsext_use_srtp", + "SSL_set_tlsext_use_srtp", + "SSL_get_selected_srtp_profile", + ] + + +def cryptography_has_op_no_renegotiation() -> list[str]: + return [ + "SSL_OP_NO_RENEGOTIATION", + ] + + +def cryptography_has_dtls_get_data_mtu() -> list[str]: + return [ + "DTLS_get_data_mtu", + ] + + +def cryptography_has_ssl_cookie() -> list[str]: + return [ + "SSL_OP_COOKIE_EXCHANGE", + "DTLSv1_listen", + "SSL_CTX_set_cookie_generate_cb", + "SSL_CTX_set_cookie_verify_cb", + ] + + +def cryptography_has_prime_checks() -> list[str]: + return [ + "BN_prime_checks_for_size", + ] + + +def cryptography_has_unexpected_eof_while_reading() -> list[str]: + return ["SSL_R_UNEXPECTED_EOF_WHILE_READING"] + + +def cryptography_has_ssl_op_ignore_unexpected_eof() -> list[str]: + return [ + "SSL_OP_IGNORE_UNEXPECTED_EOF", + ] + + +def cryptography_has_get_extms_support() -> list[str]: + return ["SSL_get_extms_support"] + + +def cryptography_has_ssl_get0_group_name() -> list[str]: + return ["SSL_get0_group_name"] + + +# This is a mapping of +# {condition: function-returning-names-dependent-on-that-condition} so we can +# loop over them and delete unsupported names at runtime. It will be removed +# when cffi supports #if in cdef. We use functions instead of just a dict of +# lists so we can use coverage to measure which are used. +CONDITIONAL_NAMES = { + "Cryptography_HAS_SET_CERT_CB": cryptography_has_set_cert_cb, + "Cryptography_HAS_SSL_ST": cryptography_has_ssl_st, + "Cryptography_HAS_TLS_ST": cryptography_has_tls_st, + "Cryptography_HAS_SIGALGS": cryptography_has_ssl_sigalgs, + "Cryptography_HAS_PSK": cryptography_has_psk, + "Cryptography_HAS_PSK_TLSv1_3": cryptography_has_psk_tlsv13, + "Cryptography_HAS_CUSTOM_EXT": cryptography_has_custom_ext, + "Cryptography_HAS_TLSv1_3_FUNCTIONS": cryptography_has_tlsv13_functions, + "Cryptography_HAS_TLSv1_3_HS_FUNCTIONS": ( + cryptography_has_tlsv13_hs_functions + ), + "Cryptography_HAS_SSL_VERIFY_CLIENT_POST_HANDSHAKE": ( + cryptography_has_ssl_verify_client_post_handshake + ), + "Cryptography_HAS_ENGINE": cryptography_has_engine, + "Cryptography_HAS_VERIFIED_CHAIN": cryptography_has_verified_chain, + "Cryptography_HAS_SRTP": cryptography_has_srtp, + "Cryptography_HAS_OP_NO_RENEGOTIATION": ( + cryptography_has_op_no_renegotiation + ), + "Cryptography_HAS_DTLS_GET_DATA_MTU": cryptography_has_dtls_get_data_mtu, + "Cryptography_HAS_SSL_COOKIE": cryptography_has_ssl_cookie, + "Cryptography_HAS_PRIME_CHECKS": cryptography_has_prime_checks, + "Cryptography_HAS_UNEXPECTED_EOF_WHILE_READING": ( + cryptography_has_unexpected_eof_while_reading + ), + "Cryptography_HAS_SSL_OP_IGNORE_UNEXPECTED_EOF": ( + cryptography_has_ssl_op_ignore_unexpected_eof + ), + "Cryptography_HAS_GET_EXTMS_SUPPORT": cryptography_has_get_extms_support, + "Cryptography_HAS_SSL_GET0_GROUP_NAME": ( + cryptography_has_ssl_get0_group_name + ), +} diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/binding.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/binding.py new file mode 100644 index 0000000000000000000000000000000000000000..4494c71e7e169ceec04294d7751f95b95b5c3761 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/bindings/openssl/binding.py @@ -0,0 +1,137 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import os +import sys +import threading +import types +import typing +import warnings +from collections.abc import Callable + +import cryptography +from cryptography.exceptions import InternalError +from cryptography.hazmat.bindings._rust import _openssl, openssl +from cryptography.hazmat.bindings.openssl._conditional import CONDITIONAL_NAMES +from cryptography.utils import CryptographyDeprecationWarning + + +def _openssl_assert(ok: bool) -> None: + if not ok: + errors = openssl.capture_error_stack() + + raise InternalError( + "Unknown OpenSSL error. This error is commonly encountered when " + "another library is not cleaning up the OpenSSL error stack. If " + "you are using cryptography with another library that uses " + "OpenSSL try disabling it before reporting a bug. Otherwise " + "please file an issue at https://github.com/pyca/cryptography/" + "issues with information on how to reproduce " + f"this. ({errors!r})", + errors, + ) + + +def build_conditional_library( + lib: typing.Any, + conditional_names: dict[str, Callable[[], list[str]]], +) -> typing.Any: + conditional_lib = types.ModuleType("lib") + conditional_lib._original_lib = lib # type: ignore[attr-defined] + excluded_names = set() + for condition, names_cb in conditional_names.items(): + if not getattr(lib, condition): + excluded_names.update(names_cb()) + + for attr in dir(lib): + if attr not in excluded_names: + setattr(conditional_lib, attr, getattr(lib, attr)) + + return conditional_lib + + +class Binding: + """ + OpenSSL API wrapper. + """ + + lib: typing.ClassVar[typing.Any] = None + ffi = _openssl.ffi + _lib_loaded = False + _init_lock = threading.Lock() + + def __init__(self) -> None: + self._ensure_ffi_initialized() + + @classmethod + def _ensure_ffi_initialized(cls) -> None: + with cls._init_lock: + if not cls._lib_loaded: + cls.lib = build_conditional_library( + _openssl.lib, CONDITIONAL_NAMES + ) + cls._lib_loaded = True + + @classmethod + def init_static_locks(cls) -> None: + cls._ensure_ffi_initialized() + + +def _verify_package_version(version: str) -> None: + # Occasionally we run into situations where the version of the Python + # package does not match the version of the shared object that is loaded. + # This may occur in environments where multiple versions of cryptography + # are installed and available in the python path. To avoid errors cropping + # up later this code checks that the currently imported package and the + # shared object that were loaded have the same version and raise an + # ImportError if they do not + so_package_version = _openssl.ffi.string( + _openssl.lib.CRYPTOGRAPHY_PACKAGE_VERSION + ) + if version.encode("ascii") != so_package_version: + raise ImportError( + "The version of cryptography does not match the loaded " + "shared object. This can happen if you have multiple copies of " + "cryptography installed in your Python path. Please try creating " + "a new virtual environment to resolve this issue. " + f"Loaded python version: {version}, " + f"shared object version: {so_package_version}" + ) + + _openssl_assert( + _openssl.lib.OpenSSL_version_num() == openssl.openssl_version(), + ) + + +_verify_package_version(cryptography.__version__) + +Binding.init_static_locks() + +if ( + sys.platform == "win32" + and os.environ.get("PROCESSOR_ARCHITEW6432") is not None +): + warnings.warn( + "You are using cryptography on a 32-bit Python on a 64-bit Windows " + "Operating System. Cryptography will be significantly faster if you " + "switch to using a 64-bit Python.", + UserWarning, + stacklevel=2, + ) + +if ( + not openssl.CRYPTOGRAPHY_IS_LIBRESSL + and not openssl.CRYPTOGRAPHY_IS_BORINGSSL + and not openssl.CRYPTOGRAPHY_IS_AWSLC + and not openssl.CRYPTOGRAPHY_OPENSSL_300_OR_GREATER +): + warnings.warn( + "You are using OpenSSL < 3.0. Support for OpenSSL < 3.0 is deprecated " + "and will be removed in the next release. Please upgrade to OpenSSL " + "3.0 or later.", + CryptographyDeprecationWarning, + stacklevel=2, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41d731863aa2927b7a4fb02d7e536c35c678a102 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__init__.py @@ -0,0 +1,5 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88e102e1d2567dc551d7c64bcae56e429e0271be Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41d731863aa2927b7a4fb02d7e536c35c678a102 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__init__.py @@ -0,0 +1,5 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6195143aebdf42a08adf13a6729518057740623f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48856a42e6807dc0118e138b53dd20277b1be90b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/__pycache__/algorithms.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..072a99143d6e3fd6c69e4454d61894f34e6c59b9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/decrepit/ciphers/algorithms.py @@ -0,0 +1,112 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, + _verify_key_size, +) + + +class ARC4(CipherAlgorithm): + name = "RC4" + key_sizes = frozenset([40, 56, 64, 80, 128, 160, 192, 256]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class TripleDES(BlockCipherAlgorithm): + name = "3DES" + block_size = 64 + key_sizes = frozenset([64, 128, 192]) + + def __init__(self, key: bytes): + if len(key) == 8: + key += key + key + elif len(key) == 16: + key += key[:8] + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +# Not actually supported, marker for tests +class _DES: + key_size = 64 + + +class Blowfish(BlockCipherAlgorithm): + name = "Blowfish" + block_size = 64 + key_sizes = frozenset(range(32, 449, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class CAST5(BlockCipherAlgorithm): + name = "CAST5" + block_size = 64 + key_sizes = frozenset(range(40, 129, 8)) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class SEED(BlockCipherAlgorithm): + name = "SEED" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class IDEA(BlockCipherAlgorithm): + name = "IDEA" + block_size = 64 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +# This class only allows RC2 with a 128-bit key. No support for +# effective key bits or other key sizes is provided. +class RC2(BlockCipherAlgorithm): + name = "RC2" + block_size = 64 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a1aa9d9876e534672392284cd50dc872d6723f71 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89af3e59e72cf7b315df71e1b54ba2d8f570e411 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_asymmetric.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4abb24b400efc75a11ea4bc0fdc0f7020e309871 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_cipheralgorithm.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6407b112de2091ea974f852e73e3a00ea0ffd017 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/_serialization.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a819e01193523908e339d8c8d0a8c86d8eb85f6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/cmac.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ff5b6ef13462ee0ff4ab69cfd15acbdfed805b8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/constant_time.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46a4f2845d3cfa59b477008c68f77acf104b9e03 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hashes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..066609ff95f790e2893f3991ab117ae19e338e2e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/hmac.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..878bc248f6b491501fc2dc8be8fad1d13f6175fe Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/keywrap.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fe731ac98c0aaf23e6489c1e350d5f7a1a431d4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/padding.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03e3f7a5bdc53d47cd5d35985b15a39e706cc4d1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/__pycache__/poly1305.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_asymmetric.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_asymmetric.py new file mode 100644 index 0000000000000000000000000000000000000000..ea55ffdf1a721f8fd2de8ae67de913bc47cbf55d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_asymmetric.py @@ -0,0 +1,19 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +# This exists to break an import cycle. It is normally accessible from the +# asymmetric padding module. + + +class AsymmetricPadding(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this padding (e.g. "PSS", "PKCS1"). + """ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py new file mode 100644 index 0000000000000000000000000000000000000000..305a9fd3179cd439b7a86355e6cd6c8251583532 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_cipheralgorithm.py @@ -0,0 +1,60 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils + +# This exists to break an import cycle. It is normally accessible from the +# ciphers module. + + +class CipherAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "AES", "Camellia"). + """ + + @property + @abc.abstractmethod + def key_sizes(self) -> frozenset[int]: + """ + Valid key sizes for this algorithm in bits + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The size of the key being used as an integer in bits (e.g. 128, 256). + """ + + +class BlockCipherAlgorithm(CipherAlgorithm): + key: utils.Buffer + + @property + @abc.abstractmethod + def block_size(self) -> int: + """ + The size of a block as an integer in bits (e.g. 64, 128). + """ + + +def _verify_key_size( + algorithm: CipherAlgorithm, key: utils.Buffer +) -> utils.Buffer: + # Verify that the key is instance of bytes + utils._check_byteslike("key", key) + + # Verify that the key size matches the expected key size + if len(key) * 8 not in algorithm.key_sizes: + raise ValueError( + f"Invalid key size ({len(key) * 8}) for {algorithm.name}." + ) + return key diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_serialization.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_serialization.py new file mode 100644 index 0000000000000000000000000000000000000000..e998865cdd9787e2aa2b6d87d5917b87b3ef20e9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/_serialization.py @@ -0,0 +1,168 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.hazmat.primitives.hashes import HashAlgorithm + +# This exists to break an import cycle. These classes are normally accessible +# from the serialization module. + + +class PBES(utils.Enum): + PBESv1SHA1And3KeyTripleDESCBC = "PBESv1 using SHA1 and 3-Key TripleDES" + PBESv2SHA256AndAES256CBC = "PBESv2 using SHA256 PBKDF2 and AES256 CBC" + + +class Encoding(utils.Enum): + PEM = "PEM" + DER = "DER" + OpenSSH = "OpenSSH" + Raw = "Raw" + X962 = "ANSI X9.62" + SMIME = "S/MIME" + + +class PrivateFormat(utils.Enum): + PKCS8 = "PKCS8" + TraditionalOpenSSL = "TraditionalOpenSSL" + Raw = "Raw" + OpenSSH = "OpenSSH" + PKCS12 = "PKCS12" + + def encryption_builder(self) -> KeySerializationEncryptionBuilder: + if self not in (PrivateFormat.OpenSSH, PrivateFormat.PKCS12): + raise ValueError( + "encryption_builder only supported with PrivateFormat.OpenSSH" + " and PrivateFormat.PKCS12" + ) + return KeySerializationEncryptionBuilder(self) + + +class PublicFormat(utils.Enum): + SubjectPublicKeyInfo = "X.509 subjectPublicKeyInfo with PKCS#1" + PKCS1 = "Raw PKCS#1" + OpenSSH = "OpenSSH" + Raw = "Raw" + CompressedPoint = "X9.62 Compressed Point" + UncompressedPoint = "X9.62 Uncompressed Point" + + +class ParameterFormat(utils.Enum): + PKCS3 = "PKCS3" + + +class KeySerializationEncryption(metaclass=abc.ABCMeta): + pass + + +class BestAvailableEncryption(KeySerializationEncryption): + def __init__(self, password: bytes): + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + self.password = password + + +class NoEncryption(KeySerializationEncryption): + pass + + +class KeySerializationEncryptionBuilder: + def __init__( + self, + format: PrivateFormat, + *, + _kdf_rounds: int | None = None, + _hmac_hash: HashAlgorithm | None = None, + _key_cert_algorithm: PBES | None = None, + ) -> None: + self._format = format + + self._kdf_rounds = _kdf_rounds + self._hmac_hash = _hmac_hash + self._key_cert_algorithm = _key_cert_algorithm + + def kdf_rounds(self, rounds: int) -> KeySerializationEncryptionBuilder: + if self._kdf_rounds is not None: + raise ValueError("kdf_rounds already set") + + if not isinstance(rounds, int): + raise TypeError("kdf_rounds must be an integer") + + if rounds < 1: + raise ValueError("kdf_rounds must be a positive integer") + + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def hmac_hash( + self, algorithm: HashAlgorithm + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "hmac_hash only supported with PrivateFormat.PKCS12" + ) + + if self._hmac_hash is not None: + raise ValueError("hmac_hash already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=algorithm, + _key_cert_algorithm=self._key_cert_algorithm, + ) + + def key_cert_algorithm( + self, algorithm: PBES + ) -> KeySerializationEncryptionBuilder: + if self._format is not PrivateFormat.PKCS12: + raise TypeError( + "key_cert_algorithm only supported with PrivateFormat.PKCS12" + ) + if self._key_cert_algorithm is not None: + raise ValueError("key_cert_algorithm already set") + return KeySerializationEncryptionBuilder( + self._format, + _kdf_rounds=self._kdf_rounds, + _hmac_hash=self._hmac_hash, + _key_cert_algorithm=algorithm, + ) + + def build(self, password: bytes) -> KeySerializationEncryption: + if not isinstance(password, bytes) or len(password) == 0: + raise ValueError("Password must be 1 or more bytes.") + + return _KeySerializationEncryption( + self._format, + password, + kdf_rounds=self._kdf_rounds, + hmac_hash=self._hmac_hash, + key_cert_algorithm=self._key_cert_algorithm, + ) + + +class _KeySerializationEncryption(KeySerializationEncryption): + def __init__( + self, + format: PrivateFormat, + password: bytes, + *, + kdf_rounds: int | None, + hmac_hash: HashAlgorithm | None, + key_cert_algorithm: PBES | None, + ): + self._format = format + self.password = password + + self._kdf_rounds = kdf_rounds + self._hmac_hash = hmac_hash + self._key_cert_algorithm = key_cert_algorithm diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b509336233c2fafe4185a49da5909c8bbb38dfd7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__init__.py @@ -0,0 +1,3 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6629a7b37737530bcd118a74604ea7504560c337 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..45fd91603737f69ce272189b57e20d7108cf3d0c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dh.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d618d66f9af982477af7723f20ab580639b0ec75 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/dsa.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7986eb749a0bae15e04fd2c6bdeff122dc3161c9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ec.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a88b1d2b0fd1e8e802b8dea1647f8258da1951c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed25519.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1961b930aff3a48875602f50b945392654ff7b0f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/ed448.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96f68077195abe3bed250312bf4620e07351fed2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/padding.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36753424466dcbe5deeb7daabd8591852c9cda54 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/rsa.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..84b4043df793d13b71ba09f4388eb5bdb4ae0dc0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/types.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd50ed6b4f315d21cf892cfcc0b7cfc6b422b32d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ad65c3050963172aa7c8cd5ff3c04e2536e3df2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x25519.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d853103744caf8a9bb4ac22189704ba95198f73d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/__pycache__/x448.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py new file mode 100644 index 0000000000000000000000000000000000000000..1822e99dcda89bc16a0a9a184499c097e854102d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dh.py @@ -0,0 +1,147 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization + +generate_parameters = rust_openssl.dh.generate_parameters + + +DHPrivateNumbers = rust_openssl.dh.DHPrivateNumbers +DHPublicNumbers = rust_openssl.dh.DHPublicNumbers +DHParameterNumbers = rust_openssl.dh.DHParameterNumbers + + +class DHParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DHPrivateKey: + """ + Generates and returns a DHPrivateKey. + """ + + @abc.abstractmethod + def parameter_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.ParameterFormat, + ) -> bytes: + """ + Returns the parameters serialized as bytes. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DHParameterNumbers: + """ + Returns a DHParameterNumbers. + """ + + +DHParametersWithSerialization = DHParameters +DHParameters.register(rust_openssl.dh.DHParameters) + + +class DHPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DHPublicNumbers: + """ + Returns a DHPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> DHPublicKey: + """ + Returns a copy. + """ + + +DHPublicKeyWithSerialization = DHPublicKey +DHPublicKey.register(rust_openssl.dh.DHPublicKey) + + +class DHPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DHPublicKey: + """ + The DHPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DHParameters: + """ + The DHParameters object associated with this private key. + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: DHPublicKey) -> bytes: + """ + Given peer's DHPublicKey, carry out the key exchange and + return shared key as bytes. + """ + + @abc.abstractmethod + def private_numbers(self) -> DHPrivateNumbers: + """ + Returns a DHPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> DHPrivateKey: + """ + Returns a copy. + """ + + +DHPrivateKeyWithSerialization = DHPrivateKey +DHPrivateKey.register(rust_openssl.dh.DHPrivateKey) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py new file mode 100644 index 0000000000000000000000000000000000000000..21d78ba95e036156fc20d6b096c136d0abdddda2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py @@ -0,0 +1,167 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.utils import Buffer + + +class DSAParameters(metaclass=abc.ABCMeta): + @abc.abstractmethod + def generate_private_key(self) -> DSAPrivateKey: + """ + Generates and returns a DSAPrivateKey. + """ + + @abc.abstractmethod + def parameter_numbers(self) -> DSAParameterNumbers: + """ + Returns a DSAParameterNumbers. + """ + + +DSAParametersWithNumbers = DSAParameters +DSAParameters.register(rust_openssl.dsa.DSAParameters) + + +class DSAPrivateKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def public_key(self) -> DSAPublicKey: + """ + The DSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: Buffer, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> DSAPrivateNumbers: + """ + Returns a DSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> DSAPrivateKey: + """ + Returns a copy. + """ + + +DSAPrivateKeyWithSerialization = DSAPrivateKey +DSAPrivateKey.register(rust_openssl.dsa.DSAPrivateKey) + + +class DSAPublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the prime modulus. + """ + + @abc.abstractmethod + def parameters(self) -> DSAParameters: + """ + The DSAParameters object associated with this public key. + """ + + @abc.abstractmethod + def public_numbers(self) -> DSAPublicNumbers: + """ + Returns a DSAPublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: Buffer, + data: Buffer, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> DSAPublicKey: + """ + Returns a copy. + """ + + +DSAPublicKeyWithSerialization = DSAPublicKey +DSAPublicKey.register(rust_openssl.dsa.DSAPublicKey) + +DSAPrivateNumbers = rust_openssl.dsa.DSAPrivateNumbers +DSAPublicNumbers = rust_openssl.dsa.DSAPublicNumbers +DSAParameterNumbers = rust_openssl.dsa.DSAParameterNumbers + + +def generate_parameters( + key_size: int, backend: typing.Any = None +) -> DSAParameters: + if key_size not in (1024, 2048, 3072, 4096): + raise ValueError("Key size must be 1024, 2048, 3072, or 4096 bits.") + + return rust_openssl.dsa.generate_parameters(key_size) + + +def generate_private_key( + key_size: int, backend: typing.Any = None +) -> DSAPrivateKey: + parameters = generate_parameters(key_size) + return parameters.generate_private_key() diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py new file mode 100644 index 0000000000000000000000000000000000000000..a13d9827f44afc42de62b7c21fd48fe2c99b1578 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ec.py @@ -0,0 +1,447 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat._oid import ObjectIdentifier +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class EllipticCurveOID: + SECP192R1 = ObjectIdentifier("1.2.840.10045.3.1.1") + SECP224R1 = ObjectIdentifier("1.3.132.0.33") + SECP256K1 = ObjectIdentifier("1.3.132.0.10") + SECP256R1 = ObjectIdentifier("1.2.840.10045.3.1.7") + SECP384R1 = ObjectIdentifier("1.3.132.0.34") + SECP521R1 = ObjectIdentifier("1.3.132.0.35") + BRAINPOOLP256R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.7") + BRAINPOOLP384R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.11") + BRAINPOOLP512R1 = ObjectIdentifier("1.3.36.3.3.2.8.1.1.13") + SECT163K1 = ObjectIdentifier("1.3.132.0.1") + SECT163R2 = ObjectIdentifier("1.3.132.0.15") + SECT233K1 = ObjectIdentifier("1.3.132.0.26") + SECT233R1 = ObjectIdentifier("1.3.132.0.27") + SECT283K1 = ObjectIdentifier("1.3.132.0.16") + SECT283R1 = ObjectIdentifier("1.3.132.0.17") + SECT409K1 = ObjectIdentifier("1.3.132.0.36") + SECT409R1 = ObjectIdentifier("1.3.132.0.37") + SECT571K1 = ObjectIdentifier("1.3.132.0.38") + SECT571R1 = ObjectIdentifier("1.3.132.0.39") + + +class EllipticCurve(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + The name of the curve. e.g. secp256r1. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @property + @abc.abstractmethod + def group_order(self) -> int: + """ + The order of the curve's group. + """ + + +class EllipticCurveSignatureAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm( + self, + ) -> asym_utils.Prehashed | hashes.HashAlgorithm: + """ + The digest algorithm used with this signature. + """ + + +class EllipticCurvePrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def exchange( + self, algorithm: ECDH, peer_public_key: EllipticCurvePublicKey + ) -> bytes: + """ + Performs a key exchange operation using the provided algorithm with the + provided peer's public key. + """ + + @abc.abstractmethod + def public_key(self) -> EllipticCurvePublicKey: + """ + The EllipticCurvePublicKey for this private key. + """ + + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def sign( + self, + data: utils.Buffer, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> bytes: + """ + Signs the data + """ + + @abc.abstractmethod + def private_numbers(self) -> EllipticCurvePrivateNumbers: + """ + Returns an EllipticCurvePrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> EllipticCurvePrivateKey: + """ + Returns a copy. + """ + + +EllipticCurvePrivateKeyWithSerialization = EllipticCurvePrivateKey +EllipticCurvePrivateKey.register(rust_openssl.ec.ECPrivateKey) + + +class EllipticCurvePublicKey(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def curve(self) -> EllipticCurve: + """ + The EllipticCurve that this key is on. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + Bit size of a secret scalar for the curve. + """ + + @abc.abstractmethod + def public_numbers(self) -> EllipticCurvePublicNumbers: + """ + Returns an EllipticCurvePublicNumbers. + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: utils.Buffer, + data: utils.Buffer, + signature_algorithm: EllipticCurveSignatureAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @classmethod + def from_encoded_point( + cls, curve: EllipticCurve, data: bytes + ) -> EllipticCurvePublicKey: + utils._check_bytes("data", data) + + if len(data) == 0: + raise ValueError("data must not be an empty byte string") + + if data[0] not in [0x02, 0x03, 0x04]: + raise ValueError("Unsupported elliptic curve point type") + + return rust_openssl.ec.from_public_bytes(curve, data) + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> EllipticCurvePublicKey: + """ + Returns a copy. + """ + + +EllipticCurvePublicKeyWithSerialization = EllipticCurvePublicKey +EllipticCurvePublicKey.register(rust_openssl.ec.ECPublicKey) + +EllipticCurvePrivateNumbers = rust_openssl.ec.EllipticCurvePrivateNumbers +EllipticCurvePublicNumbers = rust_openssl.ec.EllipticCurvePublicNumbers + + +class SECT571R1(EllipticCurve): + name = "sect571r1" + key_size = 570 + group_order = 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE661CE18FF55987308059B186823851EC7DD9CA1161DE93D5174D66E8382E9BB2FE84E47 # noqa: E501 + + +class SECT409R1(EllipticCurve): + name = "sect409r1" + key_size = 409 + group_order = 0x10000000000000000000000000000000000000000000000000001E2AAD6A612F33307BE5FA47C3C9E052F838164CD37D9A21173 # noqa: E501 + + +class SECT283R1(EllipticCurve): + name = "sect283r1" + key_size = 283 + group_order = 0x3FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEF90399660FC938A90165B042A7CEFADB307 # noqa: E501 + + +class SECT233R1(EllipticCurve): + name = "sect233r1" + key_size = 233 + group_order = 0x1000000000000000000000000000013E974E72F8A6922031D2603CFE0D7 + + +class SECT163R2(EllipticCurve): + name = "sect163r2" + key_size = 163 + group_order = 0x40000000000000000000292FE77E70C12A4234C33 + + +class SECT571K1(EllipticCurve): + name = "sect571k1" + key_size = 571 + group_order = 0x20000000000000000000000000000000000000000000000000000000000000000000000131850E1F19A63E4B391A8DB917F4138B630D84BE5D639381E91DEB45CFE778F637C1001 # noqa: E501 + + +class SECT409K1(EllipticCurve): + name = "sect409k1" + key_size = 409 + group_order = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE5F83B2D4EA20400EC4557D5ED3E3E7CA5B4B5C83B8E01E5FCF # noqa: E501 + + +class SECT283K1(EllipticCurve): + name = "sect283k1" + key_size = 283 + group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFE9AE2ED07577265DFF7F94451E061E163C61 # noqa: E501 + + +class SECT233K1(EllipticCurve): + name = "sect233k1" + key_size = 233 + group_order = 0x8000000000000000000000000000069D5BB915BCD46EFB1AD5F173ABDF + + +class SECT163K1(EllipticCurve): + name = "sect163k1" + key_size = 163 + group_order = 0x4000000000000000000020108A2E0CC0D99F8A5EF + + +class SECP521R1(EllipticCurve): + name = "secp521r1" + key_size = 521 + group_order = 0x1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409 # noqa: E501 + + +class SECP384R1(EllipticCurve): + name = "secp384r1" + key_size = 384 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973 # noqa: E501 + + +class SECP256R1(EllipticCurve): + name = "secp256r1" + key_size = 256 + group_order = ( + 0xFFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551 + ) + + +class SECP256K1(EllipticCurve): + name = "secp256k1" + key_size = 256 + group_order = ( + 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 + ) + + +class SECP224R1(EllipticCurve): + name = "secp224r1" + key_size = 224 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D + + +class SECP192R1(EllipticCurve): + name = "secp192r1" + key_size = 192 + group_order = 0xFFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831 + + +class BrainpoolP256R1(EllipticCurve): + name = "brainpoolP256r1" + key_size = 256 + group_order = ( + 0xA9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7 + ) + + +class BrainpoolP384R1(EllipticCurve): + name = "brainpoolP384r1" + key_size = 384 + group_order = 0x8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565 # noqa: E501 + + +class BrainpoolP512R1(EllipticCurve): + name = "brainpoolP512r1" + key_size = 512 + group_order = 0xAADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069 # noqa: E501 + + +_CURVE_TYPES: dict[str, EllipticCurve] = { + "prime192v1": SECP192R1(), + "prime256v1": SECP256R1(), + "secp192r1": SECP192R1(), + "secp224r1": SECP224R1(), + "secp256r1": SECP256R1(), + "secp384r1": SECP384R1(), + "secp521r1": SECP521R1(), + "secp256k1": SECP256K1(), + "sect163k1": SECT163K1(), + "sect233k1": SECT233K1(), + "sect283k1": SECT283K1(), + "sect409k1": SECT409K1(), + "sect571k1": SECT571K1(), + "sect163r2": SECT163R2(), + "sect233r1": SECT233R1(), + "sect283r1": SECT283R1(), + "sect409r1": SECT409R1(), + "sect571r1": SECT571R1(), + "brainpoolP256r1": BrainpoolP256R1(), + "brainpoolP384r1": BrainpoolP384R1(), + "brainpoolP512r1": BrainpoolP512R1(), +} + + +class ECDSA(EllipticCurveSignatureAlgorithm): + def __init__( + self, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + deterministic_signing: bool = False, + ): + from cryptography.hazmat.backends.openssl.backend import backend + + if ( + deterministic_signing + and not backend.ecdsa_deterministic_supported() + ): + raise UnsupportedAlgorithm( + "ECDSA with deterministic signature (RFC 6979) is not " + "supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + self._algorithm = algorithm + self._deterministic_signing = deterministic_signing + + @property + def algorithm( + self, + ) -> asym_utils.Prehashed | hashes.HashAlgorithm: + return self._algorithm + + @property + def deterministic_signing( + self, + ) -> bool: + return self._deterministic_signing + + +generate_private_key = rust_openssl.ec.generate_private_key + + +def derive_private_key( + private_value: int, + curve: EllipticCurve, + backend: typing.Any = None, +) -> EllipticCurvePrivateKey: + if not isinstance(private_value, int): + raise TypeError("private_value must be an integer type.") + + if private_value <= 0: + raise ValueError("private_value must be a positive integer.") + + return rust_openssl.ec.derive_private_key(private_value, curve) + + +class ECDH: + pass + + +_OID_TO_CURVE = { + EllipticCurveOID.SECP192R1: SECP192R1, + EllipticCurveOID.SECP224R1: SECP224R1, + EllipticCurveOID.SECP256K1: SECP256K1, + EllipticCurveOID.SECP256R1: SECP256R1, + EllipticCurveOID.SECP384R1: SECP384R1, + EllipticCurveOID.SECP521R1: SECP521R1, + EllipticCurveOID.BRAINPOOLP256R1: BrainpoolP256R1, + EllipticCurveOID.BRAINPOOLP384R1: BrainpoolP384R1, + EllipticCurveOID.BRAINPOOLP512R1: BrainpoolP512R1, + EllipticCurveOID.SECT163K1: SECT163K1, + EllipticCurveOID.SECT163R2: SECT163R2, + EllipticCurveOID.SECT233K1: SECT233K1, + EllipticCurveOID.SECT233R1: SECT233R1, + EllipticCurveOID.SECT283K1: SECT283K1, + EllipticCurveOID.SECT283R1: SECT283R1, + EllipticCurveOID.SECT409K1: SECT409K1, + EllipticCurveOID.SECT409R1: SECT409R1, + EllipticCurveOID.SECT571K1: SECT571K1, + EllipticCurveOID.SECT571R1: SECT571R1, +} + + +def get_curve_for_oid(oid: ObjectIdentifier) -> type[EllipticCurve]: + try: + return _OID_TO_CURVE[oid] + except KeyError: + raise LookupError( + "The provided object identifier has no matching elliptic " + "curve class" + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py new file mode 100644 index 0000000000000000000000000000000000000000..e576dc9f42f159bb37cc6dd791498587d731d9fa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed25519.py @@ -0,0 +1,129 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class Ed25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed25519PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed25519.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: Buffer, data: Buffer) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed25519PublicKey: + """ + Returns a copy. + """ + + +Ed25519PublicKey.register(rust_openssl.ed25519.Ed25519PublicKey) + + +class Ed25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed25519.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> Ed25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed25519_supported(): + raise UnsupportedAlgorithm( + "ed25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed25519.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed25519PublicKey: + """ + The Ed25519PublicKey derived from the private key. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def sign(self, data: Buffer) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed25519PrivateKey: + """ + Returns a copy. + """ + + +Ed25519PrivateKey.register(rust_openssl.ed25519.Ed25519PrivateKey) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py new file mode 100644 index 0000000000000000000000000000000000000000..89db20984fd6fda41b5ae26941484e681c512d31 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/ed448.py @@ -0,0 +1,131 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class Ed448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> Ed448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def verify(self, signature: Buffer, data: Buffer) -> None: + """ + Verify the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> Ed448PublicKey: + """ + Returns a copy. + """ + + +if hasattr(rust_openssl, "ed448"): + Ed448PublicKey.register(rust_openssl.ed448.Ed448PublicKey) + + +class Ed448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> Ed448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.ed448_supported(): + raise UnsupportedAlgorithm( + "ed448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM, + ) + + return rust_openssl.ed448.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> Ed448PublicKey: + """ + The Ed448PublicKey derived from the private key. + """ + + @abc.abstractmethod + def sign(self, data: Buffer) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def __copy__(self) -> Ed448PrivateKey: + """ + Returns a copy. + """ + + +if hasattr(rust_openssl, "x448"): + Ed448PrivateKey.register(rust_openssl.ed448.Ed448PrivateKey) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..5121a288fcc7ebc333285deb941630954739623d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/padding.py @@ -0,0 +1,111 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives._asymmetric import ( + AsymmetricPadding as AsymmetricPadding, +) +from cryptography.hazmat.primitives.asymmetric import rsa + + +class PKCS1v15(AsymmetricPadding): + name = "EMSA-PKCS1-v1_5" + + +class _MaxLength: + "Sentinel value for `MAX_LENGTH`." + + +class _Auto: + "Sentinel value for `AUTO`." + + +class _DigestLength: + "Sentinel value for `DIGEST_LENGTH`." + + +class PSS(AsymmetricPadding): + MAX_LENGTH = _MaxLength() + AUTO = _Auto() + DIGEST_LENGTH = _DigestLength() + name = "EMSA-PSS" + _salt_length: int | _MaxLength | _Auto | _DigestLength + + def __init__( + self, + mgf: MGF, + salt_length: int | _MaxLength | _Auto | _DigestLength, + ) -> None: + self._mgf = mgf + + if not isinstance( + salt_length, (int, _MaxLength, _Auto, _DigestLength) + ): + raise TypeError( + "salt_length must be an integer, MAX_LENGTH, " + "DIGEST_LENGTH, or AUTO" + ) + + if isinstance(salt_length, int) and salt_length < 0: + raise ValueError("salt_length must be zero or greater.") + + self._salt_length = salt_length + + @property + def mgf(self) -> MGF: + return self._mgf + + +class OAEP(AsymmetricPadding): + name = "EME-OAEP" + + def __init__( + self, + mgf: MGF, + algorithm: hashes.HashAlgorithm, + label: bytes | None, + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._mgf = mgf + self._algorithm = algorithm + self._label = label + + @property + def algorithm(self) -> hashes.HashAlgorithm: + return self._algorithm + + @property + def mgf(self) -> MGF: + return self._mgf + + +class MGF(metaclass=abc.ABCMeta): + _algorithm: hashes.HashAlgorithm + + +class MGF1(MGF): + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of hashes.HashAlgorithm.") + + self._algorithm = algorithm + + +def calculate_max_pss_salt_length( + key: rsa.RSAPrivateKey | rsa.RSAPublicKey, + hash_algorithm: hashes.HashAlgorithm, +) -> int: + if not isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + raise TypeError("key must be an RSA public or private key") + # bit length - 1 per RFC 3447 + emlen = (key.key_size + 6) // 8 + salt_length = emlen - hash_algorithm.digest_size - 2 + assert salt_length >= 0 + return salt_length diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py new file mode 100644 index 0000000000000000000000000000000000000000..f94812e186f5f8a0d8cca4693b1fd98320fddb4a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/rsa.py @@ -0,0 +1,285 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import random +import typing +from math import gcd + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization, hashes +from cryptography.hazmat.primitives._asymmetric import AsymmetricPadding +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils + + +class RSAPrivateKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def decrypt(self, ciphertext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Decrypts the provided ciphertext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_key(self) -> RSAPublicKey: + """ + The RSAPublicKey associated with this private key. + """ + + @abc.abstractmethod + def sign( + self, + data: bytes, + padding: AsymmetricPadding, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> bytes: + """ + Signs the data. + """ + + @abc.abstractmethod + def private_numbers(self) -> RSAPrivateNumbers: + """ + Returns an RSAPrivateNumbers. + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def __copy__(self) -> RSAPrivateKey: + """ + Returns a copy. + """ + + +RSAPrivateKeyWithSerialization = RSAPrivateKey +RSAPrivateKey.register(rust_openssl.rsa.RSAPrivateKey) + + +class RSAPublicKey(metaclass=abc.ABCMeta): + @abc.abstractmethod + def encrypt(self, plaintext: bytes, padding: AsymmetricPadding) -> bytes: + """ + Encrypts the given plaintext. + """ + + @property + @abc.abstractmethod + def key_size(self) -> int: + """ + The bit length of the public modulus. + """ + + @abc.abstractmethod + def public_numbers(self) -> RSAPublicNumbers: + """ + Returns an RSAPublicNumbers + """ + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + Returns the key serialized as bytes. + """ + + @abc.abstractmethod + def verify( + self, + signature: bytes, + data: bytes, + padding: AsymmetricPadding, + algorithm: asym_utils.Prehashed | hashes.HashAlgorithm, + ) -> None: + """ + Verifies the signature of the data. + """ + + @abc.abstractmethod + def recover_data_from_signature( + self, + signature: bytes, + padding: AsymmetricPadding, + algorithm: hashes.HashAlgorithm | None, + ) -> bytes: + """ + Recovers the original data from the signature. + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> RSAPublicKey: + """ + Returns a copy. + """ + + +RSAPublicKeyWithSerialization = RSAPublicKey +RSAPublicKey.register(rust_openssl.rsa.RSAPublicKey) + +RSAPrivateNumbers = rust_openssl.rsa.RSAPrivateNumbers +RSAPublicNumbers = rust_openssl.rsa.RSAPublicNumbers + + +def generate_private_key( + public_exponent: int, + key_size: int, + backend: typing.Any = None, +) -> RSAPrivateKey: + _verify_rsa_parameters(public_exponent, key_size) + return rust_openssl.rsa.generate_private_key(public_exponent, key_size) + + +def _verify_rsa_parameters(public_exponent: int, key_size: int) -> None: + if public_exponent not in (3, 65537): + raise ValueError( + "public_exponent must be either 3 (for legacy compatibility) or " + "65537. Almost everyone should choose 65537 here!" + ) + + if key_size < 1024: + raise ValueError("key_size must be at least 1024-bits.") + + +def _modinv(e: int, m: int) -> int: + """ + Modular Multiplicative Inverse. Returns x such that: (x*e) mod m == 1 + """ + x1, x2 = 1, 0 + a, b = e, m + while b > 0: + q, r = divmod(a, b) + xn = x1 - q * x2 + a, b, x1, x2 = b, r, x2, xn + return x1 % m + + +def rsa_crt_iqmp(p: int, q: int) -> int: + """ + Compute the CRT (q ** -1) % p value from RSA primes p and q. + """ + if p <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + return _modinv(q, p) + + +def rsa_crt_dmp1(private_exponent: int, p: int) -> int: + """ + Compute the CRT private_exponent % (p - 1) value from the RSA + private_exponent (d) and p. + """ + if private_exponent <= 1 or p <= 1: + raise ValueError("Values can't be <= 1") + return private_exponent % (p - 1) + + +def rsa_crt_dmq1(private_exponent: int, q: int) -> int: + """ + Compute the CRT private_exponent % (q - 1) value from the RSA + private_exponent (d) and q. + """ + if private_exponent <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + return private_exponent % (q - 1) + + +def rsa_recover_private_exponent(e: int, p: int, q: int) -> int: + """ + Compute the RSA private_exponent (d) given the public exponent (e) + and the RSA primes p and q. + + This uses the Carmichael totient function to generate the + smallest possible working value of the private exponent. + """ + # This lambda_n is the Carmichael totient function. + # The original RSA paper uses the Euler totient function + # here: phi_n = (p - 1) * (q - 1) + # Either version of the private exponent will work, but the + # one generated by the older formulation may be larger + # than necessary. (lambda_n always divides phi_n) + # + # TODO: Replace with lcm(p - 1, q - 1) once the minimum + # supported Python version is >= 3.9. + if e <= 1 or p <= 1 or q <= 1: + raise ValueError("Values can't be <= 1") + lambda_n = (p - 1) * (q - 1) // gcd(p - 1, q - 1) + return _modinv(e, lambda_n) + + +# Controls the number of iterations rsa_recover_prime_factors will perform +# to obtain the prime factors. +_MAX_RECOVERY_ATTEMPTS = 500 + + +def rsa_recover_prime_factors(n: int, e: int, d: int) -> tuple[int, int]: + """ + Compute factors p and q from the private exponent d. We assume that n has + no more than two factors. This function is adapted from code in PyCrypto. + """ + # reject invalid values early + if d <= 1 or e <= 1: + raise ValueError("d, e can't be <= 1") + if 17 != pow(17, e * d, n): + raise ValueError("n, d, e don't match") + # See 8.2.2(i) in Handbook of Applied Cryptography. + ktot = d * e - 1 + # The quantity d*e-1 is a multiple of phi(n), even, + # and can be represented as t*2^s. + t = ktot + while t % 2 == 0: + t = t // 2 + # Cycle through all multiplicative inverses in Zn. + # The algorithm is non-deterministic, but there is a 50% chance + # any candidate a leads to successful factoring. + # See "Digitalized Signatures and Public Key Functions as Intractable + # as Factorization", M. Rabin, 1979 + spotted = False + tries = 0 + while not spotted and tries < _MAX_RECOVERY_ATTEMPTS: + a = random.randint(2, n - 1) + tries += 1 + k = t + # Cycle through all values a^{t*2^i}=a^k + while k < ktot: + cand = pow(a, k, n) + # Check if a^k is a non-trivial root of unity (mod n) + if cand != 1 and cand != (n - 1) and pow(cand, 2, n) == 1: + # We have found a number such that (cand-1)(cand+1)=0 (mod n). + # Either of the terms divides n. + p = gcd(cand + 1, n) + spotted = True + break + k *= 2 + if not spotted: + raise ValueError("Unable to compute factors p and q from exponent d.") + # Found ! + q, r = divmod(n, p) + assert r == 0 + p, q = sorted((p, q), reverse=True) + return (p, q) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/types.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/types.py new file mode 100644 index 0000000000000000000000000000000000000000..1fe4eaf51d850c30ef7764d1c0bbf17533b8ad38 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/types.py @@ -0,0 +1,111 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.hazmat.primitives.asymmetric import ( + dh, + dsa, + ec, + ed448, + ed25519, + rsa, + x448, + x25519, +) + +# Every asymmetric key type +PublicKeyTypes = typing.Union[ + dh.DHPublicKey, + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +PUBLIC_KEY_TYPES = PublicKeyTypes +utils.deprecated( + PUBLIC_KEY_TYPES, + __name__, + "Use PublicKeyTypes instead", + utils.DeprecatedIn40, + name="PUBLIC_KEY_TYPES", +) +# Every asymmetric key type +PrivateKeyTypes = typing.Union[ + dh.DHPrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + x25519.X25519PrivateKey, + x448.X448PrivateKey, +] +PRIVATE_KEY_TYPES = PrivateKeyTypes +utils.deprecated( + PRIVATE_KEY_TYPES, + __name__, + "Use PrivateKeyTypes instead", + utils.DeprecatedIn40, + name="PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate public key types +CertificateIssuerPrivateKeyTypes = typing.Union[ + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, +] +CERTIFICATE_PRIVATE_KEY_TYPES = CertificateIssuerPrivateKeyTypes +utils.deprecated( + CERTIFICATE_PRIVATE_KEY_TYPES, + __name__, + "Use CertificateIssuerPrivateKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PRIVATE_KEY_TYPES", +) +# Just the key types we allow to be used for x509 signing. This mirrors +# the certificate private key types +CertificateIssuerPublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, +] +CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES = CertificateIssuerPublicKeyTypes +utils.deprecated( + CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES, + __name__, + "Use CertificateIssuerPublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_ISSUER_PUBLIC_KEY_TYPES", +) +# This type removes DHPublicKey. x448/x25519 can be a public key +# but cannot be used in signing so they are allowed here. +CertificatePublicKeyTypes = typing.Union[ + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, +] +CERTIFICATE_PUBLIC_KEY_TYPES = CertificatePublicKeyTypes +utils.deprecated( + CERTIFICATE_PUBLIC_KEY_TYPES, + __name__, + "Use CertificatePublicKeyTypes instead", + utils.DeprecatedIn40, + name="CERTIFICATE_PUBLIC_KEY_TYPES", +) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..826b9567b47bc704902eb959fd21376c8969f695 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/utils.py @@ -0,0 +1,24 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.primitives import hashes + +decode_dss_signature = asn1.decode_dss_signature +encode_dss_signature = asn1.encode_dss_signature + + +class Prehashed: + def __init__(self, algorithm: hashes.HashAlgorithm): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise TypeError("Expected instance of HashAlgorithm.") + + self._algorithm = algorithm + self._digest_size = algorithm.digest_size + + @property + def digest_size(self) -> int: + return self._digest_size diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py new file mode 100644 index 0000000000000000000000000000000000000000..a4993766b07691cf7795c0540a3e87ed4b2245e0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x25519.py @@ -0,0 +1,122 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class X25519PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X25519PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x25519.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> X25519PublicKey: + """ + Returns a copy. + """ + + +X25519PublicKey.register(rust_openssl.x25519.X25519PublicKey) + + +class X25519PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + return rust_openssl.x25519.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> X25519PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x25519_supported(): + raise UnsupportedAlgorithm( + "X25519 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x25519.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X25519PublicKey: + """ + Returns the public key associated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X25519PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + @abc.abstractmethod + def __copy__(self) -> X25519PrivateKey: + """ + Returns a copy. + """ + + +X25519PrivateKey.register(rust_openssl.x25519.X25519PrivateKey) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py new file mode 100644 index 0000000000000000000000000000000000000000..c6fd71ba5003ae757f9c0c842bb16ef0739a1fcf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/asymmetric/x448.py @@ -0,0 +1,125 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import _serialization +from cryptography.utils import Buffer + + +class X448PublicKey(metaclass=abc.ABCMeta): + @classmethod + def from_public_bytes(cls, data: bytes) -> X448PublicKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.from_public_bytes(data) + + @abc.abstractmethod + def public_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PublicFormat, + ) -> bytes: + """ + The serialized bytes of the public key. + """ + + @abc.abstractmethod + def public_bytes_raw(self) -> bytes: + """ + The raw bytes of the public key. + Equivalent to public_bytes(Raw, Raw). + """ + + @abc.abstractmethod + def __eq__(self, other: object) -> bool: + """ + Checks equality. + """ + + @abc.abstractmethod + def __copy__(self) -> X448PublicKey: + """ + Returns a copy. + """ + + +if hasattr(rust_openssl, "x448"): + X448PublicKey.register(rust_openssl.x448.X448PublicKey) + + +class X448PrivateKey(metaclass=abc.ABCMeta): + @classmethod + def generate(cls) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.generate_key() + + @classmethod + def from_private_bytes(cls, data: Buffer) -> X448PrivateKey: + from cryptography.hazmat.backends.openssl.backend import backend + + if not backend.x448_supported(): + raise UnsupportedAlgorithm( + "X448 is not supported by this version of OpenSSL.", + _Reasons.UNSUPPORTED_EXCHANGE_ALGORITHM, + ) + + return rust_openssl.x448.from_private_bytes(data) + + @abc.abstractmethod + def public_key(self) -> X448PublicKey: + """ + Returns the public key associated with this private key + """ + + @abc.abstractmethod + def private_bytes( + self, + encoding: _serialization.Encoding, + format: _serialization.PrivateFormat, + encryption_algorithm: _serialization.KeySerializationEncryption, + ) -> bytes: + """ + The serialized bytes of the private key. + """ + + @abc.abstractmethod + def private_bytes_raw(self) -> bytes: + """ + The raw bytes of the private key. + Equivalent to private_bytes(Raw, Raw, NoEncryption()). + """ + + @abc.abstractmethod + def exchange(self, peer_public_key: X448PublicKey) -> bytes: + """ + Performs a key exchange operation using the provided peer's public key. + """ + + @abc.abstractmethod + def __copy__(self) -> X448PrivateKey: + """ + Returns a copy. + """ + + +if hasattr(rust_openssl, "x448"): + X448PrivateKey.register(rust_openssl.x448.X448PrivateKey) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..10c15d0f5cb36f19ce23b3a4255e92ef27998c9b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__init__.py @@ -0,0 +1,27 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers.base import ( + AEADCipherContext, + AEADDecryptionContext, + AEADEncryptionContext, + Cipher, + CipherContext, +) + +__all__ = [ + "AEADCipherContext", + "AEADDecryptionContext", + "AEADEncryptionContext", + "BlockCipherAlgorithm", + "Cipher", + "CipherAlgorithm", + "CipherContext", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16dabcfa55f7f4ffa62e4cae1e6a11b6d64c8489 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d75ffdc7a8785bde72cc8e66cec16951fa6800c5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/aead.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4922077980f5b5806f5dcb5a2ab142f65f72afb7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/algorithms.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5bcc2e5ecf6be228f76bc697883df0c0248a55b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1f148855a3d13fcba9f82f2b38a43d56b22bda4f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/__pycache__/modes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/aead.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/aead.py new file mode 100644 index 0000000000000000000000000000000000000000..c8a582d7844ddf57670ba657b69b5ac1f20af1d1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/aead.py @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = [ + "AESCCM", + "AESGCM", + "AESGCMSIV", + "AESOCB3", + "AESSIV", + "ChaCha20Poly1305", +] + +AESGCM = rust_openssl.aead.AESGCM +ChaCha20Poly1305 = rust_openssl.aead.ChaCha20Poly1305 +AESCCM = rust_openssl.aead.AESCCM +AESSIV = rust_openssl.aead.AESSIV +AESOCB3 = rust_openssl.aead.AESOCB3 +AESGCMSIV = rust_openssl.aead.AESGCMSIV diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py new file mode 100644 index 0000000000000000000000000000000000000000..1e402c7e08dcd72c58fe37e407433693a69117c5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/algorithms.py @@ -0,0 +1,136 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + ARC4 as ARC4, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + CAST5 as CAST5, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + IDEA as IDEA, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + SEED as SEED, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + Blowfish as Blowfish, +) +from cryptography.hazmat.decrepit.ciphers.algorithms import ( + TripleDES as TripleDES, +) +from cryptography.hazmat.primitives._cipheralgorithm import _verify_key_size +from cryptography.hazmat.primitives.ciphers import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) + + +class AES(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + # 512 added to support AES-256-XTS, which uses 512-bit keys + key_sizes = frozenset([128, 192, 256, 512]) + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class AES128(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([128]) + key_size = 128 + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + +class AES256(BlockCipherAlgorithm): + name = "AES" + block_size = 128 + key_sizes = frozenset([256]) + key_size = 256 + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + +class Camellia(BlockCipherAlgorithm): + name = "camellia" + block_size = 128 + key_sizes = frozenset([128, 192, 256]) + + def __init__(self, key: utils.Buffer): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +utils.deprecated( + ARC4, + __name__, + "ARC4 has been moved to " + "cryptography.hazmat.decrepit.ciphers.algorithms.ARC4 and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", + utils.DeprecatedIn43, + name="ARC4", +) + + +utils.deprecated( + TripleDES, + __name__, + "TripleDES has been moved to " + "cryptography.hazmat.decrepit.ciphers.algorithms.TripleDES and " + "will be removed from " + "cryptography.hazmat.primitives.ciphers.algorithms in 48.0.0.", + utils.DeprecatedIn43, + name="TripleDES", +) + + +class ChaCha20(CipherAlgorithm): + name = "ChaCha20" + key_sizes = frozenset([256]) + + def __init__(self, key: utils.Buffer, nonce: utils.Buffer): + self.key = _verify_key_size(self, key) + utils._check_byteslike("nonce", nonce) + + if len(nonce) != 16: + raise ValueError("nonce must be 128-bits (16 bytes)") + + self._nonce = nonce + + @property + def nonce(self) -> utils.Buffer: + return self._nonce + + @property + def key_size(self) -> int: + return len(self.key) * 8 + + +class SM4(BlockCipherAlgorithm): + name = "SM4" + block_size = 128 + key_sizes = frozenset([128]) + + def __init__(self, key: bytes): + self.key = _verify_key_size(self, key) + + @property + def key_size(self) -> int: + return len(self.key) * 8 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/base.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/base.py new file mode 100644 index 0000000000000000000000000000000000000000..24fceea236cb0f385f4b8c8c8e2e5772d018681b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/base.py @@ -0,0 +1,146 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import typing + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives._cipheralgorithm import CipherAlgorithm +from cryptography.hazmat.primitives.ciphers import modes +from cryptography.utils import Buffer + + +class CipherContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: Buffer) -> bytes: + """ + Processes the provided bytes through the cipher and returns the results + as bytes. + """ + + @abc.abstractmethod + def update_into(self, data: Buffer, buf: Buffer) -> int: + """ + Processes the provided bytes and writes the resulting data into the + provided buffer. Returns the number of bytes written. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Returns the results of processing the final block as bytes. + """ + + @abc.abstractmethod + def reset_nonce(self, nonce: bytes) -> None: + """ + Resets the nonce for the cipher context to the provided value. + Raises an exception if it does not support reset or if the + provided nonce does not have a valid length. + """ + + +class AEADCipherContext(CipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def authenticate_additional_data(self, data: Buffer) -> None: + """ + Authenticates the provided bytes. + """ + + +class AEADDecryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @abc.abstractmethod + def finalize_with_tag(self, tag: bytes) -> bytes: + """ + Returns the results of processing the final block as bytes and allows + delayed passing of the authentication tag. + """ + + +class AEADEncryptionContext(AEADCipherContext, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> bytes: + """ + Returns tag bytes. This is only available after encryption is + finalized. + """ + + +Mode = typing.TypeVar( + "Mode", bound=typing.Optional[modes.Mode], covariant=True +) + + +class Cipher(typing.Generic[Mode]): + def __init__( + self, + algorithm: CipherAlgorithm, + mode: Mode, + backend: typing.Any = None, + ) -> None: + if not isinstance(algorithm, CipherAlgorithm): + raise TypeError("Expected interface of CipherAlgorithm.") + + if mode is not None: + # mypy needs this assert to narrow the type from our generic + # type. Maybe it won't some time in the future. + assert isinstance(mode, modes.Mode) + mode.validate_for_algorithm(algorithm) + + self.algorithm = algorithm + self.mode = mode + + @typing.overload + def encryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADEncryptionContext: ... + + @typing.overload + def encryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: ... + + def encryptor(self): + if isinstance(self.mode, modes.ModeWithAuthenticationTag): + if self.mode.tag is not None: + raise ValueError( + "Authentication tag must be None when encrypting." + ) + + return rust_openssl.ciphers.create_encryption_ctx( + self.algorithm, self.mode + ) + + @typing.overload + def decryptor( + self: Cipher[modes.ModeWithAuthenticationTag], + ) -> AEADDecryptionContext: ... + + @typing.overload + def decryptor( + self: _CIPHER_TYPE, + ) -> CipherContext: ... + + def decryptor(self): + return rust_openssl.ciphers.create_decryption_ctx( + self.algorithm, self.mode + ) + + +_CIPHER_TYPE = Cipher[ + typing.Union[ + modes.ModeWithNonce, + modes.ModeWithTweak, + modes.ECB, + modes.ModeWithInitializationVector, + None, + ] +] + +CipherContext.register(rust_openssl.ciphers.CipherContext) +AEADEncryptionContext.register(rust_openssl.ciphers.AEADEncryptionContext) +AEADDecryptionContext.register(rust_openssl.ciphers.AEADDecryptionContext) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/modes.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/modes.py new file mode 100644 index 0000000000000000000000000000000000000000..36c555c68a90e52e2eaf355ab1cf170166aeb95c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/ciphers/modes.py @@ -0,0 +1,268 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.primitives._cipheralgorithm import ( + BlockCipherAlgorithm, + CipherAlgorithm, +) +from cryptography.hazmat.primitives.ciphers import algorithms + + +class Mode(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this mode (e.g. "ECB", "CBC"). + """ + + @abc.abstractmethod + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + """ + Checks that all the necessary invariants of this (mode, algorithm) + combination are met. + """ + + +class ModeWithInitializationVector(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def initialization_vector(self) -> utils.Buffer: + """ + The value of the initialization vector for this mode as bytes. + """ + + +class ModeWithTweak(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tweak(self) -> utils.Buffer: + """ + The value of the tweak for this mode as bytes. + """ + + +class ModeWithNonce(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def nonce(self) -> utils.Buffer: + """ + The value of the nonce for this mode as bytes. + """ + + +class ModeWithAuthenticationTag(Mode, metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def tag(self) -> bytes | None: + """ + The value of the tag supplied to the constructor of this mode. + """ + + +def _check_aes_key_length(self: Mode, algorithm: CipherAlgorithm) -> None: + if algorithm.key_size > 256 and algorithm.name == "AES": + raise ValueError( + "Only 128, 192, and 256 bit keys are allowed for this AES mode" + ) + + +def _check_iv_length( + self: ModeWithInitializationVector, algorithm: BlockCipherAlgorithm +) -> None: + iv_len = len(self.initialization_vector) + if iv_len * 8 != algorithm.block_size: + raise ValueError(f"Invalid IV size ({iv_len}) for {self.name}.") + + +def _check_nonce_length( + nonce: utils.Buffer, name: str, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{name} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + if len(nonce) * 8 != algorithm.block_size: + raise ValueError(f"Invalid nonce size ({len(nonce)}) for {name}.") + + +def _check_iv_and_key_length( + self: ModeWithInitializationVector, algorithm: CipherAlgorithm +) -> None: + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + f"{self} requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + _check_aes_key_length(self, algorithm) + _check_iv_length(self, algorithm) + + +class CBC(ModeWithInitializationVector): + name = "CBC" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class XTS(ModeWithTweak): + name = "XTS" + + def __init__(self, tweak: utils.Buffer): + utils._check_byteslike("tweak", tweak) + + if len(tweak) != 16: + raise ValueError("tweak must be 128-bits (16 bytes)") + + self._tweak = tweak + + @property + def tweak(self) -> utils.Buffer: + return self._tweak + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + if isinstance(algorithm, (algorithms.AES128, algorithms.AES256)): + raise TypeError( + "The AES128 and AES256 classes do not support XTS, please use " + "the standard AES class instead." + ) + + if algorithm.key_size not in (256, 512): + raise ValueError( + "The XTS specification requires a 256-bit key for AES-128-XTS" + " and 512-bit key for AES-256-XTS" + ) + + +class ECB(Mode): + name = "ECB" + + validate_for_algorithm = _check_aes_key_length + + +class OFB(ModeWithInitializationVector): + name = "OFB" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB(ModeWithInitializationVector): + name = "CFB" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CFB8(ModeWithInitializationVector): + name = "CFB8" + + def __init__(self, initialization_vector: utils.Buffer): + utils._check_byteslike("initialization_vector", initialization_vector) + self._initialization_vector = initialization_vector + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + validate_for_algorithm = _check_iv_and_key_length + + +class CTR(ModeWithNonce): + name = "CTR" + + def __init__(self, nonce: utils.Buffer): + utils._check_byteslike("nonce", nonce) + self._nonce = nonce + + @property + def nonce(self) -> utils.Buffer: + return self._nonce + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + _check_nonce_length(self.nonce, self.name, algorithm) + + +class GCM(ModeWithInitializationVector, ModeWithAuthenticationTag): + name = "GCM" + _MAX_ENCRYPTED_BYTES = (2**39 - 256) // 8 + _MAX_AAD_BYTES = (2**64) // 8 + + def __init__( + self, + initialization_vector: utils.Buffer, + tag: bytes | None = None, + min_tag_length: int = 16, + ): + # OpenSSL 3.0.0 constrains GCM IVs to [64, 1024] bits inclusive + # This is a sane limit anyway so we'll enforce it here. + utils._check_byteslike("initialization_vector", initialization_vector) + if len(initialization_vector) < 8 or len(initialization_vector) > 128: + raise ValueError( + "initialization_vector must be between 8 and 128 bytes (64 " + "and 1024 bits)." + ) + self._initialization_vector = initialization_vector + if tag is not None: + utils._check_bytes("tag", tag) + if min_tag_length < 4: + raise ValueError("min_tag_length must be >= 4") + if len(tag) < min_tag_length: + raise ValueError( + f"Authentication tag must be {min_tag_length} bytes or " + "longer." + ) + self._tag = tag + self._min_tag_length = min_tag_length + + @property + def tag(self) -> bytes | None: + return self._tag + + @property + def initialization_vector(self) -> utils.Buffer: + return self._initialization_vector + + def validate_for_algorithm(self, algorithm: CipherAlgorithm) -> None: + _check_aes_key_length(self, algorithm) + if not isinstance(algorithm, BlockCipherAlgorithm): + raise UnsupportedAlgorithm( + "GCM requires a block cipher algorithm", + _Reasons.UNSUPPORTED_CIPHER, + ) + block_size_bytes = algorithm.block_size // 8 + if self._tag is not None and len(self._tag) > block_size_bytes: + raise ValueError( + f"Authentication tag cannot be more than {block_size_bytes} " + "bytes." + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/cmac.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/cmac.py new file mode 100644 index 0000000000000000000000000000000000000000..2c67ce2206e4c36c7ab8c4a49ba9d87f07529598 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/cmac.py @@ -0,0 +1,10 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = ["CMAC"] +CMAC = rust_openssl.cmac.CMAC diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/constant_time.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/constant_time.py new file mode 100644 index 0000000000000000000000000000000000000000..3975c7147eb92b56685423aa1c5810adcf253a23 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/constant_time.py @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import hmac + + +def bytes_eq(a: bytes, b: bytes) -> bool: + if not isinstance(a, bytes) or not isinstance(b, bytes): + raise TypeError("a and b must be bytes.") + + return hmac.compare_digest(a, b) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hashes.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hashes.py new file mode 100644 index 0000000000000000000000000000000000000000..4b55ec33dbff64bb848c8633619bbbd36362936a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hashes.py @@ -0,0 +1,246 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.utils import Buffer + +__all__ = [ + "MD5", + "SHA1", + "SHA3_224", + "SHA3_256", + "SHA3_384", + "SHA3_512", + "SHA224", + "SHA256", + "SHA384", + "SHA512", + "SHA512_224", + "SHA512_256", + "SHAKE128", + "SHAKE256", + "SM3", + "BLAKE2b", + "BLAKE2s", + "ExtendableOutputFunction", + "Hash", + "HashAlgorithm", + "HashContext", + "XOFHash", +] + + +class HashAlgorithm(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def name(self) -> str: + """ + A string naming this algorithm (e.g. "sha256", "md5"). + """ + + @property + @abc.abstractmethod + def digest_size(self) -> int: + """ + The size of the resulting digest in bytes. + """ + + @property + @abc.abstractmethod + def block_size(self) -> int | None: + """ + The internal block size of the hash function, or None if the hash + function does not use blocks internally (e.g. SHA3). + """ + + +class HashContext(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def algorithm(self) -> HashAlgorithm: + """ + A HashAlgorithm that will be used by this context. + """ + + @abc.abstractmethod + def update(self, data: Buffer) -> None: + """ + Processes the provided bytes through the hash. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalizes the hash context and returns the hash digest as bytes. + """ + + @abc.abstractmethod + def copy(self) -> HashContext: + """ + Return a HashContext that is a copy of the current context. + """ + + +Hash = rust_openssl.hashes.Hash +HashContext.register(Hash) + +XOFHash = rust_openssl.hashes.XOFHash + + +class ExtendableOutputFunction(metaclass=abc.ABCMeta): + """ + An interface for extendable output functions. + """ + + +class SHA1(HashAlgorithm): + name = "sha1" + digest_size = 20 + block_size = 64 + + +class SHA512_224(HashAlgorithm): # noqa: N801 + name = "sha512-224" + digest_size = 28 + block_size = 128 + + +class SHA512_256(HashAlgorithm): # noqa: N801 + name = "sha512-256" + digest_size = 32 + block_size = 128 + + +class SHA224(HashAlgorithm): + name = "sha224" + digest_size = 28 + block_size = 64 + + +class SHA256(HashAlgorithm): + name = "sha256" + digest_size = 32 + block_size = 64 + + +class SHA384(HashAlgorithm): + name = "sha384" + digest_size = 48 + block_size = 128 + + +class SHA512(HashAlgorithm): + name = "sha512" + digest_size = 64 + block_size = 128 + + +class SHA3_224(HashAlgorithm): # noqa: N801 + name = "sha3-224" + digest_size = 28 + block_size = None + + +class SHA3_256(HashAlgorithm): # noqa: N801 + name = "sha3-256" + digest_size = 32 + block_size = None + + +class SHA3_384(HashAlgorithm): # noqa: N801 + name = "sha3-384" + digest_size = 48 + block_size = None + + +class SHA3_512(HashAlgorithm): # noqa: N801 + name = "sha3-512" + digest_size = 64 + block_size = None + + +class SHAKE128(HashAlgorithm, ExtendableOutputFunction): + name = "shake128" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SHAKE256(HashAlgorithm, ExtendableOutputFunction): + name = "shake256" + block_size = None + + def __init__(self, digest_size: int): + if not isinstance(digest_size, int): + raise TypeError("digest_size must be an integer") + + if digest_size < 1: + raise ValueError("digest_size must be a positive integer") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class MD5(HashAlgorithm): + name = "md5" + digest_size = 16 + block_size = 64 + + +class BLAKE2b(HashAlgorithm): + name = "blake2b" + _max_digest_size = 64 + _min_digest_size = 1 + block_size = 128 + + def __init__(self, digest_size: int): + if digest_size != 64: + raise ValueError("Digest size must be 64") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class BLAKE2s(HashAlgorithm): + name = "blake2s" + block_size = 64 + _max_digest_size = 32 + _min_digest_size = 1 + + def __init__(self, digest_size: int): + if digest_size != 32: + raise ValueError("Digest size must be 32") + + self._digest_size = digest_size + + @property + def digest_size(self) -> int: + return self._digest_size + + +class SM3(HashAlgorithm): + name = "sm3" + digest_size = 32 + block_size = 64 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hmac.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hmac.py new file mode 100644 index 0000000000000000000000000000000000000000..a9442d59ab474ac680ff7253f2ca0e67d0e93c1a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/hmac.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import hashes + +__all__ = ["HMAC"] + +HMAC = rust_openssl.hmac.HMAC +hashes.HashContext.register(HMAC) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..79bb459f01ec288d67b4f7c20fd5af436fcab4a5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__init__.py @@ -0,0 +1,23 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + + +class KeyDerivationFunction(metaclass=abc.ABCMeta): + @abc.abstractmethod + def derive(self, key_material: bytes) -> bytes: + """ + Deterministically generates and returns a new key based on the existing + key material. + """ + + @abc.abstractmethod + def verify(self, key_material: bytes, expected_key: bytes) -> None: + """ + Checks whether the key generated by the key material matches the + expected derived key. Raises an exception if they do not match. + """ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ef400e23bc0628c4a46cde5577408dad3e2b991 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03c0e6a7962b69a2d93255c7e3b2622bc8a93e34 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/argon2.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8e844c938ff70e13cfc50411e5ff64351487d04d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/concatkdf.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b895db974c39e15184b2ee93a7445ecbd386353 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/hkdf.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91963a3685aeb2c36cb2d2f7dc544e4b25f7a88b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/kbkdf.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..83ba520564790ffe715ae802a8170504e627bfa2 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/pbkdf2.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..054c3d605d362cdf6136ef5fd13d44950b255f77 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/scrypt.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b818cbf8c03f21588374aac742d298d9c35f78f8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/__pycache__/x963kdf.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/argon2.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/argon2.py new file mode 100644 index 0000000000000000000000000000000000000000..405fc8dff26876404dc27279b815d4dea6508340 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/argon2.py @@ -0,0 +1,13 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +Argon2id = rust_openssl.kdf.Argon2id +KeyDerivationFunction.register(Argon2id) + +__all__ = ["Argon2id"] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..1b928415c5c11369792a3522f001a557a9d0c5cf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/concatkdf.py @@ -0,0 +1,125 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing +from collections.abc import Callable + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized, InvalidKey +from cryptography.hazmat.primitives import constant_time, hashes, hmac +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +def _int_to_u32be(n: int) -> bytes: + return n.to_bytes(length=4, byteorder="big") + + +def _common_args_checks( + algorithm: hashes.HashAlgorithm, + length: int, + otherinfo: bytes | None, +) -> None: + max_length = algorithm.digest_size * (2**32 - 1) + if length > max_length: + raise ValueError(f"Cannot derive keys larger than {max_length} bits.") + if otherinfo is not None: + utils._check_bytes("otherinfo", otherinfo) + + +def _concatkdf_derive( + key_material: utils.Buffer, + length: int, + auxfn: Callable[[], hashes.HashContext], + otherinfo: bytes, +) -> bytes: + utils._check_byteslike("key_material", key_material) + output = [b""] + outlen = 0 + counter = 1 + + while length > outlen: + h = auxfn() + h.update(_int_to_u32be(counter)) + h.update(key_material) + h.update(otherinfo) + output.append(h.finalize()) + outlen += len(output[-1]) + counter += 1 + + return b"".join(output)[:length] + + +class ConcatKDFHash(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + otherinfo: bytes | None, + backend: typing.Any = None, + ): + _common_args_checks(algorithm, length, otherinfo) + self._algorithm = algorithm + self._length = length + self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" + + self._used = False + + def _hash(self) -> hashes.Hash: + return hashes.Hash(self._algorithm) + + def derive(self, key_material: utils.Buffer) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + return _concatkdf_derive( + key_material, self._length, self._hash, self._otherinfo + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey + + +class ConcatKDFHMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + salt: bytes | None, + otherinfo: bytes | None, + backend: typing.Any = None, + ): + _common_args_checks(algorithm, length, otherinfo) + self._algorithm = algorithm + self._length = length + self._otherinfo: bytes = otherinfo if otherinfo is not None else b"" + + if algorithm.block_size is None: + raise TypeError(f"{algorithm.name} is unsupported for ConcatKDF") + + if salt is None: + salt = b"\x00" * algorithm.block_size + else: + utils._check_bytes("salt", salt) + + self._salt = salt + + self._used = False + + def _hmac(self) -> hmac.HMAC: + return hmac.HMAC(self._salt, self._algorithm) + + def derive(self, key_material: utils.Buffer) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + return _concatkdf_derive( + key_material, self._length, self._hmac, self._otherinfo + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..1e162d9dee0ddb5f2d61a4421e5984933ae63a70 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/hkdf.py @@ -0,0 +1,16 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +HKDF = rust_openssl.kdf.HKDF +HKDFExpand = rust_openssl.kdf.HKDFExpand + +KeyDerivationFunction.register(HKDF) +KeyDerivationFunction.register(HKDFExpand) + +__all__ = ["HKDF", "HKDFExpand"] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py new file mode 100644 index 0000000000000000000000000000000000000000..5b47137616797e3706e84f0ff56c0772e3925a99 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/kbkdf.py @@ -0,0 +1,303 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing +from collections.abc import Callable + +from cryptography import utils +from cryptography.exceptions import ( + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.primitives import ( + ciphers, + cmac, + constant_time, + hashes, + hmac, +) +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class Mode(utils.Enum): + CounterMode = "ctr" + + +class CounterLocation(utils.Enum): + BeforeFixed = "before_fixed" + AfterFixed = "after_fixed" + MiddleFixed = "middle_fixed" + + +class _KBKDFDeriver: + def __init__( + self, + prf: Callable, + mode: Mode, + length: int, + rlen: int, + llen: int | None, + location: CounterLocation, + break_location: int | None, + label: bytes | None, + context: bytes | None, + fixed: bytes | None, + ): + assert callable(prf) + + if not isinstance(mode, Mode): + raise TypeError("mode must be of type Mode") + + if not isinstance(location, CounterLocation): + raise TypeError("location must be of type CounterLocation") + + if break_location is None and location is CounterLocation.MiddleFixed: + raise ValueError("Please specify a break_location") + + if ( + break_location is not None + and location != CounterLocation.MiddleFixed + ): + raise ValueError( + "break_location is ignored when location is not" + " CounterLocation.MiddleFixed" + ) + + if break_location is not None and not isinstance(break_location, int): + raise TypeError("break_location must be an integer") + + if break_location is not None and break_location < 0: + raise ValueError("break_location must be a positive integer") + + if (label or context) and fixed: + raise ValueError( + "When supplying fixed data, label and context are ignored." + ) + + if rlen is None or not self._valid_byte_length(rlen): + raise ValueError("rlen must be between 1 and 4") + + if llen is None and fixed is None: + raise ValueError("Please specify an llen") + + if llen is not None and not isinstance(llen, int): + raise TypeError("llen must be an integer") + + if llen == 0: + raise ValueError("llen must be non-zero") + + if label is None: + label = b"" + + if context is None: + context = b"" + + utils._check_bytes("label", label) + utils._check_bytes("context", context) + self._prf = prf + self._mode = mode + self._length = length + self._rlen = rlen + self._llen = llen + self._location = location + self._break_location = break_location + self._label = label + self._context = context + self._used = False + self._fixed_data = fixed + + @staticmethod + def _valid_byte_length(value: int) -> bool: + if not isinstance(value, int): + raise TypeError("value must be of type int") + + value_bin = utils.int_to_bytes(1, value) + return 1 <= len(value_bin) <= 4 + + def derive( + self, key_material: utils.Buffer, prf_output_size: int + ) -> bytes: + if self._used: + raise AlreadyFinalized + + utils._check_byteslike("key_material", key_material) + self._used = True + + # inverse floor division (equivalent to ceiling) + rounds = -(-self._length // prf_output_size) + + output = [b""] + + # For counter mode, the number of iterations shall not be + # larger than 2^r-1, where r <= 32 is the binary length of the counter + # This ensures that the counter values used as an input to the + # PRF will not repeat during a particular call to the KDF function. + r_bin = utils.int_to_bytes(1, self._rlen) + if rounds > pow(2, len(r_bin) * 8) - 1: + raise ValueError("There are too many iterations.") + + fixed = self._generate_fixed_input() + + if self._location == CounterLocation.BeforeFixed: + data_before_ctr = b"" + data_after_ctr = fixed + elif self._location == CounterLocation.AfterFixed: + data_before_ctr = fixed + data_after_ctr = b"" + else: + if isinstance( + self._break_location, int + ) and self._break_location > len(fixed): + raise ValueError("break_location offset > len(fixed)") + data_before_ctr = fixed[: self._break_location] + data_after_ctr = fixed[self._break_location :] + + for i in range(1, rounds + 1): + h = self._prf(key_material) + + counter = utils.int_to_bytes(i, self._rlen) + input_data = data_before_ctr + counter + data_after_ctr + + h.update(input_data) + + output.append(h.finalize()) + + return b"".join(output)[: self._length] + + def _generate_fixed_input(self) -> bytes: + if self._fixed_data and isinstance(self._fixed_data, bytes): + return self._fixed_data + + l_val = utils.int_to_bytes(self._length * 8, self._llen) + + return b"".join([self._label, b"\x00", self._context, l_val]) + + +class KBKDFHMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + mode: Mode, + length: int, + rlen: int, + llen: int | None, + location: CounterLocation, + label: bytes | None, + context: bytes | None, + fixed: bytes | None, + backend: typing.Any = None, + *, + break_location: int | None = None, + ): + if not isinstance(algorithm, hashes.HashAlgorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported hash algorithm.", + _Reasons.UNSUPPORTED_HASH, + ) + + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.hmac_supported(algorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported hmac algorithm.", + _Reasons.UNSUPPORTED_HASH, + ) + + self._algorithm = algorithm + + self._deriver = _KBKDFDeriver( + self._prf, + mode, + length, + rlen, + llen, + location, + break_location, + label, + context, + fixed, + ) + + def _prf(self, key_material: bytes) -> hmac.HMAC: + return hmac.HMAC(key_material, self._algorithm) + + def derive(self, key_material: utils.Buffer) -> bytes: + return self._deriver.derive(key_material, self._algorithm.digest_size) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey + + +class KBKDFCMAC(KeyDerivationFunction): + def __init__( + self, + algorithm, + mode: Mode, + length: int, + rlen: int, + llen: int | None, + location: CounterLocation, + label: bytes | None, + context: bytes | None, + fixed: bytes | None, + backend: typing.Any = None, + *, + break_location: int | None = None, + ): + if not issubclass( + algorithm, ciphers.BlockCipherAlgorithm + ) or not issubclass(algorithm, ciphers.CipherAlgorithm): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported cipher algorithm.", + _Reasons.UNSUPPORTED_CIPHER, + ) + + self._algorithm = algorithm + self._cipher: ciphers.BlockCipherAlgorithm | None = None + + self._deriver = _KBKDFDeriver( + self._prf, + mode, + length, + rlen, + llen, + location, + break_location, + label, + context, + fixed, + ) + + def _prf(self, _: bytes) -> cmac.CMAC: + assert self._cipher is not None + + return cmac.CMAC(self._cipher) + + def derive(self, key_material: utils.Buffer) -> bytes: + self._cipher = self._algorithm(key_material) + + assert self._cipher is not None + + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.cmac_algorithm_supported(self._cipher): + raise UnsupportedAlgorithm( + "Algorithm supplied is not a supported cipher algorithm.", + _Reasons.UNSUPPORTED_CIPHER, + ) + + return self._deriver.derive(key_material, self._cipher.block_size // 8) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py new file mode 100644 index 0000000000000000000000000000000000000000..d539f1317556e71b5636eb2f896ec2676d458af8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/pbkdf2.py @@ -0,0 +1,62 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import ( + AlreadyFinalized, + InvalidKey, + UnsupportedAlgorithm, + _Reasons, +) +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives import constant_time, hashes +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +class PBKDF2HMAC(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + salt: bytes, + iterations: int, + backend: typing.Any = None, + ): + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.pbkdf2_hmac_supported(algorithm): + raise UnsupportedAlgorithm( + f"{algorithm.name} is not supported for PBKDF2.", + _Reasons.UNSUPPORTED_HASH, + ) + self._used = False + self._algorithm = algorithm + self._length = length + utils._check_bytes("salt", salt) + self._salt = salt + self._iterations = iterations + + def derive(self, key_material: utils.Buffer) -> bytes: + if self._used: + raise AlreadyFinalized("PBKDF2 instances can only be used once.") + self._used = True + + return rust_openssl.kdf.derive_pbkdf2_hmac( + key_material, + self._algorithm, + self._salt, + self._iterations, + self._length, + ) + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + derived_key = self.derive(key_material) + if not constant_time.bytes_eq(derived_key, expected_key): + raise InvalidKey("Keys do not match.") diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py new file mode 100644 index 0000000000000000000000000000000000000000..f791ceea371b11c0d873ff031cf3bd653cb1b2b8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/scrypt.py @@ -0,0 +1,19 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import sys + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + +# This is used by the scrypt tests to skip tests that require more memory +# than the MEM_LIMIT +_MEM_LIMIT = sys.maxsize // 2 + +Scrypt = rust_openssl.kdf.Scrypt +KeyDerivationFunction.register(Scrypt) + +__all__ = ["Scrypt"] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py new file mode 100644 index 0000000000000000000000000000000000000000..63870cdc1f5ffb6f43ae22adda0fa00fd9931862 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/kdf/x963kdf.py @@ -0,0 +1,61 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography import utils +from cryptography.exceptions import AlreadyFinalized, InvalidKey +from cryptography.hazmat.primitives import constant_time, hashes +from cryptography.hazmat.primitives.kdf import KeyDerivationFunction + + +def _int_to_u32be(n: int) -> bytes: + return n.to_bytes(length=4, byteorder="big") + + +class X963KDF(KeyDerivationFunction): + def __init__( + self, + algorithm: hashes.HashAlgorithm, + length: int, + sharedinfo: bytes | None, + backend: typing.Any = None, + ): + max_len = algorithm.digest_size * (2**32 - 1) + if length > max_len: + raise ValueError(f"Cannot derive keys larger than {max_len} bits.") + if sharedinfo is not None: + utils._check_bytes("sharedinfo", sharedinfo) + + self._algorithm = algorithm + self._length = length + self._sharedinfo = sharedinfo + self._used = False + + def derive(self, key_material: utils.Buffer) -> bytes: + if self._used: + raise AlreadyFinalized + self._used = True + utils._check_byteslike("key_material", key_material) + output = [b""] + outlen = 0 + counter = 1 + + while self._length > outlen: + h = hashes.Hash(self._algorithm) + h.update(key_material) + h.update(_int_to_u32be(counter)) + if self._sharedinfo is not None: + h.update(self._sharedinfo) + output.append(h.finalize()) + outlen += len(output[-1]) + counter += 1 + + return b"".join(output)[: self._length] + + def verify(self, key_material: bytes, expected_key: bytes) -> None: + if not constant_time.bytes_eq(self.derive(key_material), expected_key): + raise InvalidKey diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/keywrap.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/keywrap.py new file mode 100644 index 0000000000000000000000000000000000000000..b93d87d31cff5cecdf6513e81f8e506f2b2b6d3e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/keywrap.py @@ -0,0 +1,177 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives.ciphers import Cipher +from cryptography.hazmat.primitives.ciphers.algorithms import AES +from cryptography.hazmat.primitives.ciphers.modes import ECB +from cryptography.hazmat.primitives.constant_time import bytes_eq + + +def _wrap_core( + wrapping_key: bytes, + a: bytes, + r: list[bytes], +) -> bytes: + # RFC 3394 Key Wrap - 2.2.1 (index method) + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + n = len(r) + for j in range(6): + for i in range(n): + # every encryption operation is a discrete 16 byte chunk (because + # AES has a 128-bit block size) and since we're using ECB it is + # safe to reuse the encryptor for the entire operation + b = encryptor.update(a + r[i]) + a = ( + int.from_bytes(b[:8], byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] = b[-8:] + + assert encryptor.finalize() == b"" + + return a + b"".join(r) + + +def aes_key_wrap( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(key_to_wrap) < 16: + raise ValueError("The key to wrap must be at least 16 bytes") + + if len(key_to_wrap) % 8 != 0: + raise ValueError("The key to wrap must be a multiple of 8 bytes") + + a = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, a, r) + + +def _unwrap_core( + wrapping_key: bytes, + a: bytes, + r: list[bytes], +) -> tuple[bytes, list[bytes]]: + # Implement RFC 3394 Key Unwrap - 2.2.2 (index method) + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + n = len(r) + for j in reversed(range(6)): + for i in reversed(range(n)): + atr = ( + int.from_bytes(a, byteorder="big") ^ ((n * j) + i + 1) + ).to_bytes(length=8, byteorder="big") + r[i] + # every decryption operation is a discrete 16 byte chunk so + # it is safe to reuse the decryptor for the entire operation + b = decryptor.update(atr) + a = b[:8] + r[i] = b[-8:] + + assert decryptor.finalize() == b"" + return a, r + + +def aes_key_wrap_with_padding( + wrapping_key: bytes, + key_to_wrap: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + aiv = b"\xa6\x59\x59\xa6" + len(key_to_wrap).to_bytes( + length=4, byteorder="big" + ) + # pad the key to wrap if necessary + pad = (8 - (len(key_to_wrap) % 8)) % 8 + key_to_wrap = key_to_wrap + b"\x00" * pad + if len(key_to_wrap) == 8: + # RFC 5649 - 4.1 - exactly 8 octets after padding + encryptor = Cipher(AES(wrapping_key), ECB()).encryptor() + b = encryptor.update(aiv + key_to_wrap) + assert encryptor.finalize() == b"" + return b + else: + r = [key_to_wrap[i : i + 8] for i in range(0, len(key_to_wrap), 8)] + return _wrap_core(wrapping_key, aiv, r) + + +def aes_key_unwrap_with_padding( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 16: + raise InvalidUnwrap("Must be at least 16 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + if len(wrapped_key) == 16: + # RFC 5649 - 4.2 - exactly two 64-bit blocks + decryptor = Cipher(AES(wrapping_key), ECB()).decryptor() + out = decryptor.update(wrapped_key) + assert decryptor.finalize() == b"" + a = out[:8] + data = out[8:] + n = 1 + else: + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + encrypted_aiv = r.pop(0) + n = len(r) + a, r = _unwrap_core(wrapping_key, encrypted_aiv, r) + data = b"".join(r) + + # 1) Check that MSB(32,A) = A65959A6. + # 2) Check that 8*(n-1) < LSB(32,A) <= 8*n. If so, let + # MLI = LSB(32,A). + # 3) Let b = (8*n)-MLI, and then check that the rightmost b octets of + # the output data are zero. + mli = int.from_bytes(a[4:], byteorder="big") + b = (8 * n) - mli + if ( + not bytes_eq(a[:4], b"\xa6\x59\x59\xa6") + or not 8 * (n - 1) < mli <= 8 * n + or (b != 0 and not bytes_eq(data[-b:], b"\x00" * b)) + ): + raise InvalidUnwrap() + + if b == 0: + return data + else: + return data[:-b] + + +def aes_key_unwrap( + wrapping_key: bytes, + wrapped_key: bytes, + backend: typing.Any = None, +) -> bytes: + if len(wrapped_key) < 24: + raise InvalidUnwrap("Must be at least 24 bytes") + + if len(wrapped_key) % 8 != 0: + raise InvalidUnwrap("The wrapped key must be a multiple of 8 bytes") + + if len(wrapping_key) not in [16, 24, 32]: + raise ValueError("The wrapping key must be a valid AES key length") + + aiv = b"\xa6\xa6\xa6\xa6\xa6\xa6\xa6\xa6" + r = [wrapped_key[i : i + 8] for i in range(0, len(wrapped_key), 8)] + a = r.pop(0) + a, r = _unwrap_core(wrapping_key, a, r) + if not bytes_eq(a, aiv): + raise InvalidUnwrap() + + return b"".join(r) + + +class InvalidUnwrap(Exception): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/padding.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/padding.py new file mode 100644 index 0000000000000000000000000000000000000000..f9cd1f13c469beec5512d58b3de6ee1ced4362d5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/padding.py @@ -0,0 +1,69 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc + +from cryptography import utils +from cryptography.hazmat.bindings._rust import ( + ANSIX923PaddingContext, + ANSIX923UnpaddingContext, + PKCS7PaddingContext, + PKCS7UnpaddingContext, +) + + +class PaddingContext(metaclass=abc.ABCMeta): + @abc.abstractmethod + def update(self, data: utils.Buffer) -> bytes: + """ + Pads the provided bytes and returns any available data as bytes. + """ + + @abc.abstractmethod + def finalize(self) -> bytes: + """ + Finalize the padding, returns bytes. + """ + + +def _byte_padding_check(block_size: int) -> None: + if not (0 <= block_size <= 2040): + raise ValueError("block_size must be in range(0, 2041).") + + if block_size % 8 != 0: + raise ValueError("block_size must be a multiple of 8.") + + +class PKCS7: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return PKCS7PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return PKCS7UnpaddingContext(self.block_size) + + +PaddingContext.register(PKCS7PaddingContext) +PaddingContext.register(PKCS7UnpaddingContext) + + +class ANSIX923: + def __init__(self, block_size: int): + _byte_padding_check(block_size) + self.block_size = block_size + + def padder(self) -> PaddingContext: + return ANSIX923PaddingContext(self.block_size) + + def unpadder(self) -> PaddingContext: + return ANSIX923UnpaddingContext(self.block_size) + + +PaddingContext.register(ANSIX923PaddingContext) +PaddingContext.register(ANSIX923UnpaddingContext) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/poly1305.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/poly1305.py new file mode 100644 index 0000000000000000000000000000000000000000..7f5a77a576fd258a9a634ae3c3365fc3f7d4702a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/poly1305.py @@ -0,0 +1,11 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +__all__ = ["Poly1305"] + +Poly1305 = rust_openssl.poly1305.Poly1305 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..62283cc70fd6bb7d29da3dd67773761a56e86f10 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__init__.py @@ -0,0 +1,65 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat.primitives._serialization import ( + BestAvailableEncryption, + Encoding, + KeySerializationEncryption, + NoEncryption, + ParameterFormat, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) +from cryptography.hazmat.primitives.serialization.base import ( + load_der_parameters, + load_der_private_key, + load_der_public_key, + load_pem_parameters, + load_pem_private_key, + load_pem_public_key, +) +from cryptography.hazmat.primitives.serialization.ssh import ( + SSHCertificate, + SSHCertificateBuilder, + SSHCertificateType, + SSHCertPrivateKeyTypes, + SSHCertPublicKeyTypes, + SSHPrivateKeyTypes, + SSHPublicKeyTypes, + load_ssh_private_key, + load_ssh_public_identity, + load_ssh_public_key, + ssh_key_fingerprint, +) + +__all__ = [ + "BestAvailableEncryption", + "Encoding", + "KeySerializationEncryption", + "NoEncryption", + "ParameterFormat", + "PrivateFormat", + "PublicFormat", + "SSHCertPrivateKeyTypes", + "SSHCertPublicKeyTypes", + "SSHCertificate", + "SSHCertificateBuilder", + "SSHCertificateType", + "SSHPrivateKeyTypes", + "SSHPublicKeyTypes", + "_KeySerializationEncryption", + "load_der_parameters", + "load_der_private_key", + "load_der_public_key", + "load_pem_parameters", + "load_pem_private_key", + "load_pem_public_key", + "load_ssh_private_key", + "load_ssh_public_identity", + "load_ssh_public_key", + "ssh_key_fingerprint", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08aae358b41e1480a9f6fe35e81fac6a39df04e9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89bc40d61cfc834c4f0d05406946ee6aabcb2a95 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8fd385ca334eca0e9f85469c3ac59e44aeea9f37 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs12.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..374ea5bd9aa6e9f8c9def75aab10c13561a8647c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/pkcs7.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26788f95121d561c15cb9e9d748304302967dc57 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/__pycache__/ssh.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/base.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/base.py new file mode 100644 index 0000000000000000000000000000000000000000..e7c998b7f35b3e364909348f0516f51cf902ebfe --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/base.py @@ -0,0 +1,14 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from cryptography.hazmat.bindings._rust import openssl as rust_openssl + +load_pem_private_key = rust_openssl.keys.load_pem_private_key +load_der_private_key = rust_openssl.keys.load_der_private_key + +load_pem_public_key = rust_openssl.keys.load_pem_public_key +load_der_public_key = rust_openssl.keys.load_der_public_key + +load_pem_parameters = rust_openssl.dh.from_pem_parameters +load_der_parameters = rust_openssl.dh.from_der_parameters diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py new file mode 100644 index 0000000000000000000000000000000000000000..58884ff61a79e50afe2df7ed134c33d447d02998 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs12.py @@ -0,0 +1,176 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing +from collections.abc import Iterable + +from cryptography import x509 +from cryptography.hazmat.bindings._rust import pkcs12 as rust_pkcs12 +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives._serialization import PBES as PBES +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + rsa, +) +from cryptography.hazmat.primitives.asymmetric.types import PrivateKeyTypes + +__all__ = [ + "PBES", + "PKCS12Certificate", + "PKCS12KeyAndCertificates", + "PKCS12PrivateKeyTypes", + "load_key_and_certificates", + "load_pkcs12", + "serialize_java_truststore", + "serialize_key_and_certificates", +] + +PKCS12PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, +] + + +PKCS12Certificate = rust_pkcs12.PKCS12Certificate + + +class PKCS12KeyAndCertificates: + def __init__( + self, + key: PrivateKeyTypes | None, + cert: PKCS12Certificate | None, + additional_certs: list[PKCS12Certificate], + ): + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + if cert is not None and not isinstance(cert, PKCS12Certificate): + raise TypeError("cert must be a PKCS12Certificate object or None") + if not all( + isinstance(add_cert, PKCS12Certificate) + for add_cert in additional_certs + ): + raise TypeError( + "all values in additional_certs must be PKCS12Certificate" + " objects" + ) + self._key = key + self._cert = cert + self._additional_certs = additional_certs + + @property + def key(self) -> PrivateKeyTypes | None: + return self._key + + @property + def cert(self) -> PKCS12Certificate | None: + return self._cert + + @property + def additional_certs(self) -> list[PKCS12Certificate]: + return self._additional_certs + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PKCS12KeyAndCertificates): + return NotImplemented + + return ( + self.key == other.key + and self.cert == other.cert + and self.additional_certs == other.additional_certs + ) + + def __hash__(self) -> int: + return hash((self.key, self.cert, tuple(self.additional_certs))) + + def __repr__(self) -> str: + fmt = ( + "" + ) + return fmt.format(self.key, self.cert, self.additional_certs) + + +load_key_and_certificates = rust_pkcs12.load_key_and_certificates +load_pkcs12 = rust_pkcs12.load_pkcs12 + + +_PKCS12CATypes = typing.Union[ + x509.Certificate, + PKCS12Certificate, +] + + +def serialize_java_truststore( + certs: Iterable[PKCS12Certificate], + encryption_algorithm: serialization.KeySerializationEncryption, +) -> bytes: + if not certs: + raise ValueError("You must supply at least one cert") + + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) + + return rust_pkcs12.serialize_java_truststore(certs, encryption_algorithm) + + +def serialize_key_and_certificates( + name: bytes | None, + key: PKCS12PrivateKeyTypes | None, + cert: x509.Certificate | None, + cas: Iterable[_PKCS12CATypes] | None, + encryption_algorithm: serialization.KeySerializationEncryption, +) -> bytes: + if key is not None and not isinstance( + key, + ( + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ec.EllipticCurvePrivateKey, + ed25519.Ed25519PrivateKey, + ed448.Ed448PrivateKey, + ), + ): + raise TypeError( + "Key must be RSA, DSA, EllipticCurve, ED25519, or ED448" + " private key, or None." + ) + + if not isinstance( + encryption_algorithm, serialization.KeySerializationEncryption + ): + raise TypeError( + "Key encryption algorithm must be a " + "KeySerializationEncryption instance" + ) + + if key is None and cert is None and not cas: + raise ValueError("You must supply at least one of key, cert, or cas") + + return rust_pkcs12.serialize_key_and_certificates( + name, key, cert, cas, encryption_algorithm + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py new file mode 100644 index 0000000000000000000000000000000000000000..456dc5b0831c0961d715c1e2697b48e59dc2ad24 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/pkcs7.py @@ -0,0 +1,411 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import email.base64mime +import email.generator +import email.message +import email.policy +import io +import typing +from collections.abc import Iterable + +from cryptography import utils, x509 +from cryptography.exceptions import UnsupportedAlgorithm, _Reasons +from cryptography.hazmat.bindings._rust import pkcs7 as rust_pkcs7 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec, padding, rsa +from cryptography.hazmat.primitives.ciphers import ( + algorithms, +) +from cryptography.utils import _check_byteslike + +load_pem_pkcs7_certificates = rust_pkcs7.load_pem_pkcs7_certificates + +load_der_pkcs7_certificates = rust_pkcs7.load_der_pkcs7_certificates + +serialize_certificates = rust_pkcs7.serialize_certificates + +PKCS7HashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +] + +PKCS7PrivateKeyTypes = typing.Union[ + rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey +] + +ContentEncryptionAlgorithm = typing.Union[ + typing.Type[algorithms.AES128], typing.Type[algorithms.AES256] +] + + +class PKCS7Options(utils.Enum): + Text = "Add text/plain MIME type" + Binary = "Don't translate input data into canonical MIME format" + DetachedSignature = "Don't embed data in the PKCS7 structure" + NoCapabilities = "Don't embed SMIME capabilities" + NoAttributes = "Don't embed authenticatedAttributes" + NoCerts = "Don't embed signer certificate" + + +class PKCS7SignatureBuilder: + def __init__( + self, + data: utils.Buffer | None = None, + signers: list[ + tuple[ + x509.Certificate, + PKCS7PrivateKeyTypes, + PKCS7HashTypes, + padding.PSS | padding.PKCS1v15 | None, + ] + ] = [], + additional_certs: list[x509.Certificate] = [], + ): + self._data = data + self._signers = signers + self._additional_certs = additional_certs + + def set_data(self, data: utils.Buffer) -> PKCS7SignatureBuilder: + _check_byteslike("data", data) + if self._data is not None: + raise ValueError("data may only be set once") + + return PKCS7SignatureBuilder(data, self._signers) + + def add_signer( + self, + certificate: x509.Certificate, + private_key: PKCS7PrivateKeyTypes, + hash_algorithm: PKCS7HashTypes, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ) -> PKCS7SignatureBuilder: + if not isinstance( + hash_algorithm, + ( + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + ), + ): + raise TypeError( + "hash_algorithm must be one of hashes.SHA224, " + "SHA256, SHA384, or SHA512" + ) + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + if not isinstance( + private_key, (rsa.RSAPrivateKey, ec.EllipticCurvePrivateKey) + ): + raise TypeError("Only RSA & EC keys are supported at this time.") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + return PKCS7SignatureBuilder( + self._data, + [ + *self._signers, + (certificate, private_key, hash_algorithm, rsa_padding), + ], + ) + + def add_certificate( + self, certificate: x509.Certificate + ) -> PKCS7SignatureBuilder: + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + return PKCS7SignatureBuilder( + self._data, self._signers, [*self._additional_certs, certificate] + ) + + def sign( + self, + encoding: serialization.Encoding, + options: Iterable[PKCS7Options], + backend: typing.Any = None, + ) -> bytes: + if len(self._signers) == 0: + raise ValueError("Must have at least one signer") + if self._data is None: + raise ValueError("You must add data to sign") + options = list(options) + if not all(isinstance(x, PKCS7Options) for x in options): + raise ValueError("options must be from the PKCS7Options enum") + if encoding not in ( + serialization.Encoding.PEM, + serialization.Encoding.DER, + serialization.Encoding.SMIME, + ): + raise ValueError( + "Must be PEM, DER, or SMIME from the Encoding enum" + ) + + # Text is a meaningless option unless it is accompanied by + # DetachedSignature + if ( + PKCS7Options.Text in options + and PKCS7Options.DetachedSignature not in options + ): + raise ValueError( + "When passing the Text option you must also pass " + "DetachedSignature" + ) + + if PKCS7Options.Text in options and encoding in ( + serialization.Encoding.DER, + serialization.Encoding.PEM, + ): + raise ValueError( + "The Text option is only available for SMIME serialization" + ) + + # No attributes implies no capabilities so we'll error if you try to + # pass both. + if ( + PKCS7Options.NoAttributes in options + and PKCS7Options.NoCapabilities in options + ): + raise ValueError( + "NoAttributes is a superset of NoCapabilities. Do not pass " + "both values." + ) + + return rust_pkcs7.sign_and_serialize(self, encoding, options) + + +class PKCS7EnvelopeBuilder: + def __init__( + self, + *, + _data: bytes | None = None, + _recipients: list[x509.Certificate] | None = None, + _content_encryption_algorithm: ContentEncryptionAlgorithm + | None = None, + ): + from cryptography.hazmat.backends.openssl.backend import ( + backend as ossl, + ) + + if not ossl.rsa_encryption_supported(padding=padding.PKCS1v15()): + raise UnsupportedAlgorithm( + "RSA with PKCS1 v1.5 padding is not supported by this version" + " of OpenSSL.", + _Reasons.UNSUPPORTED_PADDING, + ) + self._data = _data + self._recipients = _recipients if _recipients is not None else [] + self._content_encryption_algorithm = _content_encryption_algorithm + + def set_data(self, data: bytes) -> PKCS7EnvelopeBuilder: + _check_byteslike("data", data) + if self._data is not None: + raise ValueError("data may only be set once") + + return PKCS7EnvelopeBuilder( + _data=data, + _recipients=self._recipients, + _content_encryption_algorithm=self._content_encryption_algorithm, + ) + + def add_recipient( + self, + certificate: x509.Certificate, + ) -> PKCS7EnvelopeBuilder: + if not isinstance(certificate, x509.Certificate): + raise TypeError("certificate must be a x509.Certificate") + + if not isinstance(certificate.public_key(), rsa.RSAPublicKey): + raise TypeError("Only RSA keys are supported at this time.") + + return PKCS7EnvelopeBuilder( + _data=self._data, + _recipients=[ + *self._recipients, + certificate, + ], + _content_encryption_algorithm=self._content_encryption_algorithm, + ) + + def set_content_encryption_algorithm( + self, content_encryption_algorithm: ContentEncryptionAlgorithm + ) -> PKCS7EnvelopeBuilder: + if self._content_encryption_algorithm is not None: + raise ValueError("Content encryption algo may only be set once") + if content_encryption_algorithm not in { + algorithms.AES128, + algorithms.AES256, + }: + raise TypeError("Only AES128 and AES256 are supported") + + return PKCS7EnvelopeBuilder( + _data=self._data, + _recipients=self._recipients, + _content_encryption_algorithm=content_encryption_algorithm, + ) + + def encrypt( + self, + encoding: serialization.Encoding, + options: Iterable[PKCS7Options], + ) -> bytes: + if len(self._recipients) == 0: + raise ValueError("Must have at least one recipient") + if self._data is None: + raise ValueError("You must add data to encrypt") + + # The default content encryption algorithm is AES-128, which the S/MIME + # v3.2 RFC specifies as MUST support (https://datatracker.ietf.org/doc/html/rfc5751#section-2.7) + content_encryption_algorithm = ( + self._content_encryption_algorithm or algorithms.AES128 + ) + + options = list(options) + if not all(isinstance(x, PKCS7Options) for x in options): + raise ValueError("options must be from the PKCS7Options enum") + if encoding not in ( + serialization.Encoding.PEM, + serialization.Encoding.DER, + serialization.Encoding.SMIME, + ): + raise ValueError( + "Must be PEM, DER, or SMIME from the Encoding enum" + ) + + # Only allow options that make sense for encryption + if any( + opt not in [PKCS7Options.Text, PKCS7Options.Binary] + for opt in options + ): + raise ValueError( + "Only the following options are supported for encryption: " + "Text, Binary" + ) + elif PKCS7Options.Text in options and PKCS7Options.Binary in options: + # OpenSSL accepts both options at the same time, but ignores Text. + # We fail defensively to avoid unexpected outputs. + raise ValueError( + "Cannot use Binary and Text options at the same time" + ) + + return rust_pkcs7.encrypt_and_serialize( + self, content_encryption_algorithm, encoding, options + ) + + +pkcs7_decrypt_der = rust_pkcs7.decrypt_der +pkcs7_decrypt_pem = rust_pkcs7.decrypt_pem +pkcs7_decrypt_smime = rust_pkcs7.decrypt_smime + + +def _smime_signed_encode( + data: bytes, signature: bytes, micalg: str, text_mode: bool +) -> bytes: + # This function works pretty hard to replicate what OpenSSL does + # precisely. For good and for ill. + + m = email.message.Message() + m.add_header("MIME-Version", "1.0") + m.add_header( + "Content-Type", + "multipart/signed", + protocol="application/x-pkcs7-signature", + micalg=micalg, + ) + + m.preamble = "This is an S/MIME signed message\n" + + msg_part = OpenSSLMimePart() + msg_part.set_payload(data) + if text_mode: + msg_part.add_header("Content-Type", "text/plain") + m.attach(msg_part) + + sig_part = email.message.MIMEPart() + sig_part.add_header( + "Content-Type", "application/x-pkcs7-signature", name="smime.p7s" + ) + sig_part.add_header("Content-Transfer-Encoding", "base64") + sig_part.add_header( + "Content-Disposition", "attachment", filename="smime.p7s" + ) + sig_part.set_payload( + email.base64mime.body_encode(signature, maxlinelen=65) + ) + del sig_part["MIME-Version"] + m.attach(sig_part) + + fp = io.BytesIO() + g = email.generator.BytesGenerator( + fp, + maxheaderlen=0, + mangle_from_=False, + policy=m.policy.clone(linesep="\r\n"), + ) + g.flatten(m) + return fp.getvalue() + + +def _smime_enveloped_encode(data: bytes) -> bytes: + m = email.message.Message() + m.add_header("MIME-Version", "1.0") + m.add_header("Content-Disposition", "attachment", filename="smime.p7m") + m.add_header( + "Content-Type", + "application/pkcs7-mime", + smime_type="enveloped-data", + name="smime.p7m", + ) + m.add_header("Content-Transfer-Encoding", "base64") + + m.set_payload(email.base64mime.body_encode(data, maxlinelen=65)) + + return m.as_bytes(policy=m.policy.clone(linesep="\n", max_line_length=0)) + + +def _smime_enveloped_decode(data: bytes) -> bytes: + m = email.message_from_bytes(data) + if m.get_content_type() not in { + "application/x-pkcs7-mime", + "application/pkcs7-mime", + }: + raise ValueError("Not an S/MIME enveloped message") + return bytes(m.get_payload(decode=True)) + + +def _smime_remove_text_headers(data: bytes) -> bytes: + m = email.message_from_bytes(data) + # Using get() instead of get_content_type() since it has None as default, + # where the latter has "text/plain". Both methods are case-insensitive. + content_type = m.get("content-type") + if content_type is None: + raise ValueError( + "Decrypted MIME data has no 'Content-Type' header. " + "Please remove the 'Text' option to parse it manually." + ) + if "text/plain" not in content_type: + raise ValueError( + f"Decrypted MIME data content type is '{content_type}', not " + "'text/plain'. Remove the 'Text' option to parse it manually." + ) + return bytes(m.get_payload(decode=True)) + + +class OpenSSLMimePart(email.message.MIMEPart): + # A MIMEPart subclass that replicates OpenSSL's behavior of not including + # a newline if there are no headers. + def _write_headers(self, generator) -> None: + if list(self.raw_items()): + generator._write_headers(self) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/ssh.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/ssh.py new file mode 100644 index 0000000000000000000000000000000000000000..cb10cf89d66cc575381311580dcbcc3cc91941b8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/serialization/ssh.py @@ -0,0 +1,1619 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import enum +import os +import re +import typing +import warnings +from base64 import encodebytes as _base64_encode +from dataclasses import dataclass + +from cryptography import utils +from cryptography.exceptions import UnsupportedAlgorithm +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed25519, + padding, + rsa, +) +from cryptography.hazmat.primitives.asymmetric import utils as asym_utils +from cryptography.hazmat.primitives.ciphers import ( + AEADDecryptionContext, + Cipher, + algorithms, + modes, +) +from cryptography.hazmat.primitives.serialization import ( + Encoding, + KeySerializationEncryption, + NoEncryption, + PrivateFormat, + PublicFormat, + _KeySerializationEncryption, +) + +try: + from bcrypt import kdf as _bcrypt_kdf + + _bcrypt_supported = True +except ImportError: + _bcrypt_supported = False + + def _bcrypt_kdf( + password: bytes, + salt: bytes, + desired_key_bytes: int, + rounds: int, + ignore_few_rounds: bool = False, + ) -> bytes: + raise UnsupportedAlgorithm("Need bcrypt module") + + +_SSH_ED25519 = b"ssh-ed25519" +_SSH_RSA = b"ssh-rsa" +_SSH_DSA = b"ssh-dss" +_ECDSA_NISTP256 = b"ecdsa-sha2-nistp256" +_ECDSA_NISTP384 = b"ecdsa-sha2-nistp384" +_ECDSA_NISTP521 = b"ecdsa-sha2-nistp521" +_CERT_SUFFIX = b"-cert-v01@openssh.com" + +# U2F application string suffixed pubkey +_SK_SSH_ED25519 = b"sk-ssh-ed25519@openssh.com" +_SK_SSH_ECDSA_NISTP256 = b"sk-ecdsa-sha2-nistp256@openssh.com" + +# These are not key types, only algorithms, so they cannot appear +# as a public key type +_SSH_RSA_SHA256 = b"rsa-sha2-256" +_SSH_RSA_SHA512 = b"rsa-sha2-512" + +_SSH_PUBKEY_RC = re.compile(rb"\A(\S+)[ \t]+(\S+)") +_SK_MAGIC = b"openssh-key-v1\0" +_SK_START = b"-----BEGIN OPENSSH PRIVATE KEY-----" +_SK_END = b"-----END OPENSSH PRIVATE KEY-----" +_BCRYPT = b"bcrypt" +_NONE = b"none" +_DEFAULT_CIPHER = b"aes256-ctr" +_DEFAULT_ROUNDS = 16 + +# re is only way to work on bytes-like data +_PEM_RC = re.compile(_SK_START + b"(.*?)" + _SK_END, re.DOTALL) + +# padding for max blocksize +_PADDING = memoryview(bytearray(range(1, 1 + 16))) + + +@dataclass +class _SSHCipher: + alg: type[algorithms.AES] + key_len: int + mode: type[modes.CTR] | type[modes.CBC] | type[modes.GCM] + block_len: int + iv_len: int + tag_len: int | None + is_aead: bool + + +# ciphers that are actually used in key wrapping +_SSH_CIPHERS: dict[bytes, _SSHCipher] = { + b"aes256-ctr": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CTR, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-cbc": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.CBC, + block_len=16, + iv_len=16, + tag_len=None, + is_aead=False, + ), + b"aes256-gcm@openssh.com": _SSHCipher( + alg=algorithms.AES, + key_len=32, + mode=modes.GCM, + block_len=16, + iv_len=12, + tag_len=16, + is_aead=True, + ), +} + +# map local curve name to key type +_ECDSA_KEY_TYPE = { + "secp256r1": _ECDSA_NISTP256, + "secp384r1": _ECDSA_NISTP384, + "secp521r1": _ECDSA_NISTP521, +} + + +def _get_ssh_key_type(key: SSHPrivateKeyTypes | SSHPublicKeyTypes) -> bytes: + if isinstance(key, ec.EllipticCurvePrivateKey): + key_type = _ecdsa_key_type(key.public_key()) + elif isinstance(key, ec.EllipticCurvePublicKey): + key_type = _ecdsa_key_type(key) + elif isinstance(key, (rsa.RSAPrivateKey, rsa.RSAPublicKey)): + key_type = _SSH_RSA + elif isinstance(key, (dsa.DSAPrivateKey, dsa.DSAPublicKey)): + key_type = _SSH_DSA + elif isinstance( + key, (ed25519.Ed25519PrivateKey, ed25519.Ed25519PublicKey) + ): + key_type = _SSH_ED25519 + else: + raise ValueError("Unsupported key type") + + return key_type + + +def _ecdsa_key_type(public_key: ec.EllipticCurvePublicKey) -> bytes: + """Return SSH key_type and curve_name for private key.""" + curve = public_key.curve + if curve.name not in _ECDSA_KEY_TYPE: + raise ValueError( + f"Unsupported curve for ssh private key: {curve.name!r}" + ) + return _ECDSA_KEY_TYPE[curve.name] + + +def _ssh_pem_encode( + data: utils.Buffer, + prefix: bytes = _SK_START + b"\n", + suffix: bytes = _SK_END + b"\n", +) -> bytes: + return b"".join([prefix, _base64_encode(data), suffix]) + + +def _check_block_size(data: utils.Buffer, block_len: int) -> None: + """Require data to be full blocks""" + if not data or len(data) % block_len != 0: + raise ValueError("Corrupt data: missing padding") + + +def _check_empty(data: utils.Buffer) -> None: + """All data should have been parsed.""" + if data: + raise ValueError("Corrupt data: unparsed data") + + +def _init_cipher( + ciphername: bytes, + password: bytes | None, + salt: bytes, + rounds: int, +) -> Cipher[modes.CBC | modes.CTR | modes.GCM]: + """Generate key + iv and return cipher.""" + if not password: + raise TypeError( + "Key is password-protected, but password was not provided." + ) + + ciph = _SSH_CIPHERS[ciphername] + seed = _bcrypt_kdf( + password, salt, ciph.key_len + ciph.iv_len, rounds, True + ) + return Cipher( + ciph.alg(seed[: ciph.key_len]), + ciph.mode(seed[ciph.key_len :]), + ) + + +def _get_u32(data: memoryview) -> tuple[int, memoryview]: + """Uint32""" + if len(data) < 4: + raise ValueError("Invalid data") + return int.from_bytes(data[:4], byteorder="big"), data[4:] + + +def _get_u64(data: memoryview) -> tuple[int, memoryview]: + """Uint64""" + if len(data) < 8: + raise ValueError("Invalid data") + return int.from_bytes(data[:8], byteorder="big"), data[8:] + + +def _get_sshstr(data: memoryview) -> tuple[memoryview, memoryview]: + """Bytes with u32 length prefix""" + n, data = _get_u32(data) + if n > len(data): + raise ValueError("Invalid data") + return data[:n], data[n:] + + +def _get_mpint(data: memoryview) -> tuple[int, memoryview]: + """Big integer.""" + val, data = _get_sshstr(data) + if val and val[0] > 0x7F: + raise ValueError("Invalid data") + return int.from_bytes(val, "big"), data + + +def _to_mpint(val: int) -> bytes: + """Storage format for signed bigint.""" + if val < 0: + raise ValueError("negative mpint not allowed") + if not val: + return b"" + nbytes = (val.bit_length() + 8) // 8 + return utils.int_to_bytes(val, nbytes) + + +class _FragList: + """Build recursive structure without data copy.""" + + flist: list[utils.Buffer] + + def __init__(self, init: list[utils.Buffer] | None = None) -> None: + self.flist = [] + if init: + self.flist.extend(init) + + def put_raw(self, val: utils.Buffer) -> None: + """Add plain bytes""" + self.flist.append(val) + + def put_u32(self, val: int) -> None: + """Big-endian uint32""" + self.flist.append(val.to_bytes(length=4, byteorder="big")) + + def put_u64(self, val: int) -> None: + """Big-endian uint64""" + self.flist.append(val.to_bytes(length=8, byteorder="big")) + + def put_sshstr(self, val: bytes | _FragList) -> None: + """Bytes prefixed with u32 length""" + if isinstance(val, (bytes, memoryview, bytearray)): + self.put_u32(len(val)) + self.flist.append(val) + else: + self.put_u32(val.size()) + self.flist.extend(val.flist) + + def put_mpint(self, val: int) -> None: + """Big-endian bigint prefixed with u32 length""" + self.put_sshstr(_to_mpint(val)) + + def size(self) -> int: + """Current number of bytes""" + return sum(map(len, self.flist)) + + def render(self, dstbuf: memoryview, pos: int = 0) -> int: + """Write into bytearray""" + for frag in self.flist: + flen = len(frag) + start, pos = pos, pos + flen + dstbuf[start:pos] = frag + return pos + + def tobytes(self) -> bytes: + """Return as bytes""" + buf = memoryview(bytearray(self.size())) + self.render(buf) + return buf.tobytes() + + +class _SSHFormatRSA: + """Format for RSA keys. + + Public: + mpint e, n + Private: + mpint n, e, d, iqmp, p, q + """ + + def get_public( + self, data: memoryview + ) -> tuple[tuple[int, int], memoryview]: + """RSA public fields""" + e, data = _get_mpint(data) + n, data = _get_mpint(data) + return (e, n), data + + def load_public( + self, data: memoryview + ) -> tuple[rsa.RSAPublicKey, memoryview]: + """Make RSA public key from data.""" + (e, n), data = self.get_public(data) + public_numbers = rsa.RSAPublicNumbers(e, n) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[rsa.RSAPrivateKey, memoryview]: + """Make RSA private key from data.""" + n, data = _get_mpint(data) + e, data = _get_mpint(data) + d, data = _get_mpint(data) + iqmp, data = _get_mpint(data) + p, data = _get_mpint(data) + q, data = _get_mpint(data) + + if (e, n) != pubfields: + raise ValueError("Corrupt data: rsa field mismatch") + dmp1 = rsa.rsa_crt_dmp1(d, p) + dmq1 = rsa.rsa_crt_dmq1(d, q) + public_numbers = rsa.RSAPublicNumbers(e, n) + private_numbers = rsa.RSAPrivateNumbers( + p, q, d, dmp1, dmq1, iqmp, public_numbers + ) + private_key = private_numbers.private_key( + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation + ) + return private_key, data + + def encode_public( + self, public_key: rsa.RSAPublicKey, f_pub: _FragList + ) -> None: + """Write RSA public key""" + pubn = public_key.public_numbers() + f_pub.put_mpint(pubn.e) + f_pub.put_mpint(pubn.n) + + def encode_private( + self, private_key: rsa.RSAPrivateKey, f_priv: _FragList + ) -> None: + """Write RSA private key""" + private_numbers = private_key.private_numbers() + public_numbers = private_numbers.public_numbers + + f_priv.put_mpint(public_numbers.n) + f_priv.put_mpint(public_numbers.e) + + f_priv.put_mpint(private_numbers.d) + f_priv.put_mpint(private_numbers.iqmp) + f_priv.put_mpint(private_numbers.p) + f_priv.put_mpint(private_numbers.q) + + +class _SSHFormatDSA: + """Format for DSA keys. + + Public: + mpint p, q, g, y + Private: + mpint p, q, g, y, x + """ + + def get_public(self, data: memoryview) -> tuple[tuple, memoryview]: + """DSA public fields""" + p, data = _get_mpint(data) + q, data = _get_mpint(data) + g, data = _get_mpint(data) + y, data = _get_mpint(data) + return (p, q, g, y), data + + def load_public( + self, data: memoryview + ) -> tuple[dsa.DSAPublicKey, memoryview]: + """Make DSA public key from data.""" + (p, q, g, y), data = self.get_public(data) + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + public_key = public_numbers.public_key() + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[dsa.DSAPrivateKey, memoryview]: + """Make DSA private key from data.""" + (p, q, g, y), data = self.get_public(data) + x, data = _get_mpint(data) + + if (p, q, g, y) != pubfields: + raise ValueError("Corrupt data: dsa field mismatch") + parameter_numbers = dsa.DSAParameterNumbers(p, q, g) + public_numbers = dsa.DSAPublicNumbers(y, parameter_numbers) + self._validate(public_numbers) + private_numbers = dsa.DSAPrivateNumbers(x, public_numbers) + private_key = private_numbers.private_key() + return private_key, data + + def encode_public( + self, public_key: dsa.DSAPublicKey, f_pub: _FragList + ) -> None: + """Write DSA public key""" + public_numbers = public_key.public_numbers() + parameter_numbers = public_numbers.parameter_numbers + self._validate(public_numbers) + + f_pub.put_mpint(parameter_numbers.p) + f_pub.put_mpint(parameter_numbers.q) + f_pub.put_mpint(parameter_numbers.g) + f_pub.put_mpint(public_numbers.y) + + def encode_private( + self, private_key: dsa.DSAPrivateKey, f_priv: _FragList + ) -> None: + """Write DSA private key""" + self.encode_public(private_key.public_key(), f_priv) + f_priv.put_mpint(private_key.private_numbers().x) + + def _validate(self, public_numbers: dsa.DSAPublicNumbers) -> None: + parameter_numbers = public_numbers.parameter_numbers + if parameter_numbers.p.bit_length() != 1024: + raise ValueError("SSH supports only 1024 bit DSA keys") + + +class _SSHFormatECDSA: + """Format for ECDSA keys. + + Public: + str curve + bytes point + Private: + str curve + bytes point + mpint secret + """ + + def __init__(self, ssh_curve_name: bytes, curve: ec.EllipticCurve): + self.ssh_curve_name = ssh_curve_name + self.curve = curve + + def get_public( + self, data: memoryview + ) -> tuple[tuple[memoryview, memoryview], memoryview]: + """ECDSA public fields""" + curve, data = _get_sshstr(data) + point, data = _get_sshstr(data) + if curve != self.ssh_curve_name: + raise ValueError("Curve name mismatch") + if point[0] != 4: + raise NotImplementedError("Need uncompressed point") + return (curve, point), data + + def load_public( + self, data: memoryview + ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: + """Make ECDSA public key from data.""" + (_, point), data = self.get_public(data) + public_key = ec.EllipticCurvePublicKey.from_encoded_point( + self.curve, point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[ec.EllipticCurvePrivateKey, memoryview]: + """Make ECDSA private key from data.""" + (curve_name, point), data = self.get_public(data) + secret, data = _get_mpint(data) + + if (curve_name, point) != pubfields: + raise ValueError("Corrupt data: ecdsa field mismatch") + private_key = ec.derive_private_key(secret, self.curve) + return private_key, data + + def encode_public( + self, public_key: ec.EllipticCurvePublicKey, f_pub: _FragList + ) -> None: + """Write ECDSA public key""" + point = public_key.public_bytes( + Encoding.X962, PublicFormat.UncompressedPoint + ) + f_pub.put_sshstr(self.ssh_curve_name) + f_pub.put_sshstr(point) + + def encode_private( + self, private_key: ec.EllipticCurvePrivateKey, f_priv: _FragList + ) -> None: + """Write ECDSA private key""" + public_key = private_key.public_key() + private_numbers = private_key.private_numbers() + + self.encode_public(public_key, f_priv) + f_priv.put_mpint(private_numbers.private_value) + + +class _SSHFormatEd25519: + """Format for Ed25519 keys. + + Public: + bytes point + Private: + bytes point + bytes secret_and_point + """ + + def get_public( + self, data: memoryview + ) -> tuple[tuple[memoryview], memoryview]: + """Ed25519 public fields""" + point, data = _get_sshstr(data) + return (point,), data + + def load_public( + self, data: memoryview + ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: + """Make Ed25519 public key from data.""" + (point,), data = self.get_public(data) + public_key = ed25519.Ed25519PublicKey.from_public_bytes( + point.tobytes() + ) + return public_key, data + + def load_private( + self, data: memoryview, pubfields, unsafe_skip_rsa_key_validation: bool + ) -> tuple[ed25519.Ed25519PrivateKey, memoryview]: + """Make Ed25519 private key from data.""" + (point,), data = self.get_public(data) + keypair, data = _get_sshstr(data) + + secret = keypair[:32] + point2 = keypair[32:] + if point != point2 or (point,) != pubfields: + raise ValueError("Corrupt data: ed25519 field mismatch") + private_key = ed25519.Ed25519PrivateKey.from_private_bytes(secret) + return private_key, data + + def encode_public( + self, public_key: ed25519.Ed25519PublicKey, f_pub: _FragList + ) -> None: + """Write Ed25519 public key""" + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_pub.put_sshstr(raw_public_key) + + def encode_private( + self, private_key: ed25519.Ed25519PrivateKey, f_priv: _FragList + ) -> None: + """Write Ed25519 private key""" + public_key = private_key.public_key() + raw_private_key = private_key.private_bytes( + Encoding.Raw, PrivateFormat.Raw, NoEncryption() + ) + raw_public_key = public_key.public_bytes( + Encoding.Raw, PublicFormat.Raw + ) + f_keypair = _FragList([raw_private_key, raw_public_key]) + + self.encode_public(public_key, f_priv) + f_priv.put_sshstr(f_keypair) + + +def load_application(data) -> tuple[memoryview, memoryview]: + """ + U2F application strings + """ + application, data = _get_sshstr(data) + if not application.tobytes().startswith(b"ssh:"): + raise ValueError( + "U2F application string does not start with b'ssh:' " + f"({application})" + ) + return application, data + + +class _SSHFormatSKEd25519: + """ + The format of a sk-ssh-ed25519@openssh.com public key is: + + string "sk-ssh-ed25519@openssh.com" + string public key + string application (user-specified, but typically "ssh:") + """ + + def load_public( + self, data: memoryview + ) -> tuple[ed25519.Ed25519PublicKey, memoryview]: + """Make Ed25519 public key from data.""" + public_key, data = _lookup_kformat(_SSH_ED25519).load_public(data) + _, data = load_application(data) + return public_key, data + + def get_public(self, data: memoryview) -> typing.NoReturn: + # Confusingly `get_public` is an entry point used by private key + # loading. + raise UnsupportedAlgorithm( + "sk-ssh-ed25519 private keys cannot be loaded" + ) + + +class _SSHFormatSKECDSA: + """ + The format of a sk-ecdsa-sha2-nistp256@openssh.com public key is: + + string "sk-ecdsa-sha2-nistp256@openssh.com" + string curve name + ec_point Q + string application (user-specified, but typically "ssh:") + """ + + def load_public( + self, data: memoryview + ) -> tuple[ec.EllipticCurvePublicKey, memoryview]: + """Make ECDSA public key from data.""" + public_key, data = _lookup_kformat(_ECDSA_NISTP256).load_public(data) + _, data = load_application(data) + return public_key, data + + def get_public(self, data: memoryview) -> typing.NoReturn: + # Confusingly `get_public` is an entry point used by private key + # loading. + raise UnsupportedAlgorithm( + "sk-ecdsa-sha2-nistp256 private keys cannot be loaded" + ) + + +_KEY_FORMATS = { + _SSH_RSA: _SSHFormatRSA(), + _SSH_DSA: _SSHFormatDSA(), + _SSH_ED25519: _SSHFormatEd25519(), + _ECDSA_NISTP256: _SSHFormatECDSA(b"nistp256", ec.SECP256R1()), + _ECDSA_NISTP384: _SSHFormatECDSA(b"nistp384", ec.SECP384R1()), + _ECDSA_NISTP521: _SSHFormatECDSA(b"nistp521", ec.SECP521R1()), + _SK_SSH_ED25519: _SSHFormatSKEd25519(), + _SK_SSH_ECDSA_NISTP256: _SSHFormatSKECDSA(), +} + + +def _lookup_kformat(key_type: utils.Buffer): + """Return valid format or throw error""" + if not isinstance(key_type, bytes): + key_type = memoryview(key_type).tobytes() + if key_type in _KEY_FORMATS: + return _KEY_FORMATS[key_type] + raise UnsupportedAlgorithm(f"Unsupported key type: {key_type!r}") + + +SSHPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + dsa.DSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +def load_ssh_private_key( + data: utils.Buffer, + password: bytes | None, + backend: typing.Any = None, + *, + unsafe_skip_rsa_key_validation: bool = False, +) -> SSHPrivateKeyTypes: + """Load private key from OpenSSH custom encoding.""" + utils._check_byteslike("data", data) + if password is not None: + utils._check_bytes("password", password) + + m = _PEM_RC.search(data) + if not m: + raise ValueError("Not OpenSSH private key format") + p1 = m.start(1) + p2 = m.end(1) + data = binascii.a2b_base64(memoryview(data)[p1:p2]) + if not data.startswith(_SK_MAGIC): + raise ValueError("Not OpenSSH private key format") + data = memoryview(data)[len(_SK_MAGIC) :] + + # parse header + ciphername, data = _get_sshstr(data) + kdfname, data = _get_sshstr(data) + kdfoptions, data = _get_sshstr(data) + nkeys, data = _get_u32(data) + if nkeys != 1: + raise ValueError("Only one key supported") + + # load public key data + pubdata, data = _get_sshstr(data) + pub_key_type, pubdata = _get_sshstr(pubdata) + kformat = _lookup_kformat(pub_key_type) + pubfields, pubdata = kformat.get_public(pubdata) + _check_empty(pubdata) + + if ciphername != _NONE or kdfname != _NONE: + ciphername_bytes = ciphername.tobytes() + if ciphername_bytes not in _SSH_CIPHERS: + raise UnsupportedAlgorithm( + f"Unsupported cipher: {ciphername_bytes!r}" + ) + if kdfname != _BCRYPT: + raise UnsupportedAlgorithm(f"Unsupported KDF: {kdfname!r}") + blklen = _SSH_CIPHERS[ciphername_bytes].block_len + tag_len = _SSH_CIPHERS[ciphername_bytes].tag_len + # load secret data + edata, data = _get_sshstr(data) + # see https://bugzilla.mindrot.org/show_bug.cgi?id=3553 for + # information about how OpenSSH handles AEAD tags + if _SSH_CIPHERS[ciphername_bytes].is_aead: + tag = bytes(data) + if len(tag) != tag_len: + raise ValueError("Corrupt data: invalid tag length for cipher") + else: + _check_empty(data) + _check_block_size(edata, blklen) + salt, kbuf = _get_sshstr(kdfoptions) + rounds, kbuf = _get_u32(kbuf) + _check_empty(kbuf) + ciph = _init_cipher(ciphername_bytes, password, salt.tobytes(), rounds) + dec = ciph.decryptor() + edata = memoryview(dec.update(edata)) + if _SSH_CIPHERS[ciphername_bytes].is_aead: + assert isinstance(dec, AEADDecryptionContext) + _check_empty(dec.finalize_with_tag(tag)) + else: + # _check_block_size requires data to be a full block so there + # should be no output from finalize + _check_empty(dec.finalize()) + else: + if password: + raise TypeError( + "Password was given but private key is not encrypted." + ) + # load secret data + edata, data = _get_sshstr(data) + _check_empty(data) + blklen = 8 + _check_block_size(edata, blklen) + ck1, edata = _get_u32(edata) + ck2, edata = _get_u32(edata) + if ck1 != ck2: + raise ValueError("Corrupt data: broken checksum") + + # load per-key struct + key_type, edata = _get_sshstr(edata) + if key_type != pub_key_type: + raise ValueError("Corrupt data: key type mismatch") + private_key, edata = kformat.load_private( + edata, + pubfields, + unsafe_skip_rsa_key_validation=unsafe_skip_rsa_key_validation, + ) + # We don't use the comment + _, edata = _get_sshstr(edata) + + # yes, SSH does padding check *after* all other parsing is done. + # need to follow as it writes zero-byte padding too. + if edata != _PADDING[: len(edata)]: + raise ValueError("Corrupt data: invalid padding") + + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + + return private_key + + +def _serialize_ssh_private_key( + private_key: SSHPrivateKeyTypes, + password: bytes, + encryption_algorithm: KeySerializationEncryption, +) -> bytes: + """Serialize private key with OpenSSH custom encoding.""" + utils._check_bytes("password", password) + if isinstance(private_key, dsa.DSAPrivateKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + + key_type = _get_ssh_key_type(private_key) + kformat = _lookup_kformat(key_type) + + # setup parameters + f_kdfoptions = _FragList() + if password: + ciphername = _DEFAULT_CIPHER + blklen = _SSH_CIPHERS[ciphername].block_len + kdfname = _BCRYPT + rounds = _DEFAULT_ROUNDS + if ( + isinstance(encryption_algorithm, _KeySerializationEncryption) + and encryption_algorithm._kdf_rounds is not None + ): + rounds = encryption_algorithm._kdf_rounds + salt = os.urandom(16) + f_kdfoptions.put_sshstr(salt) + f_kdfoptions.put_u32(rounds) + ciph = _init_cipher(ciphername, password, salt, rounds) + else: + ciphername = kdfname = _NONE + blklen = 8 + ciph = None + nkeys = 1 + checkval = os.urandom(4) + comment = b"" + + # encode public and private parts together + f_public_key = _FragList() + f_public_key.put_sshstr(key_type) + kformat.encode_public(private_key.public_key(), f_public_key) + + f_secrets = _FragList([checkval, checkval]) + f_secrets.put_sshstr(key_type) + kformat.encode_private(private_key, f_secrets) + f_secrets.put_sshstr(comment) + f_secrets.put_raw(_PADDING[: blklen - (f_secrets.size() % blklen)]) + + # top-level structure + f_main = _FragList() + f_main.put_raw(_SK_MAGIC) + f_main.put_sshstr(ciphername) + f_main.put_sshstr(kdfname) + f_main.put_sshstr(f_kdfoptions) + f_main.put_u32(nkeys) + f_main.put_sshstr(f_public_key) + f_main.put_sshstr(f_secrets) + + # copy result info bytearray + slen = f_secrets.size() + mlen = f_main.size() + buf = memoryview(bytearray(mlen + blklen)) + f_main.render(buf) + ofs = mlen - slen + + # encrypt in-place + if ciph is not None: + ciph.encryptor().update_into(buf[ofs:mlen], buf[ofs:]) + + return _ssh_pem_encode(buf[:mlen]) + + +SSHPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + dsa.DSAPublicKey, + ed25519.Ed25519PublicKey, +] + +SSHCertPublicKeyTypes = typing.Union[ + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, +] + + +class SSHCertificateType(enum.Enum): + USER = 1 + HOST = 2 + + +class SSHCertificate: + def __init__( + self, + _nonce: memoryview, + _public_key: SSHPublicKeyTypes, + _serial: int, + _cctype: int, + _key_id: memoryview, + _valid_principals: list[bytes], + _valid_after: int, + _valid_before: int, + _critical_options: dict[bytes, bytes], + _extensions: dict[bytes, bytes], + _sig_type: memoryview, + _sig_key: memoryview, + _inner_sig_type: memoryview, + _signature: memoryview, + _tbs_cert_body: memoryview, + _cert_key_type: bytes, + _cert_body: memoryview, + ): + self._nonce = _nonce + self._public_key = _public_key + self._serial = _serial + try: + self._type = SSHCertificateType(_cctype) + except ValueError: + raise ValueError("Invalid certificate type") + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_after = _valid_after + self._valid_before = _valid_before + self._critical_options = _critical_options + self._extensions = _extensions + self._sig_type = _sig_type + self._sig_key = _sig_key + self._inner_sig_type = _inner_sig_type + self._signature = _signature + self._cert_key_type = _cert_key_type + self._cert_body = _cert_body + self._tbs_cert_body = _tbs_cert_body + + @property + def nonce(self) -> bytes: + return bytes(self._nonce) + + def public_key(self) -> SSHCertPublicKeyTypes: + # make mypy happy until we remove DSA support entirely and + # the underlying union won't have a disallowed type + return typing.cast(SSHCertPublicKeyTypes, self._public_key) + + @property + def serial(self) -> int: + return self._serial + + @property + def type(self) -> SSHCertificateType: + return self._type + + @property + def key_id(self) -> bytes: + return bytes(self._key_id) + + @property + def valid_principals(self) -> list[bytes]: + return self._valid_principals + + @property + def valid_before(self) -> int: + return self._valid_before + + @property + def valid_after(self) -> int: + return self._valid_after + + @property + def critical_options(self) -> dict[bytes, bytes]: + return self._critical_options + + @property + def extensions(self) -> dict[bytes, bytes]: + return self._extensions + + def signature_key(self) -> SSHCertPublicKeyTypes: + sigformat = _lookup_kformat(self._sig_type) + signature_key, sigkey_rest = sigformat.load_public(self._sig_key) + _check_empty(sigkey_rest) + return signature_key + + def public_bytes(self) -> bytes: + return ( + bytes(self._cert_key_type) + + b" " + + binascii.b2a_base64(bytes(self._cert_body), newline=False) + ) + + def verify_cert_signature(self) -> None: + signature_key = self.signature_key() + if isinstance(signature_key, ed25519.Ed25519PublicKey): + signature_key.verify( + bytes(self._signature), bytes(self._tbs_cert_body) + ) + elif isinstance(signature_key, ec.EllipticCurvePublicKey): + # The signature is encoded as a pair of big-endian integers + r, data = _get_mpint(self._signature) + s, data = _get_mpint(data) + _check_empty(data) + computed_sig = asym_utils.encode_dss_signature(r, s) + hash_alg = _get_ec_hash_alg(signature_key.curve) + signature_key.verify( + computed_sig, bytes(self._tbs_cert_body), ec.ECDSA(hash_alg) + ) + else: + assert isinstance(signature_key, rsa.RSAPublicKey) + if self._inner_sig_type == _SSH_RSA: + hash_alg = hashes.SHA1() + elif self._inner_sig_type == _SSH_RSA_SHA256: + hash_alg = hashes.SHA256() + else: + assert self._inner_sig_type == _SSH_RSA_SHA512 + hash_alg = hashes.SHA512() + signature_key.verify( + bytes(self._signature), + bytes(self._tbs_cert_body), + padding.PKCS1v15(), + hash_alg, + ) + + +def _get_ec_hash_alg(curve: ec.EllipticCurve) -> hashes.HashAlgorithm: + if isinstance(curve, ec.SECP256R1): + return hashes.SHA256() + elif isinstance(curve, ec.SECP384R1): + return hashes.SHA384() + else: + assert isinstance(curve, ec.SECP521R1) + return hashes.SHA512() + + +def _load_ssh_public_identity( + data: utils.Buffer, + _legacy_dsa_allowed=False, +) -> SSHCertificate | SSHPublicKeyTypes: + utils._check_byteslike("data", data) + + m = _SSH_PUBKEY_RC.match(data) + if not m: + raise ValueError("Invalid line format") + key_type = orig_key_type = m.group(1) + key_body = m.group(2) + with_cert = False + if key_type.endswith(_CERT_SUFFIX): + with_cert = True + key_type = key_type[: -len(_CERT_SUFFIX)] + if key_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA keys aren't supported in SSH certificates" + ) + kformat = _lookup_kformat(key_type) + + try: + rest = memoryview(binascii.a2b_base64(key_body)) + except (TypeError, binascii.Error): + raise ValueError("Invalid format") + + if with_cert: + cert_body = rest + inner_key_type, rest = _get_sshstr(rest) + if inner_key_type != orig_key_type: + raise ValueError("Invalid key format") + if with_cert: + nonce, rest = _get_sshstr(rest) + public_key, rest = kformat.load_public(rest) + if with_cert: + serial, rest = _get_u64(rest) + cctype, rest = _get_u32(rest) + key_id, rest = _get_sshstr(rest) + principals, rest = _get_sshstr(rest) + valid_principals = [] + while principals: + principal, principals = _get_sshstr(principals) + valid_principals.append(bytes(principal)) + valid_after, rest = _get_u64(rest) + valid_before, rest = _get_u64(rest) + crit_options, rest = _get_sshstr(rest) + critical_options = _parse_exts_opts(crit_options) + exts, rest = _get_sshstr(rest) + extensions = _parse_exts_opts(exts) + # Get the reserved field, which is unused. + _, rest = _get_sshstr(rest) + sig_key_raw, rest = _get_sshstr(rest) + sig_type, sig_key = _get_sshstr(sig_key_raw) + if sig_type == _SSH_DSA and not _legacy_dsa_allowed: + raise UnsupportedAlgorithm( + "DSA signatures aren't supported in SSH certificates" + ) + # Get the entire cert body and subtract the signature + tbs_cert_body = cert_body[: -len(rest)] + signature_raw, rest = _get_sshstr(rest) + _check_empty(rest) + inner_sig_type, sig_rest = _get_sshstr(signature_raw) + # RSA certs can have multiple algorithm types + if ( + sig_type == _SSH_RSA + and inner_sig_type + not in [_SSH_RSA_SHA256, _SSH_RSA_SHA512, _SSH_RSA] + ) or (sig_type != _SSH_RSA and inner_sig_type != sig_type): + raise ValueError("Signature key type does not match") + signature, sig_rest = _get_sshstr(sig_rest) + _check_empty(sig_rest) + return SSHCertificate( + nonce, + public_key, + serial, + cctype, + key_id, + valid_principals, + valid_after, + valid_before, + critical_options, + extensions, + sig_type, + sig_key, + inner_sig_type, + signature, + tbs_cert_body, + orig_key_type, + cert_body, + ) + else: + _check_empty(rest) + return public_key + + +def load_ssh_public_identity( + data: utils.Buffer, +) -> SSHCertificate | SSHPublicKeyTypes: + return _load_ssh_public_identity(data) + + +def _parse_exts_opts(exts_opts: memoryview) -> dict[bytes, bytes]: + result: dict[bytes, bytes] = {} + last_name = None + while exts_opts: + name, exts_opts = _get_sshstr(exts_opts) + bname: bytes = bytes(name) + if bname in result: + raise ValueError("Duplicate name") + if last_name is not None and bname < last_name: + raise ValueError("Fields not lexically sorted") + value, exts_opts = _get_sshstr(exts_opts) + if len(value) > 0: + value, extra = _get_sshstr(value) + if len(extra) > 0: + raise ValueError("Unexpected extra data after value") + result[bname] = bytes(value) + last_name = bname + return result + + +def ssh_key_fingerprint( + key: SSHPublicKeyTypes, + hash_algorithm: hashes.MD5 | hashes.SHA256, +) -> bytes: + if not isinstance(hash_algorithm, (hashes.MD5, hashes.SHA256)): + raise TypeError("hash_algorithm must be either MD5 or SHA256") + + key_type = _get_ssh_key_type(key) + kformat = _lookup_kformat(key_type) + + f_pub = _FragList() + f_pub.put_sshstr(key_type) + kformat.encode_public(key, f_pub) + + ssh_binary_data = f_pub.tobytes() + + # Hash the binary data + hash_obj = hashes.Hash(hash_algorithm) + hash_obj.update(ssh_binary_data) + return hash_obj.finalize() + + +def load_ssh_public_key( + data: utils.Buffer, backend: typing.Any = None +) -> SSHPublicKeyTypes: + cert_or_key = _load_ssh_public_identity(data, _legacy_dsa_allowed=True) + public_key: SSHPublicKeyTypes + if isinstance(cert_or_key, SSHCertificate): + public_key = cert_or_key.public_key() + else: + public_key = cert_or_key + + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA keys are deprecated and will be removed in a future " + "release.", + utils.DeprecatedIn40, + stacklevel=2, + ) + return public_key + + +def serialize_ssh_public_key(public_key: SSHPublicKeyTypes) -> bytes: + """One-line public key format for OpenSSH""" + if isinstance(public_key, dsa.DSAPublicKey): + warnings.warn( + "SSH DSA key support is deprecated and will be " + "removed in a future release", + utils.DeprecatedIn40, + stacklevel=4, + ) + key_type = _get_ssh_key_type(public_key) + kformat = _lookup_kformat(key_type) + + f_pub = _FragList() + f_pub.put_sshstr(key_type) + kformat.encode_public(public_key, f_pub) + + pub = binascii.b2a_base64(f_pub.tobytes()).strip() + return b"".join([key_type, b" ", pub]) + + +SSHCertPrivateKeyTypes = typing.Union[ + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, +] + + +# This is an undocumented limit enforced in the openssh codebase for sshd and +# ssh-keygen, but it is undefined in the ssh certificates spec. +_SSHKEY_CERT_MAX_PRINCIPALS = 256 + + +class SSHCertificateBuilder: + def __init__( + self, + _public_key: SSHCertPublicKeyTypes | None = None, + _serial: int | None = None, + _type: SSHCertificateType | None = None, + _key_id: bytes | None = None, + _valid_principals: list[bytes] = [], + _valid_for_all_principals: bool = False, + _valid_before: int | None = None, + _valid_after: int | None = None, + _critical_options: list[tuple[bytes, bytes]] = [], + _extensions: list[tuple[bytes, bytes]] = [], + ): + self._public_key = _public_key + self._serial = _serial + self._type = _type + self._key_id = _key_id + self._valid_principals = _valid_principals + self._valid_for_all_principals = _valid_for_all_principals + self._valid_before = _valid_before + self._valid_after = _valid_after + self._critical_options = _critical_options + self._extensions = _extensions + + def public_key( + self, public_key: SSHCertPublicKeyTypes + ) -> SSHCertificateBuilder: + if not isinstance( + public_key, + ( + ec.EllipticCurvePublicKey, + rsa.RSAPublicKey, + ed25519.Ed25519PublicKey, + ), + ): + raise TypeError("Unsupported key type") + if self._public_key is not None: + raise ValueError("public_key already set") + + return SSHCertificateBuilder( + _public_key=public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def serial(self, serial: int) -> SSHCertificateBuilder: + if not isinstance(serial, int): + raise TypeError("serial must be an integer") + if not 0 <= serial < 2**64: + raise ValueError("serial must be between 0 and 2**64") + if self._serial is not None: + raise ValueError("serial already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def type(self, type: SSHCertificateType) -> SSHCertificateBuilder: + if not isinstance(type, SSHCertificateType): + raise TypeError("type must be an SSHCertificateType") + if self._type is not None: + raise ValueError("type already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def key_id(self, key_id: bytes) -> SSHCertificateBuilder: + if not isinstance(key_id, bytes): + raise TypeError("key_id must be bytes") + if self._key_id is not None: + raise ValueError("key_id already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_principals( + self, valid_principals: list[bytes] + ) -> SSHCertificateBuilder: + if self._valid_for_all_principals: + raise ValueError( + "Principals can't be set because the cert is valid " + "for all principals" + ) + if ( + not all(isinstance(x, bytes) for x in valid_principals) + or not valid_principals + ): + raise TypeError( + "principals must be a list of bytes and can't be empty" + ) + if self._valid_principals: + raise ValueError("valid_principals already set") + + if len(valid_principals) > _SSHKEY_CERT_MAX_PRINCIPALS: + raise ValueError( + "Reached or exceeded the maximum number of valid_principals" + ) + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_for_all_principals(self): + if self._valid_principals: + raise ValueError( + "valid_principals already set, can't set " + "valid_for_all_principals" + ) + if self._valid_for_all_principals: + raise ValueError("valid_for_all_principals already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=True, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_before(self, valid_before: int | float) -> SSHCertificateBuilder: + if not isinstance(valid_before, (int, float)): + raise TypeError("valid_before must be an int or float") + valid_before = int(valid_before) + if valid_before < 0 or valid_before >= 2**64: + raise ValueError("valid_before must [0, 2**64)") + if self._valid_before is not None: + raise ValueError("valid_before already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def valid_after(self, valid_after: int | float) -> SSHCertificateBuilder: + if not isinstance(valid_after, (int, float)): + raise TypeError("valid_after must be an int or float") + valid_after = int(valid_after) + if valid_after < 0 or valid_after >= 2**64: + raise ValueError("valid_after must [0, 2**64)") + if self._valid_after is not None: + raise ValueError("valid_after already set") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=valid_after, + _critical_options=self._critical_options, + _extensions=self._extensions, + ) + + def add_critical_option( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._critical_options]: + raise ValueError("Duplicate critical option name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=[*self._critical_options, (name, value)], + _extensions=self._extensions, + ) + + def add_extension( + self, name: bytes, value: bytes + ) -> SSHCertificateBuilder: + if not isinstance(name, bytes) or not isinstance(value, bytes): + raise TypeError("name and value must be bytes") + # This is O(n**2) + if name in [name for name, _ in self._extensions]: + raise ValueError("Duplicate extension name") + + return SSHCertificateBuilder( + _public_key=self._public_key, + _serial=self._serial, + _type=self._type, + _key_id=self._key_id, + _valid_principals=self._valid_principals, + _valid_for_all_principals=self._valid_for_all_principals, + _valid_before=self._valid_before, + _valid_after=self._valid_after, + _critical_options=self._critical_options, + _extensions=[*self._extensions, (name, value)], + ) + + def sign(self, private_key: SSHCertPrivateKeyTypes) -> SSHCertificate: + if not isinstance( + private_key, + ( + ec.EllipticCurvePrivateKey, + rsa.RSAPrivateKey, + ed25519.Ed25519PrivateKey, + ), + ): + raise TypeError("Unsupported private key type") + + if self._public_key is None: + raise ValueError("public_key must be set") + + # Not required + serial = 0 if self._serial is None else self._serial + + if self._type is None: + raise ValueError("type must be set") + + # Not required + key_id = b"" if self._key_id is None else self._key_id + + # A zero length list is valid, but means the certificate + # is valid for any principal of the specified type. We require + # the user to explicitly set valid_for_all_principals to get + # that behavior. + if not self._valid_principals and not self._valid_for_all_principals: + raise ValueError( + "valid_principals must be set if valid_for_all_principals " + "is False" + ) + + if self._valid_before is None: + raise ValueError("valid_before must be set") + + if self._valid_after is None: + raise ValueError("valid_after must be set") + + if self._valid_after > self._valid_before: + raise ValueError("valid_after must be earlier than valid_before") + + # lexically sort our byte strings + self._critical_options.sort(key=lambda x: x[0]) + self._extensions.sort(key=lambda x: x[0]) + + key_type = _get_ssh_key_type(self._public_key) + cert_prefix = key_type + _CERT_SUFFIX + + # Marshal the bytes to be signed + nonce = os.urandom(32) + kformat = _lookup_kformat(key_type) + f = _FragList() + f.put_sshstr(cert_prefix) + f.put_sshstr(nonce) + kformat.encode_public(self._public_key, f) + f.put_u64(serial) + f.put_u32(self._type.value) + f.put_sshstr(key_id) + fprincipals = _FragList() + for p in self._valid_principals: + fprincipals.put_sshstr(p) + f.put_sshstr(fprincipals.tobytes()) + f.put_u64(self._valid_after) + f.put_u64(self._valid_before) + fcrit = _FragList() + for name, value in self._critical_options: + fcrit.put_sshstr(name) + if len(value) > 0: + foptval = _FragList() + foptval.put_sshstr(value) + fcrit.put_sshstr(foptval.tobytes()) + else: + fcrit.put_sshstr(value) + f.put_sshstr(fcrit.tobytes()) + fext = _FragList() + for name, value in self._extensions: + fext.put_sshstr(name) + if len(value) > 0: + fextval = _FragList() + fextval.put_sshstr(value) + fext.put_sshstr(fextval.tobytes()) + else: + fext.put_sshstr(value) + f.put_sshstr(fext.tobytes()) + f.put_sshstr(b"") # RESERVED FIELD + # encode CA public key + ca_type = _get_ssh_key_type(private_key) + caformat = _lookup_kformat(ca_type) + caf = _FragList() + caf.put_sshstr(ca_type) + caformat.encode_public(private_key.public_key(), caf) + f.put_sshstr(caf.tobytes()) + # Sigs according to the rules defined for the CA's public key + # (RFC4253 section 6.6 for ssh-rsa, RFC5656 for ECDSA, + # and RFC8032 for Ed25519). + if isinstance(private_key, ed25519.Ed25519PrivateKey): + signature = private_key.sign(f.tobytes()) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + elif isinstance(private_key, ec.EllipticCurvePrivateKey): + hash_alg = _get_ec_hash_alg(private_key.curve) + signature = private_key.sign(f.tobytes(), ec.ECDSA(hash_alg)) + r, s = asym_utils.decode_dss_signature(signature) + fsig = _FragList() + fsig.put_sshstr(ca_type) + fsigblob = _FragList() + fsigblob.put_mpint(r) + fsigblob.put_mpint(s) + fsig.put_sshstr(fsigblob.tobytes()) + f.put_sshstr(fsig.tobytes()) + + else: + assert isinstance(private_key, rsa.RSAPrivateKey) + # Just like Golang, we're going to use SHA512 for RSA + # https://cs.opensource.google/go/x/crypto/+/refs/tags/ + # v0.4.0:ssh/certs.go;l=445 + # RFC 8332 defines SHA256 and 512 as options + fsig = _FragList() + fsig.put_sshstr(_SSH_RSA_SHA512) + signature = private_key.sign( + f.tobytes(), padding.PKCS1v15(), hashes.SHA512() + ) + fsig.put_sshstr(signature) + f.put_sshstr(fsig.tobytes()) + + cert_data = binascii.b2a_base64(f.tobytes()).strip() + # load_ssh_public_identity returns a union, but this is + # guaranteed to be an SSHCertificate, so we cast to make + # mypy happy. + return typing.cast( + SSHCertificate, + load_ssh_public_identity(b"".join([cert_prefix, b" ", cert_data])), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c1af423004863e7db3e163f61a6baa4ddc157351 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__init__.py @@ -0,0 +1,9 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + + +class InvalidToken(Exception): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40b39579cdcd194e65f3194cb91a12599c0b26a1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c08c88de67033b22a2773c5889088776a65e74e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/hotp.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ddf6a2bd90f752f908554f71eccd9e5a32ed1ed Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/__pycache__/totp.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py new file mode 100644 index 0000000000000000000000000000000000000000..21fb000499c43cb8492ce60d9a2c5ed6fab704e2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/hotp.py @@ -0,0 +1,101 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import base64 +import typing +from urllib.parse import quote, urlencode + +from cryptography.hazmat.primitives import constant_time, hmac +from cryptography.hazmat.primitives.hashes import SHA1, SHA256, SHA512 +from cryptography.hazmat.primitives.twofactor import InvalidToken +from cryptography.utils import Buffer + +HOTPHashTypes = typing.Union[SHA1, SHA256, SHA512] + + +def _generate_uri( + hotp: HOTP, + type_name: str, + account_name: str, + issuer: str | None, + extra_parameters: list[tuple[str, int]], +) -> str: + parameters = [ + ("digits", hotp._length), + ("secret", base64.b32encode(hotp._key)), + ("algorithm", hotp._algorithm.name.upper()), + ] + + if issuer is not None: + parameters.append(("issuer", issuer)) + + parameters.extend(extra_parameters) + + label = ( + f"{quote(issuer)}:{quote(account_name)}" + if issuer + else quote(account_name) + ) + return f"otpauth://{type_name}/{label}?{urlencode(parameters)}" + + +class HOTP: + def __init__( + self, + key: Buffer, + length: int, + algorithm: HOTPHashTypes, + backend: typing.Any = None, + enforce_key_length: bool = True, + ) -> None: + if len(key) < 16 and enforce_key_length is True: + raise ValueError("Key length has to be at least 128 bits.") + + if not isinstance(length, int): + raise TypeError("Length parameter must be an integer type.") + + if length < 6 or length > 8: + raise ValueError("Length of HOTP has to be between 6 and 8.") + + if not isinstance(algorithm, (SHA1, SHA256, SHA512)): + raise TypeError("Algorithm must be SHA1, SHA256 or SHA512.") + + self._key = key + self._length = length + self._algorithm = algorithm + + def generate(self, counter: int) -> bytes: + if not isinstance(counter, int): + raise TypeError("Counter parameter must be an integer type.") + + truncated_value = self._dynamic_truncate(counter) + hotp = truncated_value % (10**self._length) + return "{0:0{1}}".format(hotp, self._length).encode() + + def verify(self, hotp: bytes, counter: int) -> None: + if not constant_time.bytes_eq(self.generate(counter), hotp): + raise InvalidToken("Supplied HOTP value does not match.") + + def _dynamic_truncate(self, counter: int) -> int: + ctx = hmac.HMAC(self._key, self._algorithm) + + try: + ctx.update(counter.to_bytes(length=8, byteorder="big")) + except OverflowError: + raise ValueError(f"Counter must be between 0 and {2**64 - 1}.") + + hmac_value = ctx.finalize() + + offset = hmac_value[len(hmac_value) - 1] & 0b1111 + p = hmac_value[offset : offset + 4] + return int.from_bytes(p, byteorder="big") & 0x7FFFFFFF + + def get_provisioning_uri( + self, account_name: str, counter: int, issuer: str | None + ) -> str: + return _generate_uri( + self, "hotp", account_name, issuer, [("counter", int(counter))] + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/totp.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/totp.py new file mode 100644 index 0000000000000000000000000000000000000000..10c725cc0ab0c9fff5a978a3d5278ccce52d4e67 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/hazmat/primitives/twofactor/totp.py @@ -0,0 +1,56 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.primitives import constant_time +from cryptography.hazmat.primitives.twofactor import InvalidToken +from cryptography.hazmat.primitives.twofactor.hotp import ( + HOTP, + HOTPHashTypes, + _generate_uri, +) +from cryptography.utils import Buffer + + +class TOTP: + def __init__( + self, + key: Buffer, + length: int, + algorithm: HOTPHashTypes, + time_step: int, + backend: typing.Any = None, + enforce_key_length: bool = True, + ): + self._time_step = time_step + self._hotp = HOTP( + key, length, algorithm, enforce_key_length=enforce_key_length + ) + + def generate(self, time: int | float) -> bytes: + if not isinstance(time, (int, float)): + raise TypeError( + "Time parameter must be an integer type or float type." + ) + + counter = int(time / self._time_step) + return self._hotp.generate(counter) + + def verify(self, totp: bytes, time: int) -> None: + if not constant_time.bytes_eq(self.generate(time), totp): + raise InvalidToken("Supplied TOTP value does not match.") + + def get_provisioning_uri( + self, account_name: str, issuer: str | None + ) -> str: + return _generate_uri( + self._hotp, + "totp", + account_name, + issuer, + [("period", int(self._time_step))], + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__init__.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..318eecc96e1df01dc3e26bb236c55cbfd77d05c1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__init__.py @@ -0,0 +1,270 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.x509 import certificate_transparency, verification +from cryptography.x509.base import ( + Attribute, + AttributeNotFound, + Attributes, + Certificate, + CertificateBuilder, + CertificateRevocationList, + CertificateRevocationListBuilder, + CertificateSigningRequest, + CertificateSigningRequestBuilder, + InvalidVersion, + RevokedCertificate, + RevokedCertificateBuilder, + Version, + load_der_x509_certificate, + load_der_x509_crl, + load_der_x509_csr, + load_pem_x509_certificate, + load_pem_x509_certificates, + load_pem_x509_crl, + load_pem_x509_csr, + random_serial_number, +) +from cryptography.x509.extensions import ( + AccessDescription, + Admission, + Admissions, + AuthorityInformationAccess, + AuthorityKeyIdentifier, + BasicConstraints, + CertificateIssuer, + CertificatePolicies, + CRLDistributionPoints, + CRLNumber, + CRLReason, + DeltaCRLIndicator, + DistributionPoint, + DuplicateExtension, + ExtendedKeyUsage, + Extension, + ExtensionNotFound, + Extensions, + ExtensionType, + FreshestCRL, + GeneralNames, + InhibitAnyPolicy, + InvalidityDate, + IssuerAlternativeName, + IssuingDistributionPoint, + KeyUsage, + MSCertificateTemplate, + NameConstraints, + NamingAuthority, + NoticeReference, + OCSPAcceptableResponses, + OCSPNoCheck, + OCSPNonce, + PolicyConstraints, + PolicyInformation, + PrecertificateSignedCertificateTimestamps, + PrecertPoison, + PrivateKeyUsagePeriod, + ProfessionInfo, + ReasonFlags, + SignedCertificateTimestamps, + SubjectAlternativeName, + SubjectInformationAccess, + SubjectKeyIdentifier, + TLSFeature, + TLSFeatureType, + UnrecognizedExtension, + UserNotice, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + UnsupportedGeneralNameType, +) +from cryptography.x509.name import ( + Name, + NameAttribute, + RelativeDistinguishedName, +) +from cryptography.x509.oid import ( + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + PublicKeyAlgorithmOID, + SignatureAlgorithmOID, +) + +OID_AUTHORITY_INFORMATION_ACCESS = ExtensionOID.AUTHORITY_INFORMATION_ACCESS +OID_AUTHORITY_KEY_IDENTIFIER = ExtensionOID.AUTHORITY_KEY_IDENTIFIER +OID_BASIC_CONSTRAINTS = ExtensionOID.BASIC_CONSTRAINTS +OID_CERTIFICATE_POLICIES = ExtensionOID.CERTIFICATE_POLICIES +OID_CRL_DISTRIBUTION_POINTS = ExtensionOID.CRL_DISTRIBUTION_POINTS +OID_EXTENDED_KEY_USAGE = ExtensionOID.EXTENDED_KEY_USAGE +OID_FRESHEST_CRL = ExtensionOID.FRESHEST_CRL +OID_INHIBIT_ANY_POLICY = ExtensionOID.INHIBIT_ANY_POLICY +OID_ISSUER_ALTERNATIVE_NAME = ExtensionOID.ISSUER_ALTERNATIVE_NAME +OID_KEY_USAGE = ExtensionOID.KEY_USAGE +OID_PRIVATE_KEY_USAGE_PERIOD = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD +OID_NAME_CONSTRAINTS = ExtensionOID.NAME_CONSTRAINTS +OID_OCSP_NO_CHECK = ExtensionOID.OCSP_NO_CHECK +OID_POLICY_CONSTRAINTS = ExtensionOID.POLICY_CONSTRAINTS +OID_POLICY_MAPPINGS = ExtensionOID.POLICY_MAPPINGS +OID_SUBJECT_ALTERNATIVE_NAME = ExtensionOID.SUBJECT_ALTERNATIVE_NAME +OID_SUBJECT_DIRECTORY_ATTRIBUTES = ExtensionOID.SUBJECT_DIRECTORY_ATTRIBUTES +OID_SUBJECT_INFORMATION_ACCESS = ExtensionOID.SUBJECT_INFORMATION_ACCESS +OID_SUBJECT_KEY_IDENTIFIER = ExtensionOID.SUBJECT_KEY_IDENTIFIER + +OID_DSA_WITH_SHA1 = SignatureAlgorithmOID.DSA_WITH_SHA1 +OID_DSA_WITH_SHA224 = SignatureAlgorithmOID.DSA_WITH_SHA224 +OID_DSA_WITH_SHA256 = SignatureAlgorithmOID.DSA_WITH_SHA256 +OID_ECDSA_WITH_SHA1 = SignatureAlgorithmOID.ECDSA_WITH_SHA1 +OID_ECDSA_WITH_SHA224 = SignatureAlgorithmOID.ECDSA_WITH_SHA224 +OID_ECDSA_WITH_SHA256 = SignatureAlgorithmOID.ECDSA_WITH_SHA256 +OID_ECDSA_WITH_SHA384 = SignatureAlgorithmOID.ECDSA_WITH_SHA384 +OID_ECDSA_WITH_SHA512 = SignatureAlgorithmOID.ECDSA_WITH_SHA512 +OID_RSA_WITH_MD5 = SignatureAlgorithmOID.RSA_WITH_MD5 +OID_RSA_WITH_SHA1 = SignatureAlgorithmOID.RSA_WITH_SHA1 +OID_RSA_WITH_SHA224 = SignatureAlgorithmOID.RSA_WITH_SHA224 +OID_RSA_WITH_SHA256 = SignatureAlgorithmOID.RSA_WITH_SHA256 +OID_RSA_WITH_SHA384 = SignatureAlgorithmOID.RSA_WITH_SHA384 +OID_RSA_WITH_SHA512 = SignatureAlgorithmOID.RSA_WITH_SHA512 +OID_RSASSA_PSS = SignatureAlgorithmOID.RSASSA_PSS + +OID_COMMON_NAME = NameOID.COMMON_NAME +OID_COUNTRY_NAME = NameOID.COUNTRY_NAME +OID_DOMAIN_COMPONENT = NameOID.DOMAIN_COMPONENT +OID_DN_QUALIFIER = NameOID.DN_QUALIFIER +OID_EMAIL_ADDRESS = NameOID.EMAIL_ADDRESS +OID_GENERATION_QUALIFIER = NameOID.GENERATION_QUALIFIER +OID_GIVEN_NAME = NameOID.GIVEN_NAME +OID_LOCALITY_NAME = NameOID.LOCALITY_NAME +OID_ORGANIZATIONAL_UNIT_NAME = NameOID.ORGANIZATIONAL_UNIT_NAME +OID_ORGANIZATION_NAME = NameOID.ORGANIZATION_NAME +OID_PSEUDONYM = NameOID.PSEUDONYM +OID_SERIAL_NUMBER = NameOID.SERIAL_NUMBER +OID_STATE_OR_PROVINCE_NAME = NameOID.STATE_OR_PROVINCE_NAME +OID_SURNAME = NameOID.SURNAME +OID_TITLE = NameOID.TITLE + +OID_CLIENT_AUTH = ExtendedKeyUsageOID.CLIENT_AUTH +OID_CODE_SIGNING = ExtendedKeyUsageOID.CODE_SIGNING +OID_EMAIL_PROTECTION = ExtendedKeyUsageOID.EMAIL_PROTECTION +OID_OCSP_SIGNING = ExtendedKeyUsageOID.OCSP_SIGNING +OID_SERVER_AUTH = ExtendedKeyUsageOID.SERVER_AUTH +OID_TIME_STAMPING = ExtendedKeyUsageOID.TIME_STAMPING + +OID_ANY_POLICY = CertificatePoliciesOID.ANY_POLICY +OID_CPS_QUALIFIER = CertificatePoliciesOID.CPS_QUALIFIER +OID_CPS_USER_NOTICE = CertificatePoliciesOID.CPS_USER_NOTICE + +OID_CERTIFICATE_ISSUER = CRLEntryExtensionOID.CERTIFICATE_ISSUER +OID_CRL_REASON = CRLEntryExtensionOID.CRL_REASON +OID_INVALIDITY_DATE = CRLEntryExtensionOID.INVALIDITY_DATE + +OID_CA_ISSUERS = AuthorityInformationAccessOID.CA_ISSUERS +OID_OCSP = AuthorityInformationAccessOID.OCSP + +__all__ = [ + "OID_CA_ISSUERS", + "OID_OCSP", + "AccessDescription", + "Admission", + "Admissions", + "Attribute", + "AttributeNotFound", + "Attributes", + "AuthorityInformationAccess", + "AuthorityKeyIdentifier", + "BasicConstraints", + "CRLDistributionPoints", + "CRLNumber", + "CRLReason", + "Certificate", + "CertificateBuilder", + "CertificateIssuer", + "CertificatePolicies", + "CertificateRevocationList", + "CertificateRevocationListBuilder", + "CertificateSigningRequest", + "CertificateSigningRequestBuilder", + "DNSName", + "DeltaCRLIndicator", + "DirectoryName", + "DistributionPoint", + "DuplicateExtension", + "ExtendedKeyUsage", + "Extension", + "ExtensionNotFound", + "ExtensionType", + "Extensions", + "FreshestCRL", + "GeneralName", + "GeneralNames", + "IPAddress", + "InhibitAnyPolicy", + "InvalidVersion", + "InvalidityDate", + "IssuerAlternativeName", + "IssuingDistributionPoint", + "KeyUsage", + "MSCertificateTemplate", + "Name", + "NameAttribute", + "NameConstraints", + "NameOID", + "NamingAuthority", + "NoticeReference", + "OCSPAcceptableResponses", + "OCSPNoCheck", + "OCSPNonce", + "ObjectIdentifier", + "OtherName", + "PolicyConstraints", + "PolicyInformation", + "PrecertPoison", + "PrecertificateSignedCertificateTimestamps", + "PrivateKeyUsagePeriod", + "ProfessionInfo", + "PublicKeyAlgorithmOID", + "RFC822Name", + "ReasonFlags", + "RegisteredID", + "RelativeDistinguishedName", + "RevokedCertificate", + "RevokedCertificateBuilder", + "SignatureAlgorithmOID", + "SignedCertificateTimestamps", + "SubjectAlternativeName", + "SubjectInformationAccess", + "SubjectKeyIdentifier", + "TLSFeature", + "TLSFeatureType", + "UniformResourceIdentifier", + "UnrecognizedExtension", + "UnsupportedGeneralNameType", + "UserNotice", + "Version", + "certificate_transparency", + "load_der_x509_certificate", + "load_der_x509_crl", + "load_der_x509_csr", + "load_pem_x509_certificate", + "load_pem_x509_certificates", + "load_pem_x509_crl", + "load_pem_x509_csr", + "random_serial_number", + "verification", + "verification", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63adc8850042ab907a1348b7c151655f53f44c55 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96ad23697d8b4154dfdead93b336eade5b5f392a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7371ba863b8738d1f4b90a6ba526133b7990bca8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/certificate_transparency.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9039627b8d49f83e3bed2fabf7b9ad0e4d77f543 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/general_name.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9b04b5249acc97bdf9f0a6cba4c367c67e59288 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/name.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f025f7cb65ec16e27d9bca55c0bdeef8c9b640 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/ocsp.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a12af290624a45782642dd13ffa24abcede614a1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/oid.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..073cc0ede0beb9a190dd2a344e20a72387bf264a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/__pycache__/verification.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/base.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/base.py new file mode 100644 index 0000000000000000000000000000000000000000..1be612be607b4338ed30c06a33a4b5157517e11c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/base.py @@ -0,0 +1,848 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import os +import typing +import warnings +from collections.abc import Iterable + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import ( + dsa, + ec, + ed448, + ed25519, + padding, + rsa, + x448, + x25519, +) +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.extensions import ( + Extension, + Extensions, + ExtensionType, + _make_sequence_methods, +) +from cryptography.x509.name import Name, _ASN1Type +from cryptography.x509.oid import ObjectIdentifier + +_EARLIEST_UTC_TIME = datetime.datetime(1950, 1, 1) + +# This must be kept in sync with sign.rs's list of allowable types in +# identify_hash_type +_AllowedHashTypes = typing.Union[ + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, + hashes.SHA3_224, + hashes.SHA3_256, + hashes.SHA3_384, + hashes.SHA3_512, +] + + +class AttributeNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +def _reject_duplicate_extension( + extension: Extension[ExtensionType], + extensions: list[Extension[ExtensionType]], +) -> None: + # This is quadratic in the number of extensions + for e in extensions: + if e.oid == extension.oid: + raise ValueError("This extension has already been set.") + + +def _reject_duplicate_attribute( + oid: ObjectIdentifier, + attributes: list[tuple[ObjectIdentifier, bytes, int | None]], +) -> None: + # This is quadratic in the number of attributes + for attr_oid, _, _ in attributes: + if attr_oid == oid: + raise ValueError("This attribute has already been set.") + + +def _convert_to_naive_utc_time(time: datetime.datetime) -> datetime.datetime: + """Normalizes a datetime to a naive datetime in UTC. + + time -- datetime to normalize. Assumed to be in UTC if not timezone + aware. + """ + if time.tzinfo is not None: + offset = time.utcoffset() + offset = offset if offset else datetime.timedelta() + return time.replace(tzinfo=None) - offset + else: + return time + + +class Attribute: + def __init__( + self, + oid: ObjectIdentifier, + value: bytes, + _type: int = _ASN1Type.UTF8String.value, + ) -> None: + self._oid = oid + self._value = value + self._type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Attribute): + return NotImplemented + + return ( + self.oid == other.oid + and self.value == other.value + and self._type == other._type + ) + + def __hash__(self) -> int: + return hash((self.oid, self.value, self._type)) + + +class Attributes: + def __init__( + self, + attributes: Iterable[Attribute], + ) -> None: + self._attributes = list(attributes) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_attributes") + + def __repr__(self) -> str: + return f"" + + def get_attribute_for_oid(self, oid: ObjectIdentifier) -> Attribute: + for attr in self: + if attr.oid == oid: + return attr + + raise AttributeNotFound(f"No {oid} attribute was found", oid) + + +class Version(utils.Enum): + v1 = 0 + v3 = 2 + + +class InvalidVersion(Exception): + def __init__(self, msg: str, parsed_version: int) -> None: + super().__init__(msg) + self.parsed_version = parsed_version + + +Certificate = rust_x509.Certificate + + +class RevokedCertificate(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def serial_number(self) -> int: + """ + Returns the serial number of the revoked certificate. + """ + + @property + @abc.abstractmethod + def revocation_date(self) -> datetime.datetime: + """ + Returns the date of when this certificate was revoked. + """ + + @property + @abc.abstractmethod + def revocation_date_utc(self) -> datetime.datetime: + """ + Returns the date of when this certificate was revoked as a non-naive + UTC datetime. + """ + + @property + @abc.abstractmethod + def extensions(self) -> Extensions: + """ + Returns an Extensions object containing a list of Revoked extensions. + """ + + +# Runtime isinstance checks need this since the rust class is not a subclass. +RevokedCertificate.register(rust_x509.RevokedCertificate) + + +class _RawRevokedCertificate(RevokedCertificate): + def __init__( + self, + serial_number: int, + revocation_date: datetime.datetime, + extensions: Extensions, + ): + self._serial_number = serial_number + self._revocation_date = revocation_date + self._extensions = extensions + + @property + def serial_number(self) -> int: + return self._serial_number + + @property + def revocation_date(self) -> datetime.datetime: + warnings.warn( + "Properties that return a naïve datetime object have been " + "deprecated. Please switch to revocation_date_utc.", + utils.DeprecatedIn42, + stacklevel=2, + ) + return self._revocation_date + + @property + def revocation_date_utc(self) -> datetime.datetime: + return self._revocation_date.replace(tzinfo=datetime.timezone.utc) + + @property + def extensions(self) -> Extensions: + return self._extensions + + +CertificateRevocationList = rust_x509.CertificateRevocationList +CertificateSigningRequest = rust_x509.CertificateSigningRequest + + +load_pem_x509_certificate = rust_x509.load_pem_x509_certificate +load_der_x509_certificate = rust_x509.load_der_x509_certificate + +load_pem_x509_certificates = rust_x509.load_pem_x509_certificates + +load_pem_x509_csr = rust_x509.load_pem_x509_csr +load_der_x509_csr = rust_x509.load_der_x509_csr + +load_pem_x509_crl = rust_x509.load_pem_x509_crl +load_der_x509_crl = rust_x509.load_der_x509_crl + + +class CertificateSigningRequestBuilder: + def __init__( + self, + subject_name: Name | None = None, + extensions: list[Extension[ExtensionType]] = [], + attributes: list[tuple[ObjectIdentifier, bytes, int | None]] = [], + ): + """ + Creates an empty X.509 certificate request (v1). + """ + self._subject_name = subject_name + self._extensions = extensions + self._attributes = attributes + + def subject_name(self, name: Name) -> CertificateSigningRequestBuilder: + """ + Sets the certificate requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateSigningRequestBuilder( + name, self._extensions, self._attributes + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 extension to the certificate request. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateSigningRequestBuilder( + self._subject_name, + [*self._extensions, extension], + self._attributes, + ) + + def add_attribute( + self, + oid: ObjectIdentifier, + value: bytes, + *, + _tag: _ASN1Type | None = None, + ) -> CertificateSigningRequestBuilder: + """ + Adds an X.509 attribute with an OID and associated value. + """ + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + + if not isinstance(value, bytes): + raise TypeError("value must be bytes") + + if _tag is not None and not isinstance(_tag, _ASN1Type): + raise TypeError("tag must be _ASN1Type") + + _reject_duplicate_attribute(oid, self._attributes) + + if _tag is not None: + tag = _tag.value + else: + tag = None + + return CertificateSigningRequestBuilder( + self._subject_name, + self._extensions, + [*self._attributes, (oid, value, tag)], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> CertificateSigningRequest: + """ + Signs the request using the requestor's private key. + """ + if self._subject_name is None: + raise ValueError("A CertificateSigningRequest must have a subject") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_csr( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class CertificateBuilder: + _extensions: list[Extension[ExtensionType]] + + def __init__( + self, + issuer_name: Name | None = None, + subject_name: Name | None = None, + public_key: CertificatePublicKeyTypes | None = None, + serial_number: int | None = None, + not_valid_before: datetime.datetime | None = None, + not_valid_after: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + ) -> None: + self._version = Version.v3 + self._issuer_name = issuer_name + self._subject_name = subject_name + self._public_key = public_key + self._serial_number = serial_number + self._not_valid_before = not_valid_before + self._not_valid_after = not_valid_after + self._extensions = extensions + + def issuer_name(self, name: Name) -> CertificateBuilder: + """ + Sets the CA's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateBuilder( + name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def subject_name(self, name: Name) -> CertificateBuilder: + """ + Sets the requestor's distinguished name. + """ + if not isinstance(name, Name): + raise TypeError("Expecting x509.Name object.") + if self._subject_name is not None: + raise ValueError("The subject name may only be set once.") + return CertificateBuilder( + self._issuer_name, + name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def public_key( + self, + key: CertificatePublicKeyTypes, + ) -> CertificateBuilder: + """ + Sets the requestor's public key (as found in the signing request). + """ + if not isinstance( + key, + ( + dsa.DSAPublicKey, + rsa.RSAPublicKey, + ec.EllipticCurvePublicKey, + ed25519.Ed25519PublicKey, + ed448.Ed448PublicKey, + x25519.X25519PublicKey, + x448.X448PublicKey, + ), + ): + raise TypeError( + "Expecting one of DSAPublicKey, RSAPublicKey," + " EllipticCurvePublicKey, Ed25519PublicKey," + " Ed448PublicKey, X25519PublicKey, or " + "X448PublicKey." + ) + if self._public_key is not None: + raise ValueError("The public key may only be set once.") + return CertificateBuilder( + self._issuer_name, + self._subject_name, + key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def serial_number(self, number: int) -> CertificateBuilder: + """ + Sets the certificate serial number. + """ + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive.") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 bits." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + number, + self._not_valid_before, + self._not_valid_after, + self._extensions, + ) + + def not_valid_before(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate activation time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_before is not None: + raise ValueError("The not valid before may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid before date must be on or after" + " 1950 January 1)." + ) + if self._not_valid_after is not None and time > self._not_valid_after: + raise ValueError( + "The not valid before date must be before the not valid after " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + time, + self._not_valid_after, + self._extensions, + ) + + def not_valid_after(self, time: datetime.datetime) -> CertificateBuilder: + """ + Sets the certificate expiration time. + """ + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._not_valid_after is not None: + raise ValueError("The not valid after may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The not valid after date must be on or after 1950 January 1." + ) + if ( + self._not_valid_before is not None + and time < self._not_valid_before + ): + raise ValueError( + "The not valid after date must be after the not valid before " + "date." + ) + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + time, + self._extensions, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateBuilder: + """ + Adds an X.509 extension to the certificate. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return CertificateBuilder( + self._issuer_name, + self._subject_name, + self._public_key, + self._serial_number, + self._not_valid_before, + self._not_valid_after, + [*self._extensions, extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> Certificate: + """ + Signs the certificate using the CA's private key. + """ + if self._subject_name is None: + raise ValueError("A certificate must have a subject name") + + if self._issuer_name is None: + raise ValueError("A certificate must have an issuer name") + + if self._serial_number is None: + raise ValueError("A certificate must have a serial number") + + if self._not_valid_before is None: + raise ValueError("A certificate must have a not valid before time") + + if self._not_valid_after is None: + raise ValueError("A certificate must have a not valid after time") + + if self._public_key is None: + raise ValueError("A certificate must have a public key") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_certificate( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class CertificateRevocationListBuilder: + _extensions: list[Extension[ExtensionType]] + _revoked_certificates: list[RevokedCertificate] + + def __init__( + self, + issuer_name: Name | None = None, + last_update: datetime.datetime | None = None, + next_update: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + revoked_certificates: list[RevokedCertificate] = [], + ): + self._issuer_name = issuer_name + self._last_update = last_update + self._next_update = next_update + self._extensions = extensions + self._revoked_certificates = revoked_certificates + + def issuer_name( + self, issuer_name: Name + ) -> CertificateRevocationListBuilder: + if not isinstance(issuer_name, Name): + raise TypeError("Expecting x509.Name object.") + if self._issuer_name is not None: + raise ValueError("The issuer name may only be set once.") + return CertificateRevocationListBuilder( + issuer_name, + self._last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def last_update( + self, last_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(last_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._last_update is not None: + raise ValueError("Last update may only be set once.") + last_update = _convert_to_naive_utc_time(last_update) + if last_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after 1950 January 1." + ) + if self._next_update is not None and last_update > self._next_update: + raise ValueError( + "The last update date must be before the next update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + last_update, + self._next_update, + self._extensions, + self._revoked_certificates, + ) + + def next_update( + self, next_update: datetime.datetime + ) -> CertificateRevocationListBuilder: + if not isinstance(next_update, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._next_update is not None: + raise ValueError("Last update may only be set once.") + next_update = _convert_to_naive_utc_time(next_update) + if next_update < _EARLIEST_UTC_TIME: + raise ValueError( + "The last update date must be on or after 1950 January 1." + ) + if self._last_update is not None and next_update < self._last_update: + raise ValueError( + "The next update date must be after the last update date." + ) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + next_update, + self._extensions, + self._revoked_certificates, + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> CertificateRevocationListBuilder: + """ + Adds an X.509 extension to the certificate revocation list. + """ + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + [*self._extensions, extension], + self._revoked_certificates, + ) + + def add_revoked_certificate( + self, revoked_certificate: RevokedCertificate + ) -> CertificateRevocationListBuilder: + """ + Adds a revoked certificate to the CRL. + """ + if not isinstance(revoked_certificate, RevokedCertificate): + raise TypeError("Must be an instance of RevokedCertificate") + + return CertificateRevocationListBuilder( + self._issuer_name, + self._last_update, + self._next_update, + self._extensions, + [*self._revoked_certificates, revoked_certificate], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: _AllowedHashTypes | None, + backend: typing.Any = None, + *, + rsa_padding: padding.PSS | padding.PKCS1v15 | None = None, + ecdsa_deterministic: bool | None = None, + ) -> CertificateRevocationList: + if self._issuer_name is None: + raise ValueError("A CRL must have an issuer name") + + if self._last_update is None: + raise ValueError("A CRL must have a last update time") + + if self._next_update is None: + raise ValueError("A CRL must have a next update time") + + if rsa_padding is not None: + if not isinstance(rsa_padding, (padding.PSS, padding.PKCS1v15)): + raise TypeError("Padding must be PSS or PKCS1v15") + if not isinstance(private_key, rsa.RSAPrivateKey): + raise TypeError("Padding is only supported for RSA keys") + + if ecdsa_deterministic is not None: + if not isinstance(private_key, ec.EllipticCurvePrivateKey): + raise TypeError( + "Deterministic ECDSA is only supported for EC keys" + ) + + return rust_x509.create_x509_crl( + self, + private_key, + algorithm, + rsa_padding, + ecdsa_deterministic, + ) + + +class RevokedCertificateBuilder: + def __init__( + self, + serial_number: int | None = None, + revocation_date: datetime.datetime | None = None, + extensions: list[Extension[ExtensionType]] = [], + ): + self._serial_number = serial_number + self._revocation_date = revocation_date + self._extensions = extensions + + def serial_number(self, number: int) -> RevokedCertificateBuilder: + if not isinstance(number, int): + raise TypeError("Serial number must be of integral type.") + if self._serial_number is not None: + raise ValueError("The serial number may only be set once.") + if number <= 0: + raise ValueError("The serial number should be positive") + + # ASN.1 integers are always signed, so most significant bit must be + # zero. + if number.bit_length() >= 160: # As defined in RFC 5280 + raise ValueError( + "The serial number should not be more than 159 bits." + ) + return RevokedCertificateBuilder( + number, self._revocation_date, self._extensions + ) + + def revocation_date( + self, time: datetime.datetime + ) -> RevokedCertificateBuilder: + if not isinstance(time, datetime.datetime): + raise TypeError("Expecting datetime object.") + if self._revocation_date is not None: + raise ValueError("The revocation date may only be set once.") + time = _convert_to_naive_utc_time(time) + if time < _EARLIEST_UTC_TIME: + raise ValueError( + "The revocation date must be on or after 1950 January 1." + ) + return RevokedCertificateBuilder( + self._serial_number, time, self._extensions + ) + + def add_extension( + self, extval: ExtensionType, critical: bool + ) -> RevokedCertificateBuilder: + if not isinstance(extval, ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + return RevokedCertificateBuilder( + self._serial_number, + self._revocation_date, + [*self._extensions, extension], + ) + + def build(self, backend: typing.Any = None) -> RevokedCertificate: + if self._serial_number is None: + raise ValueError("A revoked certificate must have a serial number") + if self._revocation_date is None: + raise ValueError( + "A revoked certificate must have a revocation date" + ) + return _RawRevokedCertificate( + self._serial_number, + self._revocation_date, + Extensions(self._extensions), + ) + + +def random_serial_number() -> int: + return int.from_bytes(os.urandom(20), "big") >> 1 diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/certificate_transparency.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/certificate_transparency.py new file mode 100644 index 0000000000000000000000000000000000000000..fb66cc6049528dd012f07bfcef765e284d0062d2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/certificate_transparency.py @@ -0,0 +1,35 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 + + +class LogEntryType(utils.Enum): + X509_CERTIFICATE = 0 + PRE_CERTIFICATE = 1 + + +class Version(utils.Enum): + v1 = 0 + + +class SignatureAlgorithm(utils.Enum): + """ + Signature algorithms that are valid for SCTs. + + These are exactly the same as SignatureAlgorithm in RFC 5246 (TLS 1.2). + + See: + """ + + ANONYMOUS = 0 + RSA = 1 + DSA = 2 + ECDSA = 3 + + +SignedCertificateTimestamp = rust_x509.Sct diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/extensions.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/extensions.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa472d38061584e086a60820fac8555bc4fa808 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/extensions.py @@ -0,0 +1,2528 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import datetime +import hashlib +import ipaddress +import typing +from collections.abc import Iterable, Iterator + +from cryptography import utils +from cryptography.hazmat.bindings._rust import asn1 +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.hazmat.primitives import constant_time, serialization +from cryptography.hazmat.primitives.asymmetric.ec import EllipticCurvePublicKey +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPublicKeyTypes, + CertificatePublicKeyTypes, +) +from cryptography.x509.certificate_transparency import ( + SignedCertificateTimestamp, +) +from cryptography.x509.general_name import ( + DirectoryName, + DNSName, + GeneralName, + IPAddress, + OtherName, + RegisteredID, + RFC822Name, + UniformResourceIdentifier, + _IPAddressTypes, +) +from cryptography.x509.name import Name, RelativeDistinguishedName +from cryptography.x509.oid import ( + CRLEntryExtensionOID, + ExtensionOID, + ObjectIdentifier, + OCSPExtensionOID, +) + +ExtensionTypeVar = typing.TypeVar( + "ExtensionTypeVar", bound="ExtensionType", covariant=True +) + + +def _key_identifier_from_public_key( + public_key: CertificatePublicKeyTypes, +) -> bytes: + if isinstance(public_key, RSAPublicKey): + data = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.PKCS1, + ) + elif isinstance(public_key, EllipticCurvePublicKey): + data = public_key.public_bytes( + serialization.Encoding.X962, + serialization.PublicFormat.UncompressedPoint, + ) + else: + # This is a very slow way to do this. + serialized = public_key.public_bytes( + serialization.Encoding.DER, + serialization.PublicFormat.SubjectPublicKeyInfo, + ) + data = asn1.parse_spki_for_data(serialized) + + return hashlib.sha1(data).digest() + + +def _make_sequence_methods(field_name: str): + def len_method(self) -> int: + return len(getattr(self, field_name)) + + def iter_method(self): + return iter(getattr(self, field_name)) + + def getitem_method(self, idx): + return getattr(self, field_name)[idx] + + return len_method, iter_method, getitem_method + + +class DuplicateExtension(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionNotFound(Exception): + def __init__(self, msg: str, oid: ObjectIdentifier) -> None: + super().__init__(msg) + self.oid = oid + + +class ExtensionType(metaclass=abc.ABCMeta): + oid: typing.ClassVar[ObjectIdentifier] + + def public_bytes(self) -> bytes: + """ + Serializes the extension type to DER. + """ + raise NotImplementedError( + f"public_bytes is not implemented for extension type {self!r}" + ) + + +class Extensions: + def __init__(self, extensions: Iterable[Extension[ExtensionType]]) -> None: + self._extensions = list(extensions) + + def get_extension_for_oid( + self, oid: ObjectIdentifier + ) -> Extension[ExtensionType]: + for ext in self: + if ext.oid == oid: + return ext + + raise ExtensionNotFound(f"No {oid} extension was found", oid) + + def get_extension_for_class( + self, extclass: type[ExtensionTypeVar] + ) -> Extension[ExtensionTypeVar]: + if extclass is UnrecognizedExtension: + raise TypeError( + "UnrecognizedExtension can't be used with " + "get_extension_for_class because more than one instance of the" + " class may be present." + ) + + for ext in self: + if isinstance(ext.value, extclass): + return ext + + raise ExtensionNotFound( + f"No {extclass} extension was found", extclass.oid + ) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_extensions") + + def __repr__(self) -> str: + return f"" + + +class CRLNumber(ExtensionType): + oid = ExtensionOID.CRL_NUMBER + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLNumber): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + @property + def crl_number(self) -> int: + return self._crl_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityKeyIdentifier(ExtensionType): + oid = ExtensionOID.AUTHORITY_KEY_IDENTIFIER + + def __init__( + self, + key_identifier: bytes | None, + authority_cert_issuer: Iterable[GeneralName] | None, + authority_cert_serial_number: int | None, + ) -> None: + if (authority_cert_issuer is None) != ( + authority_cert_serial_number is None + ): + raise ValueError( + "authority_cert_issuer and authority_cert_serial_number " + "must both be present or both None" + ) + + if authority_cert_issuer is not None: + authority_cert_issuer = list(authority_cert_issuer) + if not all( + isinstance(x, GeneralName) for x in authority_cert_issuer + ): + raise TypeError( + "authority_cert_issuer must be a list of GeneralName " + "objects" + ) + + if authority_cert_serial_number is not None and not isinstance( + authority_cert_serial_number, int + ): + raise TypeError("authority_cert_serial_number must be an integer") + + self._key_identifier = key_identifier + self._authority_cert_issuer = authority_cert_issuer + self._authority_cert_serial_number = authority_cert_serial_number + + # This takes a subset of CertificatePublicKeyTypes because an issuer + # cannot have an X25519/X448 key. This introduces some unfortunate + # asymmetry that requires typing users to explicitly + # narrow their type, but we should make this accurate and not just + # convenient. + @classmethod + def from_issuer_public_key( + cls, public_key: CertificateIssuerPublicKeyTypes + ) -> AuthorityKeyIdentifier: + digest = _key_identifier_from_public_key(public_key) + return cls( + key_identifier=digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + @classmethod + def from_issuer_subject_key_identifier( + cls, ski: SubjectKeyIdentifier + ) -> AuthorityKeyIdentifier: + return cls( + key_identifier=ski.digest, + authority_cert_issuer=None, + authority_cert_serial_number=None, + ) + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityKeyIdentifier): + return NotImplemented + + return ( + self.key_identifier == other.key_identifier + and self.authority_cert_issuer == other.authority_cert_issuer + and self.authority_cert_serial_number + == other.authority_cert_serial_number + ) + + def __hash__(self) -> int: + if self.authority_cert_issuer is None: + aci = None + else: + aci = tuple(self.authority_cert_issuer) + return hash( + (self.key_identifier, aci, self.authority_cert_serial_number) + ) + + @property + def key_identifier(self) -> bytes | None: + return self._key_identifier + + @property + def authority_cert_issuer( + self, + ) -> list[GeneralName] | None: + return self._authority_cert_issuer + + @property + def authority_cert_serial_number(self) -> int | None: + return self._authority_cert_serial_number + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectKeyIdentifier(ExtensionType): + oid = ExtensionOID.SUBJECT_KEY_IDENTIFIER + + def __init__(self, digest: bytes) -> None: + self._digest = digest + + @classmethod + def from_public_key( + cls, public_key: CertificatePublicKeyTypes + ) -> SubjectKeyIdentifier: + return cls(_key_identifier_from_public_key(public_key)) + + @property + def digest(self) -> bytes: + return self._digest + + @property + def key_identifier(self) -> bytes: + return self._digest + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectKeyIdentifier): + return NotImplemented + + return constant_time.bytes_eq(self.digest, other.digest) + + def __hash__(self) -> int: + return hash(self.digest) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AuthorityInformationAccess(ExtensionType): + oid = ExtensionOID.AUTHORITY_INFORMATION_ACCESS + + def __init__(self, descriptions: Iterable[AccessDescription]) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AuthorityInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SubjectInformationAccess(ExtensionType): + oid = ExtensionOID.SUBJECT_INFORMATION_ACCESS + + def __init__(self, descriptions: Iterable[AccessDescription]) -> None: + descriptions = list(descriptions) + if not all(isinstance(x, AccessDescription) for x in descriptions): + raise TypeError( + "Every item in the descriptions list must be an " + "AccessDescription" + ) + + self._descriptions = descriptions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_descriptions") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectInformationAccess): + return NotImplemented + + return self._descriptions == other._descriptions + + def __hash__(self) -> int: + return hash(tuple(self._descriptions)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class AccessDescription: + def __init__( + self, access_method: ObjectIdentifier, access_location: GeneralName + ) -> None: + if not isinstance(access_method, ObjectIdentifier): + raise TypeError("access_method must be an ObjectIdentifier") + + if not isinstance(access_location, GeneralName): + raise TypeError("access_location must be a GeneralName") + + self._access_method = access_method + self._access_location = access_location + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, AccessDescription): + return NotImplemented + + return ( + self.access_method == other.access_method + and self.access_location == other.access_location + ) + + def __hash__(self) -> int: + return hash((self.access_method, self.access_location)) + + @property + def access_method(self) -> ObjectIdentifier: + return self._access_method + + @property + def access_location(self) -> GeneralName: + return self._access_location + + +class BasicConstraints(ExtensionType): + oid = ExtensionOID.BASIC_CONSTRAINTS + + def __init__(self, ca: bool, path_length: int | None) -> None: + if not isinstance(ca, bool): + raise TypeError("ca must be a boolean value") + + if path_length is not None and not ca: + raise ValueError("path_length must be None when ca is False") + + if path_length is not None and ( + not isinstance(path_length, int) or path_length < 0 + ): + raise TypeError( + "path_length must be a non-negative integer or None" + ) + + self._ca = ca + self._path_length = path_length + + @property + def ca(self) -> bool: + return self._ca + + @property + def path_length(self) -> int | None: + return self._path_length + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, BasicConstraints): + return NotImplemented + + return self.ca == other.ca and self.path_length == other.path_length + + def __hash__(self) -> int: + return hash((self.ca, self.path_length)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DeltaCRLIndicator(ExtensionType): + oid = ExtensionOID.DELTA_CRL_INDICATOR + + def __init__(self, crl_number: int) -> None: + if not isinstance(crl_number, int): + raise TypeError("crl_number must be an integer") + + self._crl_number = crl_number + + @property + def crl_number(self) -> int: + return self._crl_number + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DeltaCRLIndicator): + return NotImplemented + + return self.crl_number == other.crl_number + + def __hash__(self) -> int: + return hash(self.crl_number) + + def __repr__(self) -> str: + return f"" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLDistributionPoints(ExtensionType): + oid = ExtensionOID.CRL_DISTRIBUTION_POINTS + + def __init__( + self, distribution_points: Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLDistributionPoints): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class FreshestCRL(ExtensionType): + oid = ExtensionOID.FRESHEST_CRL + + def __init__( + self, distribution_points: Iterable[DistributionPoint] + ) -> None: + distribution_points = list(distribution_points) + if not all( + isinstance(x, DistributionPoint) for x in distribution_points + ): + raise TypeError( + "distribution_points must be a list of DistributionPoint " + "objects" + ) + + self._distribution_points = distribution_points + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_distribution_points" + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, FreshestCRL): + return NotImplemented + + return self._distribution_points == other._distribution_points + + def __hash__(self) -> int: + return hash(tuple(self._distribution_points)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class DistributionPoint: + def __init__( + self, + full_name: Iterable[GeneralName] | None, + relative_name: RelativeDistinguishedName | None, + reasons: frozenset[ReasonFlags] | None, + crl_issuer: Iterable[GeneralName] | None, + ) -> None: + if full_name and relative_name: + raise ValueError( + "You cannot provide both full_name and relative_name, at " + "least one must be None." + ) + if not full_name and not relative_name and not crl_issuer: + raise ValueError( + "Either full_name, relative_name or crl_issuer must be " + "provided." + ) + + if full_name is not None: + full_name = list(full_name) + if not all(isinstance(x, GeneralName) for x in full_name): + raise TypeError( + "full_name must be a list of GeneralName objects" + ) + + if relative_name: + if not isinstance(relative_name, RelativeDistinguishedName): + raise TypeError( + "relative_name must be a RelativeDistinguishedName" + ) + + if crl_issuer is not None: + crl_issuer = list(crl_issuer) + if not all(isinstance(x, GeneralName) for x in crl_issuer): + raise TypeError( + "crl_issuer must be None or a list of general names" + ) + + if reasons and ( + not isinstance(reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in reasons) + ): + raise TypeError("reasons must be None or frozenset of ReasonFlags") + + if reasons and ( + ReasonFlags.unspecified in reasons + or ReasonFlags.remove_from_crl in reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in a " + "DistributionPoint" + ) + + self._full_name = full_name + self._relative_name = relative_name + self._reasons = reasons + self._crl_issuer = crl_issuer + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.reasons == other.reasons + and self.crl_issuer == other.crl_issuer + ) + + def __hash__(self) -> int: + if self.full_name is not None: + fn: tuple[GeneralName, ...] | None = tuple(self.full_name) + else: + fn = None + + if self.crl_issuer is not None: + crl_issuer: tuple[GeneralName, ...] | None = tuple(self.crl_issuer) + else: + crl_issuer = None + + return hash((fn, self.relative_name, self.reasons, crl_issuer)) + + @property + def full_name(self) -> list[GeneralName] | None: + return self._full_name + + @property + def relative_name(self) -> RelativeDistinguishedName | None: + return self._relative_name + + @property + def reasons(self) -> frozenset[ReasonFlags] | None: + return self._reasons + + @property + def crl_issuer(self) -> list[GeneralName] | None: + return self._crl_issuer + + +class ReasonFlags(utils.Enum): + unspecified = "unspecified" + key_compromise = "keyCompromise" + ca_compromise = "cACompromise" + affiliation_changed = "affiliationChanged" + superseded = "superseded" + cessation_of_operation = "cessationOfOperation" + certificate_hold = "certificateHold" + privilege_withdrawn = "privilegeWithdrawn" + aa_compromise = "aACompromise" + remove_from_crl = "removeFromCRL" + + +# These are distribution point bit string mappings. Not to be confused with +# CRLReason reason flags bit string mappings. +# ReasonFlags ::= BIT STRING { +# unused (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# privilegeWithdrawn (7), +# aACompromise (8) } +_REASON_BIT_MAPPING = { + 1: ReasonFlags.key_compromise, + 2: ReasonFlags.ca_compromise, + 3: ReasonFlags.affiliation_changed, + 4: ReasonFlags.superseded, + 5: ReasonFlags.cessation_of_operation, + 6: ReasonFlags.certificate_hold, + 7: ReasonFlags.privilege_withdrawn, + 8: ReasonFlags.aa_compromise, +} + +_CRLREASONFLAGS = { + ReasonFlags.key_compromise: 1, + ReasonFlags.ca_compromise: 2, + ReasonFlags.affiliation_changed: 3, + ReasonFlags.superseded: 4, + ReasonFlags.cessation_of_operation: 5, + ReasonFlags.certificate_hold: 6, + ReasonFlags.privilege_withdrawn: 7, + ReasonFlags.aa_compromise: 8, +} + +# CRLReason ::= ENUMERATED { +# unspecified (0), +# keyCompromise (1), +# cACompromise (2), +# affiliationChanged (3), +# superseded (4), +# cessationOfOperation (5), +# certificateHold (6), +# -- value 7 is not used +# removeFromCRL (8), +# privilegeWithdrawn (9), +# aACompromise (10) } +_CRL_ENTRY_REASON_ENUM_TO_CODE = { + ReasonFlags.unspecified: 0, + ReasonFlags.key_compromise: 1, + ReasonFlags.ca_compromise: 2, + ReasonFlags.affiliation_changed: 3, + ReasonFlags.superseded: 4, + ReasonFlags.cessation_of_operation: 5, + ReasonFlags.certificate_hold: 6, + ReasonFlags.remove_from_crl: 8, + ReasonFlags.privilege_withdrawn: 9, + ReasonFlags.aa_compromise: 10, +} + + +class PolicyConstraints(ExtensionType): + oid = ExtensionOID.POLICY_CONSTRAINTS + + def __init__( + self, + require_explicit_policy: int | None, + inhibit_policy_mapping: int | None, + ) -> None: + if require_explicit_policy is not None and not isinstance( + require_explicit_policy, int + ): + raise TypeError( + "require_explicit_policy must be a non-negative integer or " + "None" + ) + + if inhibit_policy_mapping is not None and not isinstance( + inhibit_policy_mapping, int + ): + raise TypeError( + "inhibit_policy_mapping must be a non-negative integer or None" + ) + + if inhibit_policy_mapping is None and require_explicit_policy is None: + raise ValueError( + "At least one of require_explicit_policy and " + "inhibit_policy_mapping must not be None" + ) + + self._require_explicit_policy = require_explicit_policy + self._inhibit_policy_mapping = inhibit_policy_mapping + + def __repr__(self) -> str: + return ( + "".format(self) + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyConstraints): + return NotImplemented + + return ( + self.require_explicit_policy == other.require_explicit_policy + and self.inhibit_policy_mapping == other.inhibit_policy_mapping + ) + + def __hash__(self) -> int: + return hash( + (self.require_explicit_policy, self.inhibit_policy_mapping) + ) + + @property + def require_explicit_policy(self) -> int | None: + return self._require_explicit_policy + + @property + def inhibit_policy_mapping(self) -> int | None: + return self._inhibit_policy_mapping + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificatePolicies(ExtensionType): + oid = ExtensionOID.CERTIFICATE_POLICIES + + def __init__(self, policies: Iterable[PolicyInformation]) -> None: + policies = list(policies) + if not all(isinstance(x, PolicyInformation) for x in policies): + raise TypeError( + "Every item in the policies list must be a PolicyInformation" + ) + + self._policies = policies + + __len__, __iter__, __getitem__ = _make_sequence_methods("_policies") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificatePolicies): + return NotImplemented + + return self._policies == other._policies + + def __hash__(self) -> int: + return hash(tuple(self._policies)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PolicyInformation: + def __init__( + self, + policy_identifier: ObjectIdentifier, + policy_qualifiers: Iterable[str | UserNotice] | None, + ) -> None: + if not isinstance(policy_identifier, ObjectIdentifier): + raise TypeError("policy_identifier must be an ObjectIdentifier") + + self._policy_identifier = policy_identifier + + if policy_qualifiers is not None: + policy_qualifiers = list(policy_qualifiers) + if not all( + isinstance(x, (str, UserNotice)) for x in policy_qualifiers + ): + raise TypeError( + "policy_qualifiers must be a list of strings and/or " + "UserNotice objects or None" + ) + + self._policy_qualifiers = policy_qualifiers + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PolicyInformation): + return NotImplemented + + return ( + self.policy_identifier == other.policy_identifier + and self.policy_qualifiers == other.policy_qualifiers + ) + + def __hash__(self) -> int: + if self.policy_qualifiers is not None: + pq = tuple(self.policy_qualifiers) + else: + pq = None + + return hash((self.policy_identifier, pq)) + + @property + def policy_identifier(self) -> ObjectIdentifier: + return self._policy_identifier + + @property + def policy_qualifiers( + self, + ) -> list[str | UserNotice] | None: + return self._policy_qualifiers + + +class UserNotice: + def __init__( + self, + notice_reference: NoticeReference | None, + explicit_text: str | None, + ) -> None: + if notice_reference and not isinstance( + notice_reference, NoticeReference + ): + raise TypeError( + "notice_reference must be None or a NoticeReference" + ) + + self._notice_reference = notice_reference + self._explicit_text = explicit_text + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UserNotice): + return NotImplemented + + return ( + self.notice_reference == other.notice_reference + and self.explicit_text == other.explicit_text + ) + + def __hash__(self) -> int: + return hash((self.notice_reference, self.explicit_text)) + + @property + def notice_reference(self) -> NoticeReference | None: + return self._notice_reference + + @property + def explicit_text(self) -> str | None: + return self._explicit_text + + +class NoticeReference: + def __init__( + self, + organization: str | None, + notice_numbers: Iterable[int], + ) -> None: + self._organization = organization + notice_numbers = list(notice_numbers) + if not all(isinstance(x, int) for x in notice_numbers): + raise TypeError("notice_numbers must be a list of integers") + + self._notice_numbers = notice_numbers + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NoticeReference): + return NotImplemented + + return ( + self.organization == other.organization + and self.notice_numbers == other.notice_numbers + ) + + def __hash__(self) -> int: + return hash((self.organization, tuple(self.notice_numbers))) + + @property + def organization(self) -> str | None: + return self._organization + + @property + def notice_numbers(self) -> list[int]: + return self._notice_numbers + + +class ExtendedKeyUsage(ExtensionType): + oid = ExtensionOID.EXTENDED_KEY_USAGE + + def __init__(self, usages: Iterable[ObjectIdentifier]) -> None: + usages = list(usages) + if not all(isinstance(x, ObjectIdentifier) for x in usages): + raise TypeError( + "Every item in the usages list must be an ObjectIdentifier" + ) + + self._usages = usages + + __len__, __iter__, __getitem__ = _make_sequence_methods("_usages") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ExtendedKeyUsage): + return NotImplemented + + return self._usages == other._usages + + def __hash__(self) -> int: + return hash(tuple(self._usages)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNoCheck(ExtensionType): + oid = ExtensionOID.OCSP_NO_CHECK + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNoCheck): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(OCSPNoCheck) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertPoison(ExtensionType): + oid = ExtensionOID.PRECERT_POISON + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertPoison): + return NotImplemented + + return True + + def __hash__(self) -> int: + return hash(PrecertPoison) + + def __repr__(self) -> str: + return "" + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeature(ExtensionType): + oid = ExtensionOID.TLS_FEATURE + + def __init__(self, features: Iterable[TLSFeatureType]) -> None: + features = list(features) + if ( + not all(isinstance(x, TLSFeatureType) for x in features) + or len(features) == 0 + ): + raise TypeError( + "features must be a list of elements from the TLSFeatureType " + "enum" + ) + + self._features = features + + __len__, __iter__, __getitem__ = _make_sequence_methods("_features") + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, TLSFeature): + return NotImplemented + + return self._features == other._features + + def __hash__(self) -> int: + return hash(tuple(self._features)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class TLSFeatureType(utils.Enum): + # status_request is defined in RFC 6066 and is used for what is commonly + # called OCSP Must-Staple when present in the TLS Feature extension in an + # X.509 certificate. + status_request = 5 + # status_request_v2 is defined in RFC 6961 and allows multiple OCSP + # responses to be provided. It is not currently in use by clients or + # servers. + status_request_v2 = 17 + + +_TLS_FEATURE_TYPE_TO_ENUM = {x.value: x for x in TLSFeatureType} + + +class InhibitAnyPolicy(ExtensionType): + oid = ExtensionOID.INHIBIT_ANY_POLICY + + def __init__(self, skip_certs: int) -> None: + if not isinstance(skip_certs, int): + raise TypeError("skip_certs must be an integer") + + if skip_certs < 0: + raise ValueError("skip_certs must be a non-negative integer") + + self._skip_certs = skip_certs + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InhibitAnyPolicy): + return NotImplemented + + return self.skip_certs == other.skip_certs + + def __hash__(self) -> int: + return hash(self.skip_certs) + + @property + def skip_certs(self) -> int: + return self._skip_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class KeyUsage(ExtensionType): + oid = ExtensionOID.KEY_USAGE + + def __init__( + self, + digital_signature: bool, + content_commitment: bool, + key_encipherment: bool, + data_encipherment: bool, + key_agreement: bool, + key_cert_sign: bool, + crl_sign: bool, + encipher_only: bool, + decipher_only: bool, + ) -> None: + if not key_agreement and (encipher_only or decipher_only): + raise ValueError( + "encipher_only and decipher_only can only be true when " + "key_agreement is true" + ) + + self._digital_signature = digital_signature + self._content_commitment = content_commitment + self._key_encipherment = key_encipherment + self._data_encipherment = data_encipherment + self._key_agreement = key_agreement + self._key_cert_sign = key_cert_sign + self._crl_sign = crl_sign + self._encipher_only = encipher_only + self._decipher_only = decipher_only + + @property + def digital_signature(self) -> bool: + return self._digital_signature + + @property + def content_commitment(self) -> bool: + return self._content_commitment + + @property + def key_encipherment(self) -> bool: + return self._key_encipherment + + @property + def data_encipherment(self) -> bool: + return self._data_encipherment + + @property + def key_agreement(self) -> bool: + return self._key_agreement + + @property + def key_cert_sign(self) -> bool: + return self._key_cert_sign + + @property + def crl_sign(self) -> bool: + return self._crl_sign + + @property + def encipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "encipher_only is undefined unless key_agreement is true" + ) + else: + return self._encipher_only + + @property + def decipher_only(self) -> bool: + if not self.key_agreement: + raise ValueError( + "decipher_only is undefined unless key_agreement is true" + ) + else: + return self._decipher_only + + def __repr__(self) -> str: + try: + encipher_only = self.encipher_only + decipher_only = self.decipher_only + except ValueError: + # Users found None confusing because even though encipher/decipher + # have no meaning unless key_agreement is true, to construct an + # instance of the class you still need to pass False. + encipher_only = False + decipher_only = False + + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, KeyUsage): + return NotImplemented + + return ( + self.digital_signature == other.digital_signature + and self.content_commitment == other.content_commitment + and self.key_encipherment == other.key_encipherment + and self.data_encipherment == other.data_encipherment + and self.key_agreement == other.key_agreement + and self.key_cert_sign == other.key_cert_sign + and self.crl_sign == other.crl_sign + and self._encipher_only == other._encipher_only + and self._decipher_only == other._decipher_only + ) + + def __hash__(self) -> int: + return hash( + ( + self.digital_signature, + self.content_commitment, + self.key_encipherment, + self.data_encipherment, + self.key_agreement, + self.key_cert_sign, + self.crl_sign, + self._encipher_only, + self._decipher_only, + ) + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrivateKeyUsagePeriod(ExtensionType): + oid = ExtensionOID.PRIVATE_KEY_USAGE_PERIOD + + def __init__( + self, + not_before: datetime.datetime | None, + not_after: datetime.datetime | None, + ) -> None: + if ( + not isinstance(not_before, datetime.datetime) + and not_before is not None + ): + raise TypeError("not_before must be a datetime.datetime or None") + + if ( + not isinstance(not_after, datetime.datetime) + and not_after is not None + ): + raise TypeError("not_after must be a datetime.datetime or None") + + if not_before is None and not_after is None: + raise ValueError( + "At least one of not_before and not_after must not be None" + ) + + if ( + not_before is not None + and not_after is not None + and not_before > not_after + ): + raise ValueError("not_before must be before not_after") + + self._not_before = not_before + self._not_after = not_after + + @property + def not_before(self) -> datetime.datetime | None: + return self._not_before + + @property + def not_after(self) -> datetime.datetime | None: + return self._not_after + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrivateKeyUsagePeriod): + return NotImplemented + + return ( + self.not_before == other.not_before + and self.not_after == other.not_after + ) + + def __hash__(self) -> int: + return hash((self.not_before, self.not_after)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class NameConstraints(ExtensionType): + oid = ExtensionOID.NAME_CONSTRAINTS + + def __init__( + self, + permitted_subtrees: Iterable[GeneralName] | None, + excluded_subtrees: Iterable[GeneralName] | None, + ) -> None: + if permitted_subtrees is not None: + permitted_subtrees = list(permitted_subtrees) + if not permitted_subtrees: + raise ValueError( + "permitted_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in permitted_subtrees): + raise TypeError( + "permitted_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(permitted_subtrees) + + if excluded_subtrees is not None: + excluded_subtrees = list(excluded_subtrees) + if not excluded_subtrees: + raise ValueError( + "excluded_subtrees must be a non-empty list or None" + ) + if not all(isinstance(x, GeneralName) for x in excluded_subtrees): + raise TypeError( + "excluded_subtrees must be a list of GeneralName objects " + "or None" + ) + + self._validate_tree(excluded_subtrees) + + if permitted_subtrees is None and excluded_subtrees is None: + raise ValueError( + "At least one of permitted_subtrees and excluded_subtrees " + "must not be None" + ) + + self._permitted_subtrees = permitted_subtrees + self._excluded_subtrees = excluded_subtrees + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameConstraints): + return NotImplemented + + return ( + self.excluded_subtrees == other.excluded_subtrees + and self.permitted_subtrees == other.permitted_subtrees + ) + + def _validate_tree(self, tree: Iterable[GeneralName]) -> None: + self._validate_ip_name(tree) + self._validate_dns_name(tree) + + def _validate_ip_name(self, tree: Iterable[GeneralName]) -> None: + if any( + isinstance(name, IPAddress) + and not isinstance( + name.value, (ipaddress.IPv4Network, ipaddress.IPv6Network) + ) + for name in tree + ): + raise TypeError( + "IPAddress name constraints must be an IPv4Network or" + " IPv6Network object" + ) + + def _validate_dns_name(self, tree: Iterable[GeneralName]) -> None: + if any( + isinstance(name, DNSName) and "*" in name.value for name in tree + ): + raise ValueError( + "DNSName name constraints must not contain the '*' wildcard" + " character" + ) + + def __repr__(self) -> str: + return ( + f"" + ) + + def __hash__(self) -> int: + if self.permitted_subtrees is not None: + ps: tuple[GeneralName, ...] | None = tuple(self.permitted_subtrees) + else: + ps = None + + if self.excluded_subtrees is not None: + es: tuple[GeneralName, ...] | None = tuple(self.excluded_subtrees) + else: + es = None + + return hash((ps, es)) + + @property + def permitted_subtrees( + self, + ) -> list[GeneralName] | None: + return self._permitted_subtrees + + @property + def excluded_subtrees( + self, + ) -> list[GeneralName] | None: + return self._excluded_subtrees + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class Extension(typing.Generic[ExtensionTypeVar]): + def __init__( + self, oid: ObjectIdentifier, critical: bool, value: ExtensionTypeVar + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + + if not isinstance(critical, bool): + raise TypeError("critical must be a boolean value") + + self._oid = oid + self._critical = critical + self._value = value + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def critical(self) -> bool: + return self._critical + + @property + def value(self) -> ExtensionTypeVar: + return self._value + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Extension): + return NotImplemented + + return ( + self.oid == other.oid + and self.critical == other.critical + and self.value == other.value + ) + + def __hash__(self) -> int: + return hash((self.oid, self.critical, self.value)) + + +class GeneralNames: + def __init__(self, general_names: Iterable[GeneralName]) -> None: + general_names = list(general_names) + if not all(isinstance(x, GeneralName) for x in general_names): + raise TypeError( + "Every item in the general_names list must be an " + "object conforming to the GeneralName interface" + ) + + self._general_names = general_names + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + # Return the value of each GeneralName, except for OtherName instances + # which we return directly because it has two important properties not + # just one value. + objs = (i for i in self if isinstance(i, type)) + if type != OtherName: + return [i.value for i in objs] + return list(objs) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, GeneralNames): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(tuple(self._general_names)) + + +class SubjectAlternativeName(ExtensionType): + oid = ExtensionOID.SUBJECT_ALTERNATIVE_NAME + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SubjectAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuerAlternativeName(ExtensionType): + oid = ExtensionOID.ISSUER_ALTERNATIVE_NAME + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuerAlternativeName): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CertificateIssuer(ExtensionType): + oid = CRLEntryExtensionOID.CERTIFICATE_ISSUER + + def __init__(self, general_names: Iterable[GeneralName]) -> None: + self._general_names = GeneralNames(general_names) + + __len__, __iter__, __getitem__ = _make_sequence_methods("_general_names") + + @typing.overload + def get_values_for_type( + self, + type: type[DNSName] + | type[UniformResourceIdentifier] + | type[RFC822Name], + ) -> list[str]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[DirectoryName], + ) -> list[Name]: ... + + @typing.overload + def get_values_for_type( + self, + type: type[RegisteredID], + ) -> list[ObjectIdentifier]: ... + + @typing.overload + def get_values_for_type( + self, type: type[IPAddress] + ) -> list[_IPAddressTypes]: ... + + @typing.overload + def get_values_for_type( + self, type: type[OtherName] + ) -> list[OtherName]: ... + + def get_values_for_type( + self, + type: type[DNSName] + | type[DirectoryName] + | type[IPAddress] + | type[OtherName] + | type[RFC822Name] + | type[RegisteredID] + | type[UniformResourceIdentifier], + ) -> ( + list[_IPAddressTypes] + | list[str] + | list[OtherName] + | list[Name] + | list[ObjectIdentifier] + ): + return self._general_names.get_values_for_type(type) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CertificateIssuer): + return NotImplemented + + return self._general_names == other._general_names + + def __hash__(self) -> int: + return hash(self._general_names) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class CRLReason(ExtensionType): + oid = CRLEntryExtensionOID.CRL_REASON + + def __init__(self, reason: ReasonFlags) -> None: + if not isinstance(reason, ReasonFlags): + raise TypeError("reason must be an element from ReasonFlags") + + self._reason = reason + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, CRLReason): + return NotImplemented + + return self.reason == other.reason + + def __hash__(self) -> int: + return hash(self.reason) + + @property + def reason(self) -> ReasonFlags: + return self._reason + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class InvalidityDate(ExtensionType): + oid = CRLEntryExtensionOID.INVALIDITY_DATE + + def __init__(self, invalidity_date: datetime.datetime) -> None: + if not isinstance(invalidity_date, datetime.datetime): + raise TypeError("invalidity_date must be a datetime.datetime") + + self._invalidity_date = invalidity_date + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, InvalidityDate): + return NotImplemented + + return self.invalidity_date == other.invalidity_date + + def __hash__(self) -> int: + return hash(self.invalidity_date) + + @property + def invalidity_date(self) -> datetime.datetime: + return self._invalidity_date + + @property + def invalidity_date_utc(self) -> datetime.datetime: + if self._invalidity_date.tzinfo is None: + return self._invalidity_date.replace(tzinfo=datetime.timezone.utc) + else: + return self._invalidity_date.astimezone(tz=datetime.timezone.utc) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class PrecertificateSignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.PRECERT_SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, PrecertificateSignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class SignedCertificateTimestamps(ExtensionType): + oid = ExtensionOID.SIGNED_CERTIFICATE_TIMESTAMPS + + def __init__( + self, + signed_certificate_timestamps: Iterable[SignedCertificateTimestamp], + ) -> None: + signed_certificate_timestamps = list(signed_certificate_timestamps) + if not all( + isinstance(sct, SignedCertificateTimestamp) + for sct in signed_certificate_timestamps + ): + raise TypeError( + "Every item in the signed_certificate_timestamps list must be " + "a SignedCertificateTimestamp" + ) + self._signed_certificate_timestamps = signed_certificate_timestamps + + __len__, __iter__, __getitem__ = _make_sequence_methods( + "_signed_certificate_timestamps" + ) + + def __repr__(self) -> str: + return f"" + + def __hash__(self) -> int: + return hash(tuple(self._signed_certificate_timestamps)) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, SignedCertificateTimestamps): + return NotImplemented + + return ( + self._signed_certificate_timestamps + == other._signed_certificate_timestamps + ) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPNonce(ExtensionType): + oid = OCSPExtensionOID.NONCE + + def __init__(self, nonce: bytes) -> None: + if not isinstance(nonce, bytes): + raise TypeError("nonce must be bytes") + + self._nonce = nonce + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPNonce): + return NotImplemented + + return self.nonce == other.nonce + + def __hash__(self) -> int: + return hash(self.nonce) + + def __repr__(self) -> str: + return f"" + + @property + def nonce(self) -> bytes: + return self._nonce + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class OCSPAcceptableResponses(ExtensionType): + oid = OCSPExtensionOID.ACCEPTABLE_RESPONSES + + def __init__(self, responses: Iterable[ObjectIdentifier]) -> None: + responses = list(responses) + if any(not isinstance(r, ObjectIdentifier) for r in responses): + raise TypeError("All responses must be ObjectIdentifiers") + + self._responses = responses + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OCSPAcceptableResponses): + return NotImplemented + + return self._responses == other._responses + + def __hash__(self) -> int: + return hash(tuple(self._responses)) + + def __repr__(self) -> str: + return f"" + + def __iter__(self) -> Iterator[ObjectIdentifier]: + return iter(self._responses) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class IssuingDistributionPoint(ExtensionType): + oid = ExtensionOID.ISSUING_DISTRIBUTION_POINT + + def __init__( + self, + full_name: Iterable[GeneralName] | None, + relative_name: RelativeDistinguishedName | None, + only_contains_user_certs: bool, + only_contains_ca_certs: bool, + only_some_reasons: frozenset[ReasonFlags] | None, + indirect_crl: bool, + only_contains_attribute_certs: bool, + ) -> None: + if full_name is not None: + full_name = list(full_name) + + if only_some_reasons and ( + not isinstance(only_some_reasons, frozenset) + or not all(isinstance(x, ReasonFlags) for x in only_some_reasons) + ): + raise TypeError( + "only_some_reasons must be None or frozenset of ReasonFlags" + ) + + if only_some_reasons and ( + ReasonFlags.unspecified in only_some_reasons + or ReasonFlags.remove_from_crl in only_some_reasons + ): + raise ValueError( + "unspecified and remove_from_crl are not valid reasons in an " + "IssuingDistributionPoint" + ) + + if not ( + isinstance(only_contains_user_certs, bool) + and isinstance(only_contains_ca_certs, bool) + and isinstance(indirect_crl, bool) + and isinstance(only_contains_attribute_certs, bool) + ): + raise TypeError( + "only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl and only_contains_attribute_certs " + "must all be boolean." + ) + + # Per RFC5280 Section 5.2.5, the Issuing Distribution Point extension + # in a CRL can have only one of onlyContainsUserCerts, + # onlyContainsCACerts, onlyContainsAttributeCerts set to TRUE. + crl_constraints = [ + only_contains_user_certs, + only_contains_ca_certs, + only_contains_attribute_certs, + ] + + if len([x for x in crl_constraints if x]) > 1: + raise ValueError( + "Only one of the following can be set to True: " + "only_contains_user_certs, only_contains_ca_certs, " + "only_contains_attribute_certs" + ) + + if not any( + [ + only_contains_user_certs, + only_contains_ca_certs, + indirect_crl, + only_contains_attribute_certs, + full_name, + relative_name, + only_some_reasons, + ] + ): + raise ValueError( + "Cannot create empty extension: " + "if only_contains_user_certs, only_contains_ca_certs, " + "indirect_crl, and only_contains_attribute_certs are all False" + ", then either full_name, relative_name, or only_some_reasons " + "must have a value." + ) + + self._only_contains_user_certs = only_contains_user_certs + self._only_contains_ca_certs = only_contains_ca_certs + self._indirect_crl = indirect_crl + self._only_contains_attribute_certs = only_contains_attribute_certs + self._only_some_reasons = only_some_reasons + self._full_name = full_name + self._relative_name = relative_name + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IssuingDistributionPoint): + return NotImplemented + + return ( + self.full_name == other.full_name + and self.relative_name == other.relative_name + and self.only_contains_user_certs == other.only_contains_user_certs + and self.only_contains_ca_certs == other.only_contains_ca_certs + and self.only_some_reasons == other.only_some_reasons + and self.indirect_crl == other.indirect_crl + and self.only_contains_attribute_certs + == other.only_contains_attribute_certs + ) + + def __hash__(self) -> int: + return hash( + ( + self.full_name, + self.relative_name, + self.only_contains_user_certs, + self.only_contains_ca_certs, + self.only_some_reasons, + self.indirect_crl, + self.only_contains_attribute_certs, + ) + ) + + @property + def full_name(self) -> list[GeneralName] | None: + return self._full_name + + @property + def relative_name(self) -> RelativeDistinguishedName | None: + return self._relative_name + + @property + def only_contains_user_certs(self) -> bool: + return self._only_contains_user_certs + + @property + def only_contains_ca_certs(self) -> bool: + return self._only_contains_ca_certs + + @property + def only_some_reasons( + self, + ) -> frozenset[ReasonFlags] | None: + return self._only_some_reasons + + @property + def indirect_crl(self) -> bool: + return self._indirect_crl + + @property + def only_contains_attribute_certs(self) -> bool: + return self._only_contains_attribute_certs + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class MSCertificateTemplate(ExtensionType): + oid = ExtensionOID.MS_CERTIFICATE_TEMPLATE + + def __init__( + self, + template_id: ObjectIdentifier, + major_version: int | None, + minor_version: int | None, + ) -> None: + if not isinstance(template_id, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._template_id = template_id + if ( + major_version is not None and not isinstance(major_version, int) + ) or ( + minor_version is not None and not isinstance(minor_version, int) + ): + raise TypeError( + "major_version and minor_version must be integers or None" + ) + self._major_version = major_version + self._minor_version = minor_version + + @property + def template_id(self) -> ObjectIdentifier: + return self._template_id + + @property + def major_version(self) -> int | None: + return self._major_version + + @property + def minor_version(self) -> int | None: + return self._minor_version + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, MSCertificateTemplate): + return NotImplemented + + return ( + self.template_id == other.template_id + and self.major_version == other.major_version + and self.minor_version == other.minor_version + ) + + def __hash__(self) -> int: + return hash((self.template_id, self.major_version, self.minor_version)) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class NamingAuthority: + def __init__( + self, + id: ObjectIdentifier | None, + url: str | None, + text: str | None, + ) -> None: + if id is not None and not isinstance(id, ObjectIdentifier): + raise TypeError("id must be an ObjectIdentifier") + + if url is not None and not isinstance(url, str): + raise TypeError("url must be a str") + + if text is not None and not isinstance(text, str): + raise TypeError("text must be a str") + + self._id = id + self._url = url + self._text = text + + @property + def id(self) -> ObjectIdentifier | None: + return self._id + + @property + def url(self) -> str | None: + return self._url + + @property + def text(self) -> str | None: + return self._text + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NamingAuthority): + return NotImplemented + + return ( + self.id == other.id + and self.url == other.url + and self.text == other.text + ) + + def __hash__(self) -> int: + return hash( + ( + self.id, + self.url, + self.text, + ) + ) + + +class ProfessionInfo: + def __init__( + self, + naming_authority: NamingAuthority | None, + profession_items: Iterable[str], + profession_oids: Iterable[ObjectIdentifier] | None, + registration_number: str | None, + add_profession_info: bytes | None, + ) -> None: + if naming_authority is not None and not isinstance( + naming_authority, NamingAuthority + ): + raise TypeError("naming_authority must be a NamingAuthority") + + profession_items = list(profession_items) + if not all(isinstance(item, str) for item in profession_items): + raise TypeError( + "Every item in the profession_items list must be a str" + ) + + if profession_oids is not None: + profession_oids = list(profession_oids) + if not all( + isinstance(oid, ObjectIdentifier) for oid in profession_oids + ): + raise TypeError( + "Every item in the profession_oids list must be an " + "ObjectIdentifier" + ) + + if registration_number is not None and not isinstance( + registration_number, str + ): + raise TypeError("registration_number must be a str") + + if add_profession_info is not None and not isinstance( + add_profession_info, bytes + ): + raise TypeError("add_profession_info must be bytes") + + self._naming_authority = naming_authority + self._profession_items = profession_items + self._profession_oids = profession_oids + self._registration_number = registration_number + self._add_profession_info = add_profession_info + + @property + def naming_authority(self) -> NamingAuthority | None: + return self._naming_authority + + @property + def profession_items(self) -> list[str]: + return self._profession_items + + @property + def profession_oids(self) -> list[ObjectIdentifier] | None: + return self._profession_oids + + @property + def registration_number(self) -> str | None: + return self._registration_number + + @property + def add_profession_info(self) -> bytes | None: + return self._add_profession_info + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, ProfessionInfo): + return NotImplemented + + return ( + self.naming_authority == other.naming_authority + and self.profession_items == other.profession_items + and self.profession_oids == other.profession_oids + and self.registration_number == other.registration_number + and self.add_profession_info == other.add_profession_info + ) + + def __hash__(self) -> int: + if self.profession_oids is not None: + profession_oids = tuple(self.profession_oids) + else: + profession_oids = None + return hash( + ( + self.naming_authority, + tuple(self.profession_items), + profession_oids, + self.registration_number, + self.add_profession_info, + ) + ) + + +class Admission: + def __init__( + self, + admission_authority: GeneralName | None, + naming_authority: NamingAuthority | None, + profession_infos: Iterable[ProfessionInfo], + ) -> None: + if admission_authority is not None and not isinstance( + admission_authority, GeneralName + ): + raise TypeError("admission_authority must be a GeneralName") + + if naming_authority is not None and not isinstance( + naming_authority, NamingAuthority + ): + raise TypeError("naming_authority must be a NamingAuthority") + + profession_infos = list(profession_infos) + if not all( + isinstance(info, ProfessionInfo) for info in profession_infos + ): + raise TypeError( + "Every item in the profession_infos list must be a " + "ProfessionInfo" + ) + + self._admission_authority = admission_authority + self._naming_authority = naming_authority + self._profession_infos = profession_infos + + @property + def admission_authority(self) -> GeneralName | None: + return self._admission_authority + + @property + def naming_authority(self) -> NamingAuthority | None: + return self._naming_authority + + @property + def profession_infos(self) -> list[ProfessionInfo]: + return self._profession_infos + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Admission): + return NotImplemented + + return ( + self.admission_authority == other.admission_authority + and self.naming_authority == other.naming_authority + and self.profession_infos == other.profession_infos + ) + + def __hash__(self) -> int: + return hash( + ( + self.admission_authority, + self.naming_authority, + tuple(self.profession_infos), + ) + ) + + +class Admissions(ExtensionType): + oid = ExtensionOID.ADMISSIONS + + def __init__( + self, + authority: GeneralName | None, + admissions: Iterable[Admission], + ) -> None: + if authority is not None and not isinstance(authority, GeneralName): + raise TypeError("authority must be a GeneralName") + + admissions = list(admissions) + if not all( + isinstance(admission, Admission) for admission in admissions + ): + raise TypeError( + "Every item in the contents_of_admissions list must be an " + "Admission" + ) + + self._authority = authority + self._admissions = admissions + + __len__, __iter__, __getitem__ = _make_sequence_methods("_admissions") + + @property + def authority(self) -> GeneralName | None: + return self._authority + + def __repr__(self) -> str: + return ( + f"" + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Admissions): + return NotImplemented + + return ( + self.authority == other.authority + and self._admissions == other._admissions + ) + + def __hash__(self) -> int: + return hash((self.authority, tuple(self._admissions))) + + def public_bytes(self) -> bytes: + return rust_x509.encode_extension_value(self) + + +class UnrecognizedExtension(ExtensionType): + def __init__(self, oid: ObjectIdentifier, value: bytes) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError("oid must be an ObjectIdentifier") + self._oid = oid + self._value = value + + @property + def oid(self) -> ObjectIdentifier: # type: ignore[override] + return self._oid + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UnrecognizedExtension): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def public_bytes(self) -> bytes: + return self.value diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/general_name.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/general_name.py new file mode 100644 index 0000000000000000000000000000000000000000..672f28759cb0ab6d60cb4e38a574095ae3e0159d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/general_name.py @@ -0,0 +1,281 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import abc +import ipaddress +import typing +from email.utils import parseaddr + +from cryptography.x509.name import Name +from cryptography.x509.oid import ObjectIdentifier + +_IPAddressTypes = typing.Union[ + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, +] + + +class UnsupportedGeneralNameType(Exception): + pass + + +class GeneralName(metaclass=abc.ABCMeta): + @property + @abc.abstractmethod + def value(self) -> typing.Any: + """ + Return the value of the object + """ + + +class RFC822Name(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "RFC822Name values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + name, address = parseaddr(value) + if name or not address: + # parseaddr has found a name (e.g. Name ) or the entire + # value is an empty string. + raise ValueError("Invalid rfc822name value") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> RFC822Name: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RFC822Name): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DNSName(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "DNSName values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> DNSName: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DNSName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class UniformResourceIdentifier(GeneralName): + def __init__(self, value: str) -> None: + if isinstance(value, str): + try: + value.encode("ascii") + except UnicodeEncodeError: + raise ValueError( + "URI values should be passed as an A-label string. " + "This means unicode characters should be encoded via " + "a library like idna." + ) + else: + raise TypeError("value must be string") + + self._value = value + + @property + def value(self) -> str: + return self._value + + @classmethod + def _init_without_validation(cls, value: str) -> UniformResourceIdentifier: + instance = cls.__new__(cls) + instance._value = value + return instance + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, UniformResourceIdentifier): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class DirectoryName(GeneralName): + def __init__(self, value: Name) -> None: + if not isinstance(value, Name): + raise TypeError("value must be a Name") + + self._value = value + + @property + def value(self) -> Name: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, DirectoryName): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class RegisteredID(GeneralName): + def __init__(self, value: ObjectIdentifier) -> None: + if not isinstance(value, ObjectIdentifier): + raise TypeError("value must be an ObjectIdentifier") + + self._value = value + + @property + def value(self) -> ObjectIdentifier: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RegisteredID): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class IPAddress(GeneralName): + def __init__(self, value: _IPAddressTypes) -> None: + if not isinstance( + value, + ( + ipaddress.IPv4Address, + ipaddress.IPv6Address, + ipaddress.IPv4Network, + ipaddress.IPv6Network, + ), + ): + raise TypeError( + "value must be an instance of ipaddress.IPv4Address, " + "ipaddress.IPv6Address, ipaddress.IPv4Network, or " + "ipaddress.IPv6Network" + ) + + self._value = value + + @property + def value(self) -> _IPAddressTypes: + return self._value + + def _packed(self) -> bytes: + if isinstance( + self.value, (ipaddress.IPv4Address, ipaddress.IPv6Address) + ): + return self.value.packed + else: + return ( + self.value.network_address.packed + self.value.netmask.packed + ) + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, IPAddress): + return NotImplemented + + return self.value == other.value + + def __hash__(self) -> int: + return hash(self.value) + + +class OtherName(GeneralName): + def __init__(self, type_id: ObjectIdentifier, value: bytes) -> None: + if not isinstance(type_id, ObjectIdentifier): + raise TypeError("type_id must be an ObjectIdentifier") + if not isinstance(value, bytes): + raise TypeError("value must be a binary string") + + self._type_id = type_id + self._value = value + + @property + def type_id(self) -> ObjectIdentifier: + return self._type_id + + @property + def value(self) -> bytes: + return self._value + + def __repr__(self) -> str: + return f"" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, OtherName): + return NotImplemented + + return self.type_id == other.type_id and self.value == other.value + + def __hash__(self) -> int: + return hash((self.type_id, self.value)) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/name.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/name.py new file mode 100644 index 0000000000000000000000000000000000000000..685f921d7d0cf534dfda7f381541183d12d59203 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/name.py @@ -0,0 +1,476 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import binascii +import re +import sys +import typing +import warnings +from collections.abc import Iterable, Iterator + +from cryptography import utils +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.x509.oid import NameOID, ObjectIdentifier + + +class _ASN1Type(utils.Enum): + BitString = 3 + OctetString = 4 + UTF8String = 12 + NumericString = 18 + PrintableString = 19 + T61String = 20 + IA5String = 22 + UTCTime = 23 + GeneralizedTime = 24 + VisibleString = 26 + UniversalString = 28 + BMPString = 30 + + +_ASN1_TYPE_TO_ENUM = {i.value: i for i in _ASN1Type} +_NAMEOID_DEFAULT_TYPE: dict[ObjectIdentifier, _ASN1Type] = { + NameOID.COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.JURISDICTION_COUNTRY_NAME: _ASN1Type.PrintableString, + NameOID.SERIAL_NUMBER: _ASN1Type.PrintableString, + NameOID.DN_QUALIFIER: _ASN1Type.PrintableString, + NameOID.EMAIL_ADDRESS: _ASN1Type.IA5String, + NameOID.DOMAIN_COMPONENT: _ASN1Type.IA5String, +} + +# Type alias +_OidNameMap = typing.Mapping[ObjectIdentifier, str] +_NameOidMap = typing.Mapping[str, ObjectIdentifier] + +#: Short attribute names from RFC 4514: +#: https://tools.ietf.org/html/rfc4514#page-7 +_NAMEOID_TO_NAME: _OidNameMap = { + NameOID.COMMON_NAME: "CN", + NameOID.LOCALITY_NAME: "L", + NameOID.STATE_OR_PROVINCE_NAME: "ST", + NameOID.ORGANIZATION_NAME: "O", + NameOID.ORGANIZATIONAL_UNIT_NAME: "OU", + NameOID.COUNTRY_NAME: "C", + NameOID.STREET_ADDRESS: "STREET", + NameOID.DOMAIN_COMPONENT: "DC", + NameOID.USER_ID: "UID", +} +_NAME_TO_NAMEOID = {v: k for k, v in _NAMEOID_TO_NAME.items()} + +_NAMEOID_LENGTH_LIMIT = { + NameOID.COUNTRY_NAME: (2, 2), + NameOID.JURISDICTION_COUNTRY_NAME: (2, 2), + NameOID.COMMON_NAME: (1, 64), +} + + +def _escape_dn_value(val: str | bytes) -> str: + """Escape special characters in RFC4514 Distinguished Name value.""" + + if not val: + return "" + + # RFC 4514 Section 2.4 defines the value as being the # (U+0023) character + # followed by the hexadecimal encoding of the octets. + if isinstance(val, bytes): + return "#" + binascii.hexlify(val).decode("utf8") + + # See https://tools.ietf.org/html/rfc4514#section-2.4 + val = val.replace("\\", "\\\\") + val = val.replace('"', '\\"') + val = val.replace("+", "\\+") + val = val.replace(",", "\\,") + val = val.replace(";", "\\;") + val = val.replace("<", "\\<") + val = val.replace(">", "\\>") + val = val.replace("\0", "\\00") + + if val[0] in ("#", " "): + val = "\\" + val + if val[-1] == " ": + val = val[:-1] + "\\ " + + return val + + +def _unescape_dn_value(val: str) -> str: + if not val: + return "" + + # See https://tools.ietf.org/html/rfc4514#section-3 + + # special = escaped / SPACE / SHARP / EQUALS + # escaped = DQUOTE / PLUS / COMMA / SEMI / LANGLE / RANGLE + def sub(m): + val = m.group(1) + # Regular escape + if len(val) == 1: + return val + # Hex-value scape + return chr(int(val, 16)) + + return _RFC4514NameParser._PAIR_RE.sub(sub, val) + + +NameAttributeValueType = typing.TypeVar( + "NameAttributeValueType", + typing.Union[str, bytes], + str, + bytes, + covariant=True, +) + + +class NameAttribute(typing.Generic[NameAttributeValueType]): + def __init__( + self, + oid: ObjectIdentifier, + value: NameAttributeValueType, + _type: _ASN1Type | None = None, + *, + _validate: bool = True, + ) -> None: + if not isinstance(oid, ObjectIdentifier): + raise TypeError( + "oid argument must be an ObjectIdentifier instance." + ) + if _type == _ASN1Type.BitString: + if oid != NameOID.X500_UNIQUE_IDENTIFIER: + raise TypeError( + "oid must be X500_UNIQUE_IDENTIFIER for BitString type." + ) + if not isinstance(value, bytes): + raise TypeError("value must be bytes for BitString") + elif not isinstance(value, str): + raise TypeError("value argument must be a str") + + length_limits = _NAMEOID_LENGTH_LIMIT.get(oid) + if length_limits is not None: + min_length, max_length = length_limits + assert isinstance(value, str) + c_len = len(value.encode("utf8")) + if c_len < min_length or c_len > max_length: + msg = ( + f"Attribute's length must be >= {min_length} and " + f"<= {max_length}, but it was {c_len}" + ) + if _validate is True: + raise ValueError(msg) + else: + warnings.warn(msg, stacklevel=2) + + # The appropriate ASN1 string type varies by OID and is defined across + # multiple RFCs including 2459, 3280, and 5280. In general UTF8String + # is preferred (2459), but 3280 and 5280 specify several OIDs with + # alternate types. This means when we see the sentinel value we need + # to look up whether the OID has a non-UTF8 type. If it does, set it + # to that. Otherwise, UTF8! + if _type is None: + _type = _NAMEOID_DEFAULT_TYPE.get(oid, _ASN1Type.UTF8String) + + if not isinstance(_type, _ASN1Type): + raise TypeError("_type must be from the _ASN1Type enum") + + self._oid = oid + self._value: NameAttributeValueType = value + self._type: _ASN1Type = _type + + @property + def oid(self) -> ObjectIdentifier: + return self._oid + + @property + def value(self) -> NameAttributeValueType: + return self._value + + @property + def rfc4514_attribute_name(self) -> str: + """ + The short attribute name (for example "CN") if available, + otherwise the OID dotted string. + """ + return _NAMEOID_TO_NAME.get(self.oid, self.oid.dotted_string) + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Use short attribute name if available, otherwise fall back to OID + dotted string. + """ + attr_name = ( + attr_name_overrides.get(self.oid) if attr_name_overrides else None + ) + if attr_name is None: + attr_name = self.rfc4514_attribute_name + + return f"{attr_name}={_escape_dn_value(self.value)}" + + def __eq__(self, other: object) -> bool: + if not isinstance(other, NameAttribute): + return NotImplemented + + return self.oid == other.oid and self.value == other.value + + def __hash__(self) -> int: + return hash((self.oid, self.value)) + + def __repr__(self) -> str: + return f"" + + +class RelativeDistinguishedName: + def __init__(self, attributes: Iterable[NameAttribute]): + attributes = list(attributes) + if not attributes: + raise ValueError("a relative distinguished name cannot be empty") + if not all(isinstance(x, NameAttribute) for x in attributes): + raise TypeError("attributes must be an iterable of NameAttribute") + + # Keep list and frozenset to preserve attribute order where it matters + self._attributes = attributes + self._attribute_set = frozenset(attributes) + + if len(self._attribute_set) != len(attributes): + raise ValueError("duplicate attributes are not allowed") + + def get_attributes_for_oid( + self, + oid: ObjectIdentifier, + ) -> list[NameAttribute[str | bytes]]: + return [i for i in self if i.oid == oid] + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + + Within each RDN, attributes are joined by '+', although that is rarely + used in certificates. + """ + return "+".join( + attr.rfc4514_string(attr_name_overrides) + for attr in self._attributes + ) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, RelativeDistinguishedName): + return NotImplemented + + return self._attribute_set == other._attribute_set + + def __hash__(self) -> int: + return hash(self._attribute_set) + + def __iter__(self) -> Iterator[NameAttribute]: + return iter(self._attributes) + + def __len__(self) -> int: + return len(self._attributes) + + def __repr__(self) -> str: + return f"" + + +class Name: + @typing.overload + def __init__(self, attributes: Iterable[NameAttribute]) -> None: ... + + @typing.overload + def __init__( + self, attributes: Iterable[RelativeDistinguishedName] + ) -> None: ... + + def __init__( + self, + attributes: Iterable[NameAttribute | RelativeDistinguishedName], + ) -> None: + attributes = list(attributes) + if all(isinstance(x, NameAttribute) for x in attributes): + self._attributes = [ + RelativeDistinguishedName([typing.cast(NameAttribute, x)]) + for x in attributes + ] + elif all(isinstance(x, RelativeDistinguishedName) for x in attributes): + self._attributes = typing.cast( + typing.List[RelativeDistinguishedName], attributes + ) + else: + raise TypeError( + "attributes must be a list of NameAttribute" + " or a list RelativeDistinguishedName" + ) + + @classmethod + def from_rfc4514_string( + cls, + data: str, + attr_name_overrides: _NameOidMap | None = None, + ) -> Name: + return _RFC4514NameParser(data, attr_name_overrides or {}).parse() + + def rfc4514_string( + self, attr_name_overrides: _OidNameMap | None = None + ) -> str: + """ + Format as RFC4514 Distinguished Name string. + For example 'CN=foobar.com,O=Foo Corp,C=US' + + An X.509 name is a two-level structure: a list of sets of attributes. + Each list element is separated by ',' and within each list element, set + elements are separated by '+'. The latter is almost never used in + real world certificates. According to RFC4514 section 2.1 the + RDNSequence must be reversed when converting to string representation. + """ + return ",".join( + attr.rfc4514_string(attr_name_overrides) + for attr in reversed(self._attributes) + ) + + def get_attributes_for_oid( + self, + oid: ObjectIdentifier, + ) -> list[NameAttribute[str | bytes]]: + return [i for i in self if i.oid == oid] + + @property + def rdns(self) -> list[RelativeDistinguishedName]: + return self._attributes + + def public_bytes(self, backend: typing.Any = None) -> bytes: + return rust_x509.encode_name_bytes(self) + + def __eq__(self, other: object) -> bool: + if not isinstance(other, Name): + return NotImplemented + + return self._attributes == other._attributes + + def __hash__(self) -> int: + # TODO: this is relatively expensive, if this looks like a bottleneck + # for you, consider optimizing! + return hash(tuple(self._attributes)) + + def __iter__(self) -> Iterator[NameAttribute]: + for rdn in self._attributes: + yield from rdn + + def __len__(self) -> int: + return sum(len(rdn) for rdn in self._attributes) + + def __repr__(self) -> str: + rdns = ",".join(attr.rfc4514_string() for attr in self._attributes) + return f"" + + +class _RFC4514NameParser: + _OID_RE = re.compile(r"(0|([1-9]\d*))(\.(0|([1-9]\d*)))+") + _DESCR_RE = re.compile(r"[a-zA-Z][a-zA-Z\d-]*") + + _PAIR = r"\\([\\ #=\"\+,;<>]|[\da-zA-Z]{2})" + _PAIR_RE = re.compile(_PAIR) + _LUTF1 = r"[\x01-\x1f\x21\x24-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _SUTF1 = r"[\x01-\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _TUTF1 = r"[\x01-\x1F\x21\x23-\x2A\x2D-\x3A\x3D\x3F-\x5B\x5D-\x7F]" + _UTFMB = rf"[\x80-{chr(sys.maxunicode)}]" + _LEADCHAR = rf"{_LUTF1}|{_UTFMB}" + _STRINGCHAR = rf"{_SUTF1}|{_UTFMB}" + _TRAILCHAR = rf"{_TUTF1}|{_UTFMB}" + _STRING_RE = re.compile( + rf""" + ( + ({_LEADCHAR}|{_PAIR}) + ( + ({_STRINGCHAR}|{_PAIR})* + ({_TRAILCHAR}|{_PAIR}) + )? + )? + """, + re.VERBOSE, + ) + _HEXSTRING_RE = re.compile(r"#([\da-zA-Z]{2})+") + + def __init__(self, data: str, attr_name_overrides: _NameOidMap) -> None: + self._data = data + self._idx = 0 + + self._attr_name_overrides = attr_name_overrides + + def _has_data(self) -> bool: + return self._idx < len(self._data) + + def _peek(self) -> str | None: + if self._has_data(): + return self._data[self._idx] + return None + + def _read_char(self, ch: str) -> None: + if self._peek() != ch: + raise ValueError + self._idx += 1 + + def _read_re(self, pat) -> str: + match = pat.match(self._data, pos=self._idx) + if match is None: + raise ValueError + val = match.group() + self._idx += len(val) + return val + + def parse(self) -> Name: + """ + Parses the `data` string and converts it to a Name. + + According to RFC4514 section 2.1 the RDNSequence must be + reversed when converting to string representation. So, when + we parse it, we need to reverse again to get the RDNs on the + correct order. + """ + + if not self._has_data(): + return Name([]) + + rdns = [self._parse_rdn()] + + while self._has_data(): + self._read_char(",") + rdns.append(self._parse_rdn()) + + return Name(reversed(rdns)) + + def _parse_rdn(self) -> RelativeDistinguishedName: + nas = [self._parse_na()] + while self._peek() == "+": + self._read_char("+") + nas.append(self._parse_na()) + + return RelativeDistinguishedName(nas) + + def _parse_na(self) -> NameAttribute: + try: + oid_value = self._read_re(self._OID_RE) + except ValueError: + name = self._read_re(self._DESCR_RE) + oid = self._attr_name_overrides.get( + name, _NAME_TO_NAMEOID.get(name) + ) + if oid is None: + raise ValueError + else: + oid = ObjectIdentifier(oid_value) + + self._read_char("=") + if self._peek() == "#": + value = self._read_re(self._HEXSTRING_RE) + value = binascii.unhexlify(value[1:]).decode() + else: + raw_value = self._read_re(self._STRING_RE) + value = _unescape_dn_value(raw_value) + + return NameAttribute(oid, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/ocsp.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/ocsp.py new file mode 100644 index 0000000000000000000000000000000000000000..f61ed80b82bdea361b70d676a632f173368adc26 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/ocsp.py @@ -0,0 +1,379 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import datetime +from collections.abc import Iterable + +from cryptography import utils, x509 +from cryptography.hazmat.bindings._rust import ocsp +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric.types import ( + CertificateIssuerPrivateKeyTypes, +) +from cryptography.x509.base import _reject_duplicate_extension + + +class OCSPResponderEncoding(utils.Enum): + HASH = "By Hash" + NAME = "By Name" + + +class OCSPResponseStatus(utils.Enum): + SUCCESSFUL = 0 + MALFORMED_REQUEST = 1 + INTERNAL_ERROR = 2 + TRY_LATER = 3 + SIG_REQUIRED = 5 + UNAUTHORIZED = 6 + + +_ALLOWED_HASHES = ( + hashes.SHA1, + hashes.SHA224, + hashes.SHA256, + hashes.SHA384, + hashes.SHA512, +) + + +def _verify_algorithm(algorithm: hashes.HashAlgorithm) -> None: + if not isinstance(algorithm, _ALLOWED_HASHES): + raise ValueError( + "Algorithm must be SHA1, SHA224, SHA256, SHA384, or SHA512" + ) + + +class OCSPCertStatus(utils.Enum): + GOOD = 0 + REVOKED = 1 + UNKNOWN = 2 + + +class _SingleResponse: + def __init__( + self, + resp: tuple[x509.Certificate, x509.Certificate] | None, + resp_hash: tuple[bytes, bytes, int] | None, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ): + _verify_algorithm(algorithm) + if not isinstance(this_update, datetime.datetime): + raise TypeError("this_update must be a datetime object") + if next_update is not None and not isinstance( + next_update, datetime.datetime + ): + raise TypeError("next_update must be a datetime object or None") + + self._resp = resp + self._resp_hash = resp_hash + self._algorithm = algorithm + self._this_update = this_update + self._next_update = next_update + + if not isinstance(cert_status, OCSPCertStatus): + raise TypeError( + "cert_status must be an item from the OCSPCertStatus enum" + ) + if cert_status is not OCSPCertStatus.REVOKED: + if revocation_time is not None: + raise ValueError( + "revocation_time can only be provided if the certificate " + "is revoked" + ) + if revocation_reason is not None: + raise ValueError( + "revocation_reason can only be provided if the certificate" + " is revoked" + ) + else: + if not isinstance(revocation_time, datetime.datetime): + raise TypeError("revocation_time must be a datetime object") + + if revocation_reason is not None and not isinstance( + revocation_reason, x509.ReasonFlags + ): + raise TypeError( + "revocation_reason must be an item from the ReasonFlags " + "enum or None" + ) + + self._cert_status = cert_status + self._revocation_time = revocation_time + self._revocation_reason = revocation_reason + + +OCSPRequest = ocsp.OCSPRequest +OCSPResponse = ocsp.OCSPResponse +OCSPSingleResponse = ocsp.OCSPSingleResponse + + +class OCSPRequestBuilder: + def __init__( + self, + request: tuple[ + x509.Certificate, x509.Certificate, hashes.HashAlgorithm + ] + | None = None, + request_hash: tuple[bytes, bytes, int, hashes.HashAlgorithm] + | None = None, + extensions: list[x509.Extension[x509.ExtensionType]] = [], + ) -> None: + self._request = request + self._request_hash = request_hash + self._extensions = extensions + + def add_certificate( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + _verify_algorithm(algorithm) + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + return OCSPRequestBuilder( + (cert, issuer, algorithm), self._request_hash, self._extensions + ) + + def add_certificate_by_hash( + self, + issuer_name_hash: bytes, + issuer_key_hash: bytes, + serial_number: int, + algorithm: hashes.HashAlgorithm, + ) -> OCSPRequestBuilder: + if self._request is not None or self._request_hash is not None: + raise ValueError("Only one certificate can be added to a request") + + if not isinstance(serial_number, int): + raise TypeError("serial_number must be an integer") + + _verify_algorithm(algorithm) + utils._check_bytes("issuer_name_hash", issuer_name_hash) + utils._check_bytes("issuer_key_hash", issuer_key_hash) + if algorithm.digest_size != len( + issuer_name_hash + ) or algorithm.digest_size != len(issuer_key_hash): + raise ValueError( + "issuer_name_hash and issuer_key_hash must be the same length " + "as the digest size of the algorithm" + ) + + return OCSPRequestBuilder( + self._request, + (issuer_name_hash, issuer_key_hash, serial_number, algorithm), + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPRequestBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPRequestBuilder( + self._request, self._request_hash, [*self._extensions, extension] + ) + + def build(self) -> OCSPRequest: + if self._request is None and self._request_hash is None: + raise ValueError("You must add a certificate before building") + + return ocsp.create_ocsp_request(self) + + +class OCSPResponseBuilder: + def __init__( + self, + response: _SingleResponse | None = None, + responder_id: tuple[x509.Certificate, OCSPResponderEncoding] + | None = None, + certs: list[x509.Certificate] | None = None, + extensions: list[x509.Extension[x509.ExtensionType]] = [], + ): + self._response = response + self._responder_id = responder_id + self._certs = certs + self._extensions = extensions + + def add_response( + self, + cert: x509.Certificate, + issuer: x509.Certificate, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ) -> OCSPResponseBuilder: + if self._response is not None: + raise ValueError("Only one response per OCSPResponse.") + + if not isinstance(cert, x509.Certificate) or not isinstance( + issuer, x509.Certificate + ): + raise TypeError("cert and issuer must be a Certificate") + + singleresp = _SingleResponse( + (cert, issuer), + None, + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ) + return OCSPResponseBuilder( + singleresp, + self._responder_id, + self._certs, + self._extensions, + ) + + def add_response_by_hash( + self, + issuer_name_hash: bytes, + issuer_key_hash: bytes, + serial_number: int, + algorithm: hashes.HashAlgorithm, + cert_status: OCSPCertStatus, + this_update: datetime.datetime, + next_update: datetime.datetime | None, + revocation_time: datetime.datetime | None, + revocation_reason: x509.ReasonFlags | None, + ) -> OCSPResponseBuilder: + if self._response is not None: + raise ValueError("Only one response per OCSPResponse.") + + if not isinstance(serial_number, int): + raise TypeError("serial_number must be an integer") + + utils._check_bytes("issuer_name_hash", issuer_name_hash) + utils._check_bytes("issuer_key_hash", issuer_key_hash) + _verify_algorithm(algorithm) + if algorithm.digest_size != len( + issuer_name_hash + ) or algorithm.digest_size != len(issuer_key_hash): + raise ValueError( + "issuer_name_hash and issuer_key_hash must be the same length " + "as the digest size of the algorithm" + ) + + singleresp = _SingleResponse( + None, + (issuer_name_hash, issuer_key_hash, serial_number), + algorithm, + cert_status, + this_update, + next_update, + revocation_time, + revocation_reason, + ) + return OCSPResponseBuilder( + singleresp, + self._responder_id, + self._certs, + self._extensions, + ) + + def responder_id( + self, encoding: OCSPResponderEncoding, responder_cert: x509.Certificate + ) -> OCSPResponseBuilder: + if self._responder_id is not None: + raise ValueError("responder_id can only be set once") + if not isinstance(responder_cert, x509.Certificate): + raise TypeError("responder_cert must be a Certificate") + if not isinstance(encoding, OCSPResponderEncoding): + raise TypeError( + "encoding must be an element from OCSPResponderEncoding" + ) + + return OCSPResponseBuilder( + self._response, + (responder_cert, encoding), + self._certs, + self._extensions, + ) + + def certificates( + self, certs: Iterable[x509.Certificate] + ) -> OCSPResponseBuilder: + if self._certs is not None: + raise ValueError("certificates may only be set once") + certs = list(certs) + if len(certs) == 0: + raise ValueError("certs must not be an empty list") + if not all(isinstance(x, x509.Certificate) for x in certs): + raise TypeError("certs must be a list of Certificates") + return OCSPResponseBuilder( + self._response, + self._responder_id, + certs, + self._extensions, + ) + + def add_extension( + self, extval: x509.ExtensionType, critical: bool + ) -> OCSPResponseBuilder: + if not isinstance(extval, x509.ExtensionType): + raise TypeError("extension must be an ExtensionType") + + extension = x509.Extension(extval.oid, critical, extval) + _reject_duplicate_extension(extension, self._extensions) + + return OCSPResponseBuilder( + self._response, + self._responder_id, + self._certs, + [*self._extensions, extension], + ) + + def sign( + self, + private_key: CertificateIssuerPrivateKeyTypes, + algorithm: hashes.HashAlgorithm | None, + ) -> OCSPResponse: + if self._response is None: + raise ValueError("You must add a response before signing") + if self._responder_id is None: + raise ValueError("You must add a responder_id before signing") + + return ocsp.create_ocsp_response( + OCSPResponseStatus.SUCCESSFUL, self, private_key, algorithm + ) + + @classmethod + def build_unsuccessful( + cls, response_status: OCSPResponseStatus + ) -> OCSPResponse: + if not isinstance(response_status, OCSPResponseStatus): + raise TypeError( + "response_status must be an item from OCSPResponseStatus" + ) + if response_status is OCSPResponseStatus.SUCCESSFUL: + raise ValueError("response_status cannot be SUCCESSFUL") + + return ocsp.create_ocsp_response(response_status, None, None, None) + + +load_der_ocsp_request = ocsp.load_der_ocsp_request +load_der_ocsp_response = ocsp.load_der_ocsp_response diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/oid.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/oid.py new file mode 100644 index 0000000000000000000000000000000000000000..520fc7ab018c1b62132b957d332a83abef51b39e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/oid.py @@ -0,0 +1,37 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +from cryptography.hazmat._oid import ( + AttributeOID, + AuthorityInformationAccessOID, + CertificatePoliciesOID, + CRLEntryExtensionOID, + ExtendedKeyUsageOID, + ExtensionOID, + NameOID, + ObjectIdentifier, + OCSPExtensionOID, + OtherNameFormOID, + PublicKeyAlgorithmOID, + SignatureAlgorithmOID, + SubjectInformationAccessOID, +) + +__all__ = [ + "AttributeOID", + "AuthorityInformationAccessOID", + "CRLEntryExtensionOID", + "CertificatePoliciesOID", + "ExtendedKeyUsageOID", + "ExtensionOID", + "NameOID", + "OCSPExtensionOID", + "ObjectIdentifier", + "OtherNameFormOID", + "PublicKeyAlgorithmOID", + "SignatureAlgorithmOID", + "SubjectInformationAccessOID", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/verification.py b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/verification.py new file mode 100644 index 0000000000000000000000000000000000000000..2db4324d9615fb0d4dce6cd4dc5a9b55f4e28745 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/cryptography/x509/verification.py @@ -0,0 +1,34 @@ +# This file is dual licensed under the terms of the Apache License, Version +# 2.0, and the BSD License. See the LICENSE file in the root of this repository +# for complete details. + +from __future__ import annotations + +import typing + +from cryptography.hazmat.bindings._rust import x509 as rust_x509 +from cryptography.x509.general_name import DNSName, IPAddress + +__all__ = [ + "ClientVerifier", + "Criticality", + "ExtensionPolicy", + "Policy", + "PolicyBuilder", + "ServerVerifier", + "Store", + "Subject", + "VerificationError", + "VerifiedClient", +] + +Store = rust_x509.Store +Subject = typing.Union[DNSName, IPAddress] +VerifiedClient = rust_x509.VerifiedClient +ClientVerifier = rust_x509.ClientVerifier +ServerVerifier = rust_x509.ServerVerifier +PolicyBuilder = rust_x509.PolicyBuilder +Policy = rust_x509.Policy +ExtensionPolicy = rust_x509.ExtensionPolicy +Criticality = rust_x509.Criticality +VerificationError = rust_x509.VerificationError diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/licenses/LICENSE.txt b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a041280bd00a9d068f503b8ee7ce35214bd24a1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/frozendict-2.4.6.dist-info/licenses/LICENSE.txt @@ -0,0 +1,165 @@ + GNU LESSER GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + + This version of the GNU Lesser General Public License incorporates +the terms and conditions of version 3 of the GNU General Public +License, supplemented by the additional permissions listed below. + + 0. Additional Definitions. + + As used herein, "this License" refers to version 3 of the GNU Lesser +General Public License, and the "GNU GPL" refers to version 3 of the GNU +General Public License. + + "The Library" refers to a covered work governed by this License, +other than an Application or a Combined Work as defined below. + + An "Application" is any work that makes use of an interface provided +by the Library, but which is not otherwise based on the Library. +Defining a subclass of a class defined by the Library is deemed a mode +of using an interface provided by the Library. + + A "Combined Work" is a work produced by combining or linking an +Application with the Library. The particular version of the Library +with which the Combined Work was made is also called the "Linked +Version". + + The "Minimal Corresponding Source" for a Combined Work means the +Corresponding Source for the Combined Work, excluding any source code +for portions of the Combined Work that, considered in isolation, are +based on the Application, and not on the Linked Version. + + The "Corresponding Application Code" for a Combined Work means the +object code and/or source code for the Application, including any data +and utility programs needed for reproducing the Combined Work from the +Application, but excluding the System Libraries of the Combined Work. + + 1. Exception to Section 3 of the GNU GPL. + + You may convey a covered work under sections 3 and 4 of this License +without being bound by section 3 of the GNU GPL. + + 2. Conveying Modified Versions. + + If you modify a copy of the Library, and, in your modifications, a +facility refers to a function or data to be supplied by an Application +that uses the facility (other than as an argument passed when the +facility is invoked), then you may convey a copy of the modified +version: + + a) under this License, provided that you make a good faith effort to + ensure that, in the event an Application does not supply the + function or data, the facility still operates, and performs + whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of + this License applicable to that copy. + + 3. Object Code Incorporating Material from Library Header Files. + + The object code form of an Application may incorporate material from +a header file that is part of the Library. You may convey such object +code under terms of your choice, provided that, if the incorporated +material is not limited to numerical parameters, data structure +layouts and accessors, or small macros, inline functions and templates +(ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the + Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license + document. + + 4. Combined Works. + + You may convey a Combined Work under terms of your choice that, +taken together, effectively do not restrict modification of the +portions of the Library contained in the Combined Work and reverse +engineering for debugging such modifications, if you also do each of +the following: + + a) Give prominent notice with each copy of the Combined Work that + the Library is used in it and that the Library and its use are + covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license + document. + + c) For a Combined Work that displays copyright notices during + execution, include the copyright notice for the Library among + these notices, as well as a reference directing the user to the + copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this + License, and the Corresponding Application Code in a form + suitable for, and under terms that permit, the user to + recombine or relink the Application with a modified version of + the Linked Version to produce a modified Combined Work, in the + manner specified by section 6 of the GNU GPL for conveying + Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the + Library. A suitable mechanism is one that (a) uses at run time + a copy of the Library already present on the user's computer + system, and (b) will operate properly with a modified version + of the Library that is interface-compatible with the Linked + Version. + + e) Provide Installation Information, but only if you would otherwise + be required to provide such information under section 6 of the + GNU GPL, and only to the extent that such information is + necessary to install and execute a modified version of the + Combined Work produced by recombining or relinking the + Application with a modified version of the Linked Version. (If + you use option 4d0, the Installation Information must accompany + the Minimal Corresponding Source and Corresponding Application + Code. If you use option 4d1, you must provide the Installation + Information in the manner specified by section 6 of the GNU GPL + for conveying Corresponding Source.) + + 5. Combined Libraries. + + You may place library facilities that are a work based on the +Library side by side in a single library together with other library +facilities that are not Applications and are not covered by this +License, and convey such a combined library under terms of your +choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based + on the Library, uncombined with any other library facilities, + conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it + is a work based on the Library, and explaining where to find the + accompanying uncombined form of the same work. + + 6. Revised Versions of the GNU Lesser General Public License. + + The Free Software Foundation may publish revised and/or new versions +of the GNU Lesser General Public License from time to time. Such new +versions will be similar in spirit to the present version, but may +differ in detail to address new problems or concerns. + + Each version is given a distinguishing version number. If the +Library as you received it specifies that a certain numbered version +of the GNU Lesser General Public License "or any later version" +applies to it, you have the option of following the terms and +conditions either of that published version or of any later version +published by the Free Software Foundation. If the Library as you +received it does not specify a version number of the GNU Lesser +General Public License, you may choose any version of the GNU Lesser +General Public License ever published by the Free Software Foundation. + + If the Library as you received it specifies that a proxy can decide +whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is +permanent authorization for you to choose that version for the +Library. diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7260530db27b53f1e2e7a0d7d3984905c6d3f631 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/_frozendict_py.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/_frozendict_py.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d9a2a8c44e6be6ca8a218e475939526b7255609 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/_frozendict_py.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/cool.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/cool.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6eb991b9febc85590668c816a83f0ee53267c7ae Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/cool.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/core.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cde7f24f3e3e2bc94d8a644fe5d2558c25dac117 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/core.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/monkeypatch.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/monkeypatch.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..434c3037127e569154b9b4e380a62777ff0fd509 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/monkeypatch.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4754eeb8495168c55377f5994ed8c6e0b017c703 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/frozendict/__pycache__/version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..94ec0762d66b40d63b489303e4be7cffa376fa8a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__version__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__version__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d02b9dc13fac977fab10fcaf048b6e69c6a195c0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/__version__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_api.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3c3a9fb5ae285a330ee563838a7e7f25f42e40f1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_api.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_auth.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c8c4fce04e1518b79c91958aa424590fa0cb59e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_auth.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1231af1be9de1e7fdcb555d015b8037d0333bdfc Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_config.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_config.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..226508c03abcf0d4a39fccef8053efb4abbf5735 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_config.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_content.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_content.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..39fdd32c9f3e8daaf3014112ea9fe435ad349c2e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_content.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_decoders.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_decoders.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d96e9ef19ac15547f7a33dc3d336eb30c3083dd Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_decoders.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63e1f1cc56126b328ad22f38b7c087987e4f7769 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_main.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7414b599de4d1b7377f3881d186f3a5670d2472d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_main.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_models.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_models.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..40516f3adb9c6d6aff6584ad05b931dae33bd98a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_models.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_multipart.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_multipart.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9082f1aa1d4da5172b8b8418b92db86475ab2cd1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_multipart.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_status_codes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_status_codes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..df046035a43d88852c26329df2aaf434caa1fc7c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_status_codes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_types.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1fdffc054a41287c60a1600f84580adde5581f1a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_types.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urlparse.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urlparse.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48372e2622cd95de3fb87352554f410188dcf2ff Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urlparse.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urls.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urls.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..469ffa52bdd5f9d1e3117881702d3c6a6e8b83d8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_urls.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..98f3131f59aaa4da6773931748670d8b8b91f497 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/__pycache__/_utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__init__.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7a321053b29bcd48698cf2bd74a1d19c8556aefb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__init__.py @@ -0,0 +1,15 @@ +from .asgi import * +from .base import * +from .default import * +from .mock import * +from .wsgi import * + +__all__ = [ + "ASGITransport", + "AsyncBaseTransport", + "BaseTransport", + "AsyncHTTPTransport", + "HTTPTransport", + "MockTransport", + "WSGITransport", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9fe80dde2ffa6ade4c3e2f34d9bc85cbb99b957 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/asgi.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/asgi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dc9c71fb926ab8ae05f3a92dd84ca47898178793 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/asgi.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9900052afc183ba4df7bf17b2fbb12a113041063 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/default.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/default.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..894811695fe4ee17a8e09183664fda08e2f96e56 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/default.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/mock.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/mock.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1be0653f4a861a8282ce1ff725c0e166ae36b73f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/mock.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/wsgi.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/wsgi.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d5f1d7b82a46ad90f84fe3027e4e06aa65e1d637 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/__pycache__/wsgi.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/asgi.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/asgi.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc4efae0e1b14620f75f712eb15ecf500d14eef --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/asgi.py @@ -0,0 +1,187 @@ +from __future__ import annotations + +import typing + +from .._models import Request, Response +from .._types import AsyncByteStream +from .base import AsyncBaseTransport + +if typing.TYPE_CHECKING: # pragma: no cover + import asyncio + + import trio + + Event = typing.Union[asyncio.Event, trio.Event] + + +_Message = typing.MutableMapping[str, typing.Any] +_Receive = typing.Callable[[], typing.Awaitable[_Message]] +_Send = typing.Callable[ + [typing.MutableMapping[str, typing.Any]], typing.Awaitable[None] +] +_ASGIApp = typing.Callable[ + [typing.MutableMapping[str, typing.Any], _Receive, _Send], typing.Awaitable[None] +] + +__all__ = ["ASGITransport"] + + +def is_running_trio() -> bool: + try: + # sniffio is a dependency of trio. + + # See https://github.com/python-trio/trio/issues/2802 + import sniffio + + if sniffio.current_async_library() == "trio": + return True + except ImportError: # pragma: nocover + pass + + return False + + +def create_event() -> Event: + if is_running_trio(): + import trio + + return trio.Event() + + import asyncio + + return asyncio.Event() + + +class ASGIResponseStream(AsyncByteStream): + def __init__(self, body: list[bytes]) -> None: + self._body = body + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + yield b"".join(self._body) + + +class ASGITransport(AsyncBaseTransport): + """ + A custom AsyncTransport that handles sending requests directly to an ASGI app. + + ```python + transport = httpx.ASGITransport( + app=app, + root_path="/submount", + client=("1.2.3.4", 123) + ) + client = httpx.AsyncClient(transport=transport) + ``` + + Arguments: + + * `app` - The ASGI application. + * `raise_app_exceptions` - Boolean indicating if exceptions in the application + should be raised. Default to `True`. Can be set to `False` for use cases + such as testing the content of a client 500 response. + * `root_path` - The root path on which the ASGI application should be mounted. + * `client` - A two-tuple indicating the client IP and port of incoming requests. + ``` + """ + + def __init__( + self, + app: _ASGIApp, + raise_app_exceptions: bool = True, + root_path: str = "", + client: tuple[str, int] = ("127.0.0.1", 123), + ) -> None: + self.app = app + self.raise_app_exceptions = raise_app_exceptions + self.root_path = root_path + self.client = client + + async def handle_async_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, AsyncByteStream) + + # ASGI scope. + scope = { + "type": "http", + "asgi": {"version": "3.0"}, + "http_version": "1.1", + "method": request.method, + "headers": [(k.lower(), v) for (k, v) in request.headers.raw], + "scheme": request.url.scheme, + "path": request.url.path, + "raw_path": request.url.raw_path.split(b"?")[0], + "query_string": request.url.query, + "server": (request.url.host, request.url.port), + "client": self.client, + "root_path": self.root_path, + } + + # Request. + request_body_chunks = request.stream.__aiter__() + request_complete = False + + # Response. + status_code = None + response_headers = None + body_parts = [] + response_started = False + response_complete = create_event() + + # ASGI callables. + + async def receive() -> dict[str, typing.Any]: + nonlocal request_complete + + if request_complete: + await response_complete.wait() + return {"type": "http.disconnect"} + + try: + body = await request_body_chunks.__anext__() + except StopAsyncIteration: + request_complete = True + return {"type": "http.request", "body": b"", "more_body": False} + return {"type": "http.request", "body": body, "more_body": True} + + async def send(message: typing.MutableMapping[str, typing.Any]) -> None: + nonlocal status_code, response_headers, response_started + + if message["type"] == "http.response.start": + assert not response_started + + status_code = message["status"] + response_headers = message.get("headers", []) + response_started = True + + elif message["type"] == "http.response.body": + assert not response_complete.is_set() + body = message.get("body", b"") + more_body = message.get("more_body", False) + + if body and request.method != "HEAD": + body_parts.append(body) + + if not more_body: + response_complete.set() + + try: + await self.app(scope, receive, send) + except Exception: # noqa: PIE-786 + if self.raise_app_exceptions: + raise + + response_complete.set() + if status_code is None: + status_code = 500 + if response_headers is None: + response_headers = {} + + assert response_complete.is_set() + assert status_code is not None + assert response_headers is not None + + stream = ASGIResponseStream(body_parts) + + return Response(status_code, headers=response_headers, stream=stream) diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/base.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/base.py new file mode 100644 index 0000000000000000000000000000000000000000..66fd99d702480b555c06694fe14715ea6df3dfc3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/base.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import typing +from types import TracebackType + +from .._models import Request, Response + +T = typing.TypeVar("T", bound="BaseTransport") +A = typing.TypeVar("A", bound="AsyncBaseTransport") + +__all__ = ["AsyncBaseTransport", "BaseTransport"] + + +class BaseTransport: + def __enter__(self: T) -> T: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + self.close() + + def handle_request(self, request: Request) -> Response: + """ + Send a single HTTP request and return a response. + + Developers shouldn't typically ever need to call into this API directly, + since the Client class provides all the higher level user-facing API + niceties. + + In order to properly release any network resources, the response + stream should *either* be consumed immediately, with a call to + `response.stream.read()`, or else the `handle_request` call should + be followed with a try/finally block to ensuring the stream is + always closed. + + Example usage: + + with httpx.HTTPTransport() as transport: + req = httpx.Request( + method=b"GET", + url=(b"https", b"www.example.com", 443, b"/"), + headers=[(b"Host", b"www.example.com")], + ) + resp = transport.handle_request(req) + body = resp.stream.read() + print(resp.status_code, resp.headers, body) + + + Takes a `Request` instance as the only argument. + + Returns a `Response` instance. + """ + raise NotImplementedError( + "The 'handle_request' method must be implemented." + ) # pragma: no cover + + def close(self) -> None: + pass + + +class AsyncBaseTransport: + async def __aenter__(self: A) -> A: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + await self.aclose() + + async def handle_async_request( + self, + request: Request, + ) -> Response: + raise NotImplementedError( + "The 'handle_async_request' method must be implemented." + ) # pragma: no cover + + async def aclose(self) -> None: + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/default.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/default.py new file mode 100644 index 0000000000000000000000000000000000000000..d5aa05ff234fd3fbf4fee88c4a7d3e3c151a538f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/default.py @@ -0,0 +1,406 @@ +""" +Custom transports, with nicely configured defaults. + +The following additional keyword arguments are currently supported by httpcore... + +* uds: str +* local_address: str +* retries: int + +Example usages... + +# Disable HTTP/2 on a single specific domain. +mounts = { + "all://": httpx.HTTPTransport(http2=True), + "all://*example.org": httpx.HTTPTransport() +} + +# Using advanced httpcore configuration, with connection retries. +transport = httpx.HTTPTransport(retries=1) +client = httpx.Client(transport=transport) + +# Using advanced httpcore configuration, with unix domain sockets. +transport = httpx.HTTPTransport(uds="socket.uds") +client = httpx.Client(transport=transport) +""" + +from __future__ import annotations + +import contextlib +import typing +from types import TracebackType + +if typing.TYPE_CHECKING: + import ssl # pragma: no cover + + import httpx # pragma: no cover + +from .._config import DEFAULT_LIMITS, Limits, Proxy, create_ssl_context +from .._exceptions import ( + ConnectError, + ConnectTimeout, + LocalProtocolError, + NetworkError, + PoolTimeout, + ProtocolError, + ProxyError, + ReadError, + ReadTimeout, + RemoteProtocolError, + TimeoutException, + UnsupportedProtocol, + WriteError, + WriteTimeout, +) +from .._models import Request, Response +from .._types import AsyncByteStream, CertTypes, ProxyTypes, SyncByteStream +from .._urls import URL +from .base import AsyncBaseTransport, BaseTransport + +T = typing.TypeVar("T", bound="HTTPTransport") +A = typing.TypeVar("A", bound="AsyncHTTPTransport") + +SOCKET_OPTION = typing.Union[ + typing.Tuple[int, int, int], + typing.Tuple[int, int, typing.Union[bytes, bytearray]], + typing.Tuple[int, int, None, int], +] + +__all__ = ["AsyncHTTPTransport", "HTTPTransport"] + +HTTPCORE_EXC_MAP: dict[type[Exception], type[httpx.HTTPError]] = {} + + +def _load_httpcore_exceptions() -> dict[type[Exception], type[httpx.HTTPError]]: + import httpcore + + return { + httpcore.TimeoutException: TimeoutException, + httpcore.ConnectTimeout: ConnectTimeout, + httpcore.ReadTimeout: ReadTimeout, + httpcore.WriteTimeout: WriteTimeout, + httpcore.PoolTimeout: PoolTimeout, + httpcore.NetworkError: NetworkError, + httpcore.ConnectError: ConnectError, + httpcore.ReadError: ReadError, + httpcore.WriteError: WriteError, + httpcore.ProxyError: ProxyError, + httpcore.UnsupportedProtocol: UnsupportedProtocol, + httpcore.ProtocolError: ProtocolError, + httpcore.LocalProtocolError: LocalProtocolError, + httpcore.RemoteProtocolError: RemoteProtocolError, + } + + +@contextlib.contextmanager +def map_httpcore_exceptions() -> typing.Iterator[None]: + global HTTPCORE_EXC_MAP + if len(HTTPCORE_EXC_MAP) == 0: + HTTPCORE_EXC_MAP = _load_httpcore_exceptions() + try: + yield + except Exception as exc: + mapped_exc = None + + for from_exc, to_exc in HTTPCORE_EXC_MAP.items(): + if not isinstance(exc, from_exc): + continue + # We want to map to the most specific exception we can find. + # Eg if `exc` is an `httpcore.ReadTimeout`, we want to map to + # `httpx.ReadTimeout`, not just `httpx.TimeoutException`. + if mapped_exc is None or issubclass(to_exc, mapped_exc): + mapped_exc = to_exc + + if mapped_exc is None: # pragma: no cover + raise + + message = str(exc) + raise mapped_exc(message) from exc + + +class ResponseStream(SyncByteStream): + def __init__(self, httpcore_stream: typing.Iterable[bytes]) -> None: + self._httpcore_stream = httpcore_stream + + def __iter__(self) -> typing.Iterator[bytes]: + with map_httpcore_exceptions(): + for part in self._httpcore_stream: + yield part + + def close(self) -> None: + if hasattr(self._httpcore_stream, "close"): + self._httpcore_stream.close() + + +class HTTPTransport(BaseTransport): + def __init__( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + proxy: ProxyTypes | None = None, + uds: str | None = None, + local_address: str | None = None, + retries: int = 0, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + import httpcore + + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) + + if proxy is None: + self._pool = httpcore.ConnectionPool( + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + uds=uds, + local_address=local_address, + retries=retries, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("http", "https"): + self._pool = httpcore.HTTPProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + proxy_headers=proxy.headers.raw, + ssl_context=ssl_context, + proxy_ssl_context=proxy.ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("socks5", "socks5h"): + try: + import socksio # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using SOCKS proxy, but the 'socksio' package is not installed. " + "Make sure to install httpx using `pip install httpx[socks]`." + ) from None + + self._pool = httpcore.SOCKSProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + ) + else: # pragma: no cover + raise ValueError( + "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," + f" but got {proxy.url.scheme!r}." + ) + + def __enter__(self: T) -> T: # Use generics for subclass support. + self._pool.__enter__() + return self + + def __exit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + with map_httpcore_exceptions(): + self._pool.__exit__(exc_type, exc_value, traceback) + + def handle_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, SyncByteStream) + import httpcore + + req = httpcore.Request( + method=request.method, + url=httpcore.URL( + scheme=request.url.raw_scheme, + host=request.url.raw_host, + port=request.url.port, + target=request.url.raw_path, + ), + headers=request.headers.raw, + content=request.stream, + extensions=request.extensions, + ) + with map_httpcore_exceptions(): + resp = self._pool.handle_request(req) + + assert isinstance(resp.stream, typing.Iterable) + + return Response( + status_code=resp.status, + headers=resp.headers, + stream=ResponseStream(resp.stream), + extensions=resp.extensions, + ) + + def close(self) -> None: + self._pool.close() + + +class AsyncResponseStream(AsyncByteStream): + def __init__(self, httpcore_stream: typing.AsyncIterable[bytes]) -> None: + self._httpcore_stream = httpcore_stream + + async def __aiter__(self) -> typing.AsyncIterator[bytes]: + with map_httpcore_exceptions(): + async for part in self._httpcore_stream: + yield part + + async def aclose(self) -> None: + if hasattr(self._httpcore_stream, "aclose"): + await self._httpcore_stream.aclose() + + +class AsyncHTTPTransport(AsyncBaseTransport): + def __init__( + self, + verify: ssl.SSLContext | str | bool = True, + cert: CertTypes | None = None, + trust_env: bool = True, + http1: bool = True, + http2: bool = False, + limits: Limits = DEFAULT_LIMITS, + proxy: ProxyTypes | None = None, + uds: str | None = None, + local_address: str | None = None, + retries: int = 0, + socket_options: typing.Iterable[SOCKET_OPTION] | None = None, + ) -> None: + import httpcore + + proxy = Proxy(url=proxy) if isinstance(proxy, (str, URL)) else proxy + ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env) + + if proxy is None: + self._pool = httpcore.AsyncConnectionPool( + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + uds=uds, + local_address=local_address, + retries=retries, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("http", "https"): + self._pool = httpcore.AsyncHTTPProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + proxy_headers=proxy.headers.raw, + proxy_ssl_context=proxy.ssl_context, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + socket_options=socket_options, + ) + elif proxy.url.scheme in ("socks5", "socks5h"): + try: + import socksio # noqa + except ImportError: # pragma: no cover + raise ImportError( + "Using SOCKS proxy, but the 'socksio' package is not installed. " + "Make sure to install httpx using `pip install httpx[socks]`." + ) from None + + self._pool = httpcore.AsyncSOCKSProxy( + proxy_url=httpcore.URL( + scheme=proxy.url.raw_scheme, + host=proxy.url.raw_host, + port=proxy.url.port, + target=proxy.url.raw_path, + ), + proxy_auth=proxy.raw_auth, + ssl_context=ssl_context, + max_connections=limits.max_connections, + max_keepalive_connections=limits.max_keepalive_connections, + keepalive_expiry=limits.keepalive_expiry, + http1=http1, + http2=http2, + ) + else: # pragma: no cover + raise ValueError( + "Proxy protocol must be either 'http', 'https', 'socks5', or 'socks5h'," + " but got {proxy.url.scheme!r}." + ) + + async def __aenter__(self: A) -> A: # Use generics for subclass support. + await self._pool.__aenter__() + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None = None, + exc_value: BaseException | None = None, + traceback: TracebackType | None = None, + ) -> None: + with map_httpcore_exceptions(): + await self._pool.__aexit__(exc_type, exc_value, traceback) + + async def handle_async_request( + self, + request: Request, + ) -> Response: + assert isinstance(request.stream, AsyncByteStream) + import httpcore + + req = httpcore.Request( + method=request.method, + url=httpcore.URL( + scheme=request.url.raw_scheme, + host=request.url.raw_host, + port=request.url.port, + target=request.url.raw_path, + ), + headers=request.headers.raw, + content=request.stream, + extensions=request.extensions, + ) + with map_httpcore_exceptions(): + resp = await self._pool.handle_async_request(req) + + assert isinstance(resp.stream, typing.AsyncIterable) + + return Response( + status_code=resp.status, + headers=resp.headers, + stream=AsyncResponseStream(resp.stream), + extensions=resp.extensions, + ) + + async def aclose(self) -> None: + await self._pool.aclose() diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/mock.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/mock.py new file mode 100644 index 0000000000000000000000000000000000000000..8c418f59e06cae43abdbb626ec21cafc7e8c6277 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/mock.py @@ -0,0 +1,43 @@ +from __future__ import annotations + +import typing + +from .._models import Request, Response +from .base import AsyncBaseTransport, BaseTransport + +SyncHandler = typing.Callable[[Request], Response] +AsyncHandler = typing.Callable[[Request], typing.Coroutine[None, None, Response]] + + +__all__ = ["MockTransport"] + + +class MockTransport(AsyncBaseTransport, BaseTransport): + def __init__(self, handler: SyncHandler | AsyncHandler) -> None: + self.handler = handler + + def handle_request( + self, + request: Request, + ) -> Response: + request.read() + response = self.handler(request) + if not isinstance(response, Response): # pragma: no cover + raise TypeError("Cannot use an async handler in a sync Client") + return response + + async def handle_async_request( + self, + request: Request, + ) -> Response: + await request.aread() + response = self.handler(request) + + # Allow handler to *optionally* be an `async` function. + # If it is, then the `response` variable need to be awaited to actually + # return the result. + + if not isinstance(response, Response): + response = await response + + return response diff --git a/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/wsgi.py b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/wsgi.py new file mode 100644 index 0000000000000000000000000000000000000000..8592ffe017a87367cc7578184540096a9682908d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/httpx/_transports/wsgi.py @@ -0,0 +1,149 @@ +from __future__ import annotations + +import io +import itertools +import sys +import typing + +from .._models import Request, Response +from .._types import SyncByteStream +from .base import BaseTransport + +if typing.TYPE_CHECKING: + from _typeshed import OptExcInfo # pragma: no cover + from _typeshed.wsgi import WSGIApplication # pragma: no cover + +_T = typing.TypeVar("_T") + + +__all__ = ["WSGITransport"] + + +def _skip_leading_empty_chunks(body: typing.Iterable[_T]) -> typing.Iterable[_T]: + body = iter(body) + for chunk in body: + if chunk: + return itertools.chain([chunk], body) + return [] + + +class WSGIByteStream(SyncByteStream): + def __init__(self, result: typing.Iterable[bytes]) -> None: + self._close = getattr(result, "close", None) + self._result = _skip_leading_empty_chunks(result) + + def __iter__(self) -> typing.Iterator[bytes]: + for part in self._result: + yield part + + def close(self) -> None: + if self._close is not None: + self._close() + + +class WSGITransport(BaseTransport): + """ + A custom transport that handles sending requests directly to an WSGI app. + The simplest way to use this functionality is to use the `app` argument. + + ``` + client = httpx.Client(app=app) + ``` + + Alternatively, you can setup the transport instance explicitly. + This allows you to include any additional configuration arguments specific + to the WSGITransport class: + + ``` + transport = httpx.WSGITransport( + app=app, + script_name="/submount", + remote_addr="1.2.3.4" + ) + client = httpx.Client(transport=transport) + ``` + + Arguments: + + * `app` - The WSGI application. + * `raise_app_exceptions` - Boolean indicating if exceptions in the application + should be raised. Default to `True`. Can be set to `False` for use cases + such as testing the content of a client 500 response. + * `script_name` - The root path on which the WSGI application should be mounted. + * `remote_addr` - A string indicating the client IP of incoming requests. + ``` + """ + + def __init__( + self, + app: WSGIApplication, + raise_app_exceptions: bool = True, + script_name: str = "", + remote_addr: str = "127.0.0.1", + wsgi_errors: typing.TextIO | None = None, + ) -> None: + self.app = app + self.raise_app_exceptions = raise_app_exceptions + self.script_name = script_name + self.remote_addr = remote_addr + self.wsgi_errors = wsgi_errors + + def handle_request(self, request: Request) -> Response: + request.read() + wsgi_input = io.BytesIO(request.content) + + port = request.url.port or {"http": 80, "https": 443}[request.url.scheme] + environ = { + "wsgi.version": (1, 0), + "wsgi.url_scheme": request.url.scheme, + "wsgi.input": wsgi_input, + "wsgi.errors": self.wsgi_errors or sys.stderr, + "wsgi.multithread": True, + "wsgi.multiprocess": False, + "wsgi.run_once": False, + "REQUEST_METHOD": request.method, + "SCRIPT_NAME": self.script_name, + "PATH_INFO": request.url.path, + "QUERY_STRING": request.url.query.decode("ascii"), + "SERVER_NAME": request.url.host, + "SERVER_PORT": str(port), + "SERVER_PROTOCOL": "HTTP/1.1", + "REMOTE_ADDR": self.remote_addr, + } + for header_key, header_value in request.headers.raw: + key = header_key.decode("ascii").upper().replace("-", "_") + if key not in ("CONTENT_TYPE", "CONTENT_LENGTH"): + key = "HTTP_" + key + environ[key] = header_value.decode("ascii") + + seen_status = None + seen_response_headers = None + seen_exc_info = None + + def start_response( + status: str, + response_headers: list[tuple[str, str]], + exc_info: OptExcInfo | None = None, + ) -> typing.Callable[[bytes], typing.Any]: + nonlocal seen_status, seen_response_headers, seen_exc_info + seen_status = status + seen_response_headers = response_headers + seen_exc_info = exc_info + return lambda _: None + + result = self.app(environ, start_response) + + stream = WSGIByteStream(result) + + assert seen_status is not None + assert seen_response_headers is not None + if seen_exc_info and seen_exc_info[0] and self.raise_app_exceptions: + raise seen_exc_info[1] + + status_code = int(seen_status.split()[0]) + headers = [ + (key.encode("ascii"), value.encode("ascii")) + for key, value in seen_response_headers + ] + + return Response(status_code, headers=headers, stream=stream) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f72e3e075b22cd405d66b933e59111da2a4acc19 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/draw.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/draw.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2663fab37e76833821c3764ca5eca76d8308334f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/draw.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/entity_instance.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/entity_instance.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da39113c4d4d84dd4d0a83a6085199dd2a09f919 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/entity_instance.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/file.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/file.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..555d6b6083e90c90949798b4d14f333f73e3555b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/file.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/guid.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/guid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a9ba2339e7dcdda25a073a8521f4348b3287ca7d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/guid.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/settings.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/settings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63f24a82f1a2f02a713e91145be39f96e032a7f8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/settings.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/sql.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/sql.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2542123624f28910ec0dba5a537e1497bcd08740 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/sql.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/stream.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/stream.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f64a5fabaf1f38723530816824d500aad612ee9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/stream.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/template.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/template.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b4ded5859b13121fc0ffdba6b5370ef252852691 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/template.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/validate.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/validate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b1b71412a8efa7c53c48fcfa418507671d685873 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/__pycache__/validate.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0eb95b2c652439f65198ea45ecdf712c2307aa38 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__init__.py @@ -0,0 +1,316 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""High level IFC authoring and editing functions + +Authoring, editing, and deleting IFC data requires a detailed understanding of +the rules of the IFC schema. This API module provides simple to use authoring +functions that hide this complexity from you. Things like managing differences +between IFC versions, tracking owernship changes, or cleaning up after orphaned +relationships are all handled automatically. + +If you're new to IFC authoring, start by looking at the following APIs: + +- See :func:`ifcopenshell.api.project.create_file` to create a new IFC. +- See :func:`ifcopenshell.api.root.create_entity` to create new entities, like + the mandatory IfcProject, and then an IfcSite, IfcWall, etc. +- See :func:`ifcopenshell.api.aggregate.assign_object` to create a spatial + hierarchy. +- See :func:`ifcopenshell.api.spatial.assign_container` to place physical + elements (e.g. walls) inside spatial elements (e.g. building storeys). + +Also see how to `create a simple model from scratch +`_. +""" + +import json +import numpy +import inspect +import importlib +import ifcopenshell +from typing import Callable, Any, Optional, TYPE_CHECKING +from functools import partial + +if TYPE_CHECKING: + import ifcopenshell.api + +pre_listeners: dict[str, dict] = {} +post_listeners: dict[str, dict] = {} + + +def batching_argument_deprecation( + usecase_path: str, settings: dict, prev_argument: str, new_argument: str, replace_usecase: Optional[str] = None +) -> tuple[str, dict]: + if replace_usecase is not None: + print(f"WARNING. `{usecase_path}` api method is deprecated and should be replaced with `{replace_usecase}`.") + + if prev_argument in settings: + print( + f"WARNING. `{prev_argument}` argument is deprecated for API method " + f'"{usecase_path}" and should be replaced with `{new_argument}`.' + ) + settings = settings | {new_argument: [settings[prev_argument]]} + settings.pop(prev_argument) + return (replace_usecase or usecase_path, settings) + + +def renamed_arguments_deprecation( + usecase_path: str, settings: dict, arguments_remapped: dict[str, str] +) -> tuple[str, dict]: + for prev_argument, new_argument in arguments_remapped.items(): + if prev_argument in settings: + print( + f"WARNING. `{prev_argument}` argument is deprecated for API method " + f'"{usecase_path}" and should be replaced with `{new_argument}`.' + ) + settings = settings | {new_argument: settings[prev_argument]} + settings.pop(prev_argument) + return (usecase_path, settings) + + +# Example item: +# "group.add_group": partial( +# renamed_arguments_deprecation, arguments_remapped={"Name": "name", "Description": "description"} +# ), +ARGUMENTS_DEPRECATION: dict[str, Callable[[str, dict[str, Any]], tuple[str, dict[str, Any]]]] = { + "control.assign_control": partial( + batching_argument_deprecation, prev_argument="related_object", new_argument="related_objects" + ), +} + + +CACHED_USECASE_CLASSES: dict[str, Callable] = {} +CACHED_USECASES: dict[str, Callable] = {} + + +def run( + usecase_path: str, + ifc_file: Optional[ifcopenshell.file] = None, + should_run_listeners: bool = True, + **settings: Any, +) -> Any: + """This is deprecated and will be removed in a future version. Do not use this function.""" + usecase_function = CACHED_USECASES.get(usecase_path) + if not usecase_function: + importlib.import_module(f"ifcopenshell.api.{usecase_path}") + module, usecase = usecase_path.split(".") + usecase_function = getattr(getattr(ifcopenshell.api, module), usecase) + CACHED_USECASES[usecase_path] = usecase_function + if ifc_file: + return usecase_function(ifc_file, should_run_listeners=should_run_listeners, **settings) + return usecase_function(should_run_listeners=should_run_listeners, **settings) + + if should_run_listeners: + for listener in pre_listeners.get(usecase_path, {}).values(): + listener(usecase_path, ifc_file, settings) + + usecase_class = CACHED_USECASE_CLASSES.get(usecase_path) + if usecase_class is None: + importlib.import_module(f"ifcopenshell.api.{usecase_path}") + module, usecase = usecase_path.split(".") + usecase_class = getattr(getattr(getattr(ifcopenshell.api, module), usecase), "Usecase") + CACHED_USECASE_CLASSES[usecase_path] = usecase_class + + if ifc_file: + result = usecase_class(ifc_file, **settings).execute() + else: + result = usecase_class(**settings).execute() + + if should_run_listeners: + for listener in post_listeners.get(usecase_path, {}).values(): + listener(usecase_path, ifc_file, settings) + + return result + + +def add_pre_listener(usecase_path: str, name: str, callback: Callable[[str, ifcopenshell.file, dict], None]) -> None: + """Add a pre listener + + :param usecase_path: string, ifcopenshell api use case path + :param name: string, name of listener + :param callback: callback function with 3 arguments: `usecase_path`, `ifc_file`, `settings` + """ + pre_listeners.setdefault(usecase_path, {})[name] = callback + + +def add_post_listener(usecase_path: str, name: str, callback: Callable[[str, ifcopenshell.file, dict], None]) -> None: + """Add a post listener + + :param usecase_path: string, ifcopenshell api use case path + :param name: string, name of listener + :param callback: callback function with 3 arguments: `usecase_path`, `ifc_file`, `settings` + """ + post_listeners.setdefault(usecase_path, {})[name] = callback + + +def remove_pre_listener(usecase_path: str, name: str, callback: Callable[[str, ifcopenshell.file, dict], None]) -> None: + """Remove a pre listener + + :param usecase_path: string, ifcopenshell api use case path + :param name: string, name of listener + :param callback: callback function with 3 arguments: `usecase_path`, `ifc_file`, `settings` + """ + pre_listeners.get(usecase_path, {}).pop(name, None) + + +def remove_post_listener( + usecase_path: str, name: str, callback: Callable[[str, ifcopenshell.file, dict], None] +) -> None: + """Remove a post listener + + :param usecase_path: string, ifcopenshell api use case path + :param name: string, name of listener + :param callback: callback function with 3 arguments: `usecase_path`, `ifc_file`, `settings` + """ + post_listeners.get(usecase_path, {}).pop(name, None) + + +def remove_all_listeners(): + pre_listeners.clear() + post_listeners.clear() + + +def extract_docs(module: str, usecase: str) -> dict[str, Any]: + import typing + import collections + + inputs = collections.OrderedDict() + + function_init = getattr(getattr(ifcopenshell.api, module), usecase).Usecase.__init__ + function_execute = getattr(getattr(ifcopenshell.api, module), usecase).Usecase.execute + + node_data = {"module": module, "usecase": usecase} + + signature = inspect.signature(function_init) + for name, parameter in signature.parameters.items(): + if name == "self": + continue + inputs[name] = {"name": name} + if isinstance(parameter.default, (str, float, int, bool)): + inputs[name]["default"] = parameter.default + + type_hints = typing.get_type_hints(function_init) + for name, socket_data in inputs.items(): + type_hint = type_hints[name] + if isinstance(type_hint, typing._UnionGenericAlias): # pyright: ignore[reportAttributeAccessIssue] + inputs[name]["type"] = [t.__name__ for t in typing.get_args(type_hint)] + else: + inputs[name]["type"] = type_hint.__name__ + + description = "" + for i, line in enumerate(function_init.__doc__.split("\n")): + line = line.strip() + if i == 0: + node_data["name"] = line + elif line.startswith(":return:"): + node_data["output"] = {"name": line.split(":")[2].strip(), "description": line.split(":")[3].strip()} + elif line.startswith(":param"): + param_name = line.split(":")[1].strip().replace("param ", "") + inputs[param_name]["description"] = line.split(":")[2].strip() + elif i >= 2: + description += line + + if "output" in node_data: + node_data["output"]["type"] = typing.get_type_hints(function_execute)["return"].__name__ + node_data["description"] = description.strip() + node_data["inputs"] = inputs + return node_data + + +def serialise_settings(settings): + def serialise_entity_instance(entity): + return {"cast_type": "entity_instance", "value": entity.id(), "Name": getattr(entity, "Name", None)} + + vcs_settings = settings.copy() + for key, value in settings.items(): + if isinstance(value, ifcopenshell.entity_instance): + vcs_settings[key] = serialise_entity_instance(value) + elif isinstance(value, numpy.ndarray): + vcs_settings[key] = {"cast_type": "ndarray", "value": value.tolist()} + elif isinstance(value, list) and value and isinstance(value[0], ifcopenshell.entity_instance): + vcs_settings[key] = [serialise_entity_instance(i) for i in value] + else: + try: + vcs_settings[key] = str(value) + except: + vcs_settings[key] = "n/a" + try: + return json.dumps(vcs_settings) + except: + return str(vcs_settings) + + +def wrap_usecase(usecase_path, usecase): + """Wraps an API function in pre/post listeners.""" + + def wrapper(*args, should_run_listeners: bool = True, **settings): + ifc_file = args[0] if args else None + nonlocal usecase_path + if should_run_listeners: + listeners = list(pre_listeners.get(usecase_path, {}).values()) + listeners += pre_listeners.get("*", {}).values() + for listener in listeners: + listener(usecase_path, ifc_file, settings) + + # see #4531 + if usecase_path in ARGUMENTS_DEPRECATION: + usecase_path, settings = ARGUMENTS_DEPRECATION[usecase_path](usecase_path, settings) + + try: + result = usecase(*args, **settings) + except TypeError as e: + if not e.args[0].startswith(f"{usecase.__name__}()"): + # signature errors typically start with function name + # e.g. "TypeError: edit_library() got an unexpected keyword argument 'test'" + # otherwise it's an error inside api call and we shouldn't get in the way + raise e + msg = ( + f"Incorrect function arguments provided for {usecase_path}\n{str(e)}. " + f"You specified args {args} and settings {settings}\n\n" + f"Correct signature is {inspect.signature(usecase)}\n" + f"See help(ifcopenshell.api.{usecase_path}) for documentation." + ) + raise TypeError(msg) from e + + if should_run_listeners: + listeners = list(post_listeners.get(usecase_path, {}).values()) + listeners += post_listeners.get("*", {}).values() + for listener in listeners: + listener(usecase_path, ifc_file, settings) + + return result + + wrapper.__signature__ = inspect.signature(usecase) + wrapper.__doc__ = usecase.__doc__ + wrapper.__name__ = usecase_path + return wrapper + + +def wrap_usecases(path, name): + """This developer feature wraps an API module's usecases with listeners.""" + import sys + import pkgutil + + module_name = name.split(".")[-1] + module = sys.modules[name] + for loader, usecase_name, is_pkg in pkgutil.iter_modules(path): + # We may not be able to get the usecase if we are missing a dependency. + usecase = getattr(module, usecase_name, None) + if callable(usecase): + usecase_path = f"{module_name}.{usecase_name}" + setattr(module, usecase_name, wrap_usecase(usecase_path, usecase)) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aace72b6da0f403cf2ecaaa52789ca71396c99c0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..49898908ff205a5ee18da95a41ac8cce82acb341 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/__init__.py @@ -0,0 +1,35 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Aggregates is the concept of breaking down larger wholes into smaller parts. + +For example, spatial elements such as sites are broken down into one or more +buildings, and a building is broken down into storeys. Another example is for +physical elements, such as how a wall is made out of members and coverings. +""" + +from .. import wrap_usecases +from .assign_object import assign_object +from .unassign_object import unassign_object + +wrap_usecases(__path__, __name__) + +__all__ = [ + "assign_object", + "unassign_object", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/assign_object.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/assign_object.py new file mode 100644 index 0000000000000000000000000000000000000000..22d027b73b504f11c2dfa7b1eb2b0131b5ff6a29 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/assign_object.py @@ -0,0 +1,159 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.api.spatial +import ifcopenshell.api.geometry +import ifcopenshell.guid +import ifcopenshell.util.element +import ifcopenshell.util.placement +from typing import Union + + +def assign_object( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + relating_object: ifcopenshell.entity_instance, +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns object as an aggregate to the products + + All physical IFC model elements must be part of a hierarchical tree + called the "spatial decomposition", where large things are made up of + smaller things. This tree always begins at an "IfcProject" and is then + broken down using "decomposition" relationships, of which aggregation is + the first relationship you will use. + + Typically used when you want to describe how large spaces are made up of + smaller spaces. For example large spatial elements (e.g. sites, + buidings) can be made out of smaller spatial elements (e.g. storeys, + spaces). + + The largest space (typically the IfcSite) can then be aggregated in a + project. It is requirement for all spatial structures to be directly or + indirectly aggregated back to the IfcProject to create a hierarchy of + spaces. + + The other common usecase is when larger physical products are made up of + smaller physical products. For example, a stair might be made out of a + flight, a landing, a railing and so on. Or a wall might be made out of + stud members, and coverings. + + As a product may only have a single location in the "spatial + decomposition" tree, assigning an aggregate relationship will remove any + previous aggregation, containment, or nesting relationships it may have. + + IFC placements follow a convention where the placement is relative to + its parent in the spatial hierarchy. If your product has a placement, + its placement will be recalculated to follow this convention. + + :param products: The list of parts of the aggregate, typically of IfcElement or + IfcSpatialStructureElement subclass + :param relating_object: The whole of the aggregate, typically an + IfcElement or IfcSpatialStructureElement subclass + :return: The IfcRelAggregate relationship instance + or `None` if `products` was empty list. + + Example: + + .. code:: python + + project = ifcopenshell.api.root.create_entity(model, ifc_class="IfcProject") + element = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSite") + subelement = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBuilding") + + # The project contains a site (note that project aggregation is a special case in IFC) + ifcopenshell.api.aggregate.assign_object(model, products=[element], relating_object=project) + + # The site has a building + ifcopenshell.api.aggregate.assign_object(model, products=[subelement], relating_object=element) + """ + if not products: + return + + products_set = set(products) + is_decomposed_by = next((i for i in relating_object.IsDecomposedBy if i.is_a("IfcRelAggregates")), None) + + previous_aggregates_rels: set[ifcopenshell.entity_instance] = set() + products_without_aggregates: list[ifcopenshell.entity_instance] = [] + products_with_aggregates: list[ifcopenshell.entity_instance] = [] + + # check if there is anything to change + for product in products_set: + product_rel = next(iter(product.Decomposes), None) + + if product_rel is None: + products_without_aggregates.append(product) + continue + + # either is_decomposed_by is None or product is part of different rel + if product_rel != is_decomposed_by: + previous_aggregates_rels.add(product_rel) + products_with_aggregates.append(product) + + # products with already assigned aggregates will be skipped + + products_to_change = products_without_aggregates + products_with_aggregates + # nothing to change + if not products_to_change: + return is_decomposed_by + + # can be either only aggregated or only contained at the same time + # some product might not be able to have a container + possibly_contained_products = [p for p in products_without_aggregates if hasattr(p, "ContainedInStructure")] + ifcopenshell.api.spatial.unassign_container(file, products=possibly_contained_products) + + # unassign elements from previous aggregates + for decomposes in previous_aggregates_rels: + related_objects = set(decomposes.RelatedObjects) - products_set + if related_objects: + decomposes.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=decomposes) + else: + history = decomposes.OwnerHistory + file.remove(decomposes) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + # assign elements to a new aggregate + if is_decomposed_by: + is_decomposed_by.RelatedObjects = list(set(is_decomposed_by.RelatedObjects) | products_set) + ifcopenshell.api.owner.update_owner_history(file, element=is_decomposed_by) + else: + is_decomposed_by = file.create_entity( + "IfcRelAggregates", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": list(products_set), + "RelatingObject": relating_object, + } + ) + + # localize placement relative to a new aggregate for affected products + for product in products_to_change: + placement = getattr(product, "ObjectPlacement", None) + if placement and placement.is_a("IfcLocalPlacement"): + ifcopenshell.api.geometry.edit_object_placement( + file, + product=product, + matrix=ifcopenshell.util.placement.get_local_placement(product.ObjectPlacement), + is_si=False, + ) + + return is_decomposed_by diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/unassign_object.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/unassign_object.py new file mode 100644 index 0000000000000000000000000000000000000000..e34aff879cff021cc46bb6c4f430fc5f4c2245fb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/aggregate/unassign_object.py @@ -0,0 +1,75 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_object(file: ifcopenshell.file, products: list[ifcopenshell.entity_instance]) -> None: + """Unassigns products from their aggregate + + A product (i.e. a smaller part of a whole) may be aggregated into zero + or one larger space or element. This function will remove that + aggregation relationship. + + As all physical IFC model elements must be part of a hierarchical tree + called the "spatial decomposition", using this function will remove the + product from that tree. This is a dangerous operation and may result in + the product no longer being visible in IFC applications. + + If the product is not part of an aggregation relationship, nothing will + happen. + + :param products: The list of parts of the aggregate, typically of IfcElements or + IfcSpatialStructureElement subclass + :return: None + + Example: + + .. code:: python + + element = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSite") + subelement1 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBuilding") + subelement2 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBuilding") + ifcopenshell.api.aggregate.assign_object(model, products=[subelement1], relating_object=element) + ifcopenshell.api.aggregate.assign_object(model, products=[subelement2], relating_object=element) + # nothing is returned + ifcopenshell.api.aggregate.unassign_object(model, products=[subelement1]) + # nothing is returned, relationship is removed + ifcopenshell.api.aggregate.unassign_object(model, products=[subelement2]) + """ + settings = {"products": products} + + products = set(settings["products"]) + rels = set( + rel + for product in products + if (rel := next((rel for rel in product.Decomposes if rel.is_a("IfcRelAggregates")), None)) + ) + + for rel in rels: + related_objects = set(rel.RelatedObjects) - products + if related_objects: + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a7de8ab415b023f1fbe35a4e74e1f9975e7016 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/__init__.py @@ -0,0 +1,33 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Basic modification of the attributes of an element. + +All IFC entities have attributes. Some of these attributes contain rules about +inheritance and what they are allowed to contain. These usecases make sure that +any editing complies with these rules. +""" + +from .. import wrap_usecases +from .edit_attributes import edit_attributes + +wrap_usecases(__path__, __name__) + +__all__ = [ + "edit_attributes", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/edit_attributes.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/edit_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..6199ddf3b7197ee7f9514894803b88d1e13c70c4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/attribute/edit_attributes.py @@ -0,0 +1,89 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import sys +import ifcopenshell.api.owner +import ifcopenshell.util.element +from typing import Any, Union + +if sys.version_info >= (3, 10): + from types import EllipsisType +else: + EllipsisType = type(...) + + +def edit_attributes(file: ifcopenshell.file, product: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edit the attributes of a product + + All IFC entities have attributes. Normally they can be edited directly, + by simply assigning a new value to them. In some scenarios, you may wish + to also ensure that ownership history is updated. This function provides + that convenience. + + The method will maintain consistency for PredefinedType attribute + based on whether ElementType/ObjectType and whether occurrence is typed: + + - PredefinedType and ObjectType to be `None` if occurrence is typed + - PredefinedType to be "NOTDEFINED" if ElementType/ObjectType is None + - PredefinedType to be "USERDEFINED" if ElementType/ObjectType is not None + + :param product: The product you want to edit. This may be any rooted IFC + entity. + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + element = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + ifcopenshell.api.attribute.edit_attributes(model, + product=element, attributes={"Name": "Waldo"}) + """ + + def getattr_safe(element: ifcopenshell.entity_instance, attr: str) -> Union[Any, EllipsisType]: + """Return attribute value or Ellipsis if attribute doesn't exist. + + Useful as an alternative to hasattr - hasattr under the hood just does + getattr but doesn't return a value. That helps reduce times IFC is accessed. + """ + return getattr(element, attr, ...) + + for name, value in attributes.items(): + setattr(product, name, value) + + if (predefined_type := getattr_safe(product, "PredefinedType")) is not ...: + if (element_type := getattr_safe(product, "ElementType")) is not ...: + if element_type is None and predefined_type == "USERDEFINED": + product.PredefinedType = "NOTDEFINED" + elif element_type and predefined_type != "USERDEFINED": + product.PredefinedType = "USERDEFINED" + + elif (object_type := getattr_safe(product, "ObjectType")) is not ...: + relating_type = ifcopenshell.util.element.get_type(product) + # Allow for None due to https://github.com/buildingSMART/IFC4.3.x-development/issues/818 + if relating_type and relating_type.PredefinedType not in ("NOTDEFINED", None): + product.ObjectType = None + product.PredefinedType = None + elif object_type is None and predefined_type == "USERDEFINED": + product.PredefinedType = "NOTDEFINED" + elif object_type and predefined_type != "USERDEFINED": + product.PredefinedType = "USERDEFINED" + + if hasattr(product, "OwnerHistory"): + ifcopenshell.api.owner.update_owner_history(file, element=product) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3df948a5cfebebce0b6df0822baca3385c07145e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/__init__.py @@ -0,0 +1,39 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Boundaries are primarily used for representing virtual interfaces between +spaces for energy analysis. + +Boundaries may be associated with spaces or physical elements that enclose +spaces such as walls, doors, and windows. +""" + +from .. import wrap_usecases +from .assign_connection_geometry import assign_connection_geometry +from .copy_boundary import copy_boundary +from .edit_attributes import edit_attributes +from .remove_boundary import remove_boundary + +wrap_usecases(__path__, __name__) + +__all__ = [ + "assign_connection_geometry", + "copy_boundary", + "edit_attributes", + "remove_boundary", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/assign_connection_geometry.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/assign_connection_geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..36e55f2d00c9ef511842ebf4d7ff61c9b078e77e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/assign_connection_geometry.py @@ -0,0 +1,131 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.unit +import numpy as np +import numpy.typing as npt +from typing import Optional +from ifcopenshell.util.shape_builder import SequenceOfVectors, V, ifc_safe_vector_type + + +def assign_connection_geometry( + file: ifcopenshell.file, + rel_space_boundary: ifcopenshell.entity_instance, + outer_boundary: SequenceOfVectors, + location: tuple[float, float, float], + axis: tuple[float, float, float], + ref_direction: tuple[float, float, float], + inner_boundaries: Optional[SequenceOfVectors] = None, + unit_scale: Optional[float] = None, +) -> None: + """Create and assign a connection geometry to a space boundary relationship + + A space boundary may optionally have a plane that represents how that + space is adjacent to another space, known as the connection geometry. + You may specify this plane in terms of an outer boundary polyline, zero + or more inner boundaries (such as for windows), and a positional matrix + for the orientation of the plane. + + :param rel_space_boundary: The space boundary relationship to assign the + connection geometry to. + :param outer_boundary: A list of 2D points representing an open + polyline. The last point will connect to the first point. Each + point is represented by an interable of 2 floats. The coordinates of + the points are relative to the positional matrix arguments. + :param inner_boundaries: A list of zero or more inner boundaries to use + for the plane. Each boundary is represented by an open polyline, as + defined by the outer_boundary argument. + :param location: The local origin of the connection geometry, defined as + an XYZ coordinate relative to the placement of the space that is + being bounded. + :param axis: The local X axis of the connection geometry, defined as an + XYZ vector relative to the placement of the space that is being + bounded. + :param ref_direction: The local Z axis of the connection geometry, + defined as an XYZ vector relative to the placement of the space that + is being bounded. The Y vector is automatically derived using the + right hand rule. + :param unit_scale: The unit scale as calculated by + ifcopenshell.util.unit.calculate_unit_scale. If not provided, it + will be automatically calculated for you. + :return: None + + Example: + + .. code:: python + + ifcopenshell.api.boundary.assign_connection_geometry(model, + rel_space_boundary=element, + outer_boundary=[(0., 0.), (1., 0.), (1., 1.), (0., 1.)], + location=[0., 0., 0.], axis=[1., 0., 0.], ref_direction=[0., 0., 1.], + ) + """ + usecase = Usecase() + usecase.file = file + usecase.rel_space_boundary = rel_space_boundary + usecase.outer_boundary = V(outer_boundary) + usecase.inner_boundaries = V(inner_boundaries or []) + usecase.location = V(location) + usecase.axis = V(axis) + usecase.ref_direction = V(ref_direction) + usecase.unit_scale = unit_scale if unit_scale is not None else ifcopenshell.util.unit.calculate_unit_scale(file) + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + rel_space_boundary: ifcopenshell.entity_instance + outer_boundary: npt.NDArray + inner_boundaries: npt.NDArray + location: npt.NDArray + axis: npt.NDArray + ref_direction: npt.NDArray + unit_scale: float + + def execute(self): + outer_boundary = self.create_polyline(self.outer_boundary) + inner_boundaries = tuple(self.create_polyline(boundary) for boundary in self.inner_boundaries) + plane = self.create_plane(self.location, self.axis, self.ref_direction) + curve_bounded_plane = self.file.createIfcCurveBoundedPlane(plane, outer_boundary, inner_boundaries) + connection_geometry = self.file.createIfcConnectionSurfaceGeometry(curve_bounded_plane) + self.rel_space_boundary.ConnectionGeometry = connection_geometry + + def create_point(self, point: npt.NDArray) -> ifcopenshell.entity_instance: + return self.file.create_enitty("IfcCartesianPoint", ifc_safe_vector_type(point / self.unit_scale)) + + def close_polyline( + self, points: tuple[ifcopenshell.entity_instance, ...] + ) -> tuple[ifcopenshell.entity_instance, ...]: + return points + (points[0],) + + def create_polyline(self, points: npt.NDArray) -> ifcopenshell.entity_instance: + if np.allclose(points[0], points[-1]): + points = points[0 : len(points) - 1] + ifc_points = tuple(self.create_point(point) for point in points) + return self.file.createIfcPolyline(self.close_polyline(ifc_points)) + + def create_plane( + self, location: npt.NDArray, axis: npt.NDArray, ref_direction: npt.NDArray + ) -> ifcopenshell.entity_instance: + return self.file.createIfcPlane( + self.file.createIfcAxis2Placement3D( + self.create_point(location), + self.file.createIfcDirection(axis), + self.file.createIfcDirection(ref_direction), + ) + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/copy_boundary.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/copy_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e74b5a113317c9f82b70264e173498ca51d3ea --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/copy_boundary.py @@ -0,0 +1,40 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element + + +def copy_boundary(file: ifcopenshell.file, boundary: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Copies a space boundary + + :param boundary: The IfcRelSpaceBoundary you want to copy. + :return: Duplicate of the IfcRelSpaceBoundary + + Example: + + # A boring boundary with no geometry. Note that this boundary is + # invalid and does not relate to any space or building element. + boundary = ifcopenshell.api.root.create_entity(model, ifc_class="IfcRelSpaceBoundary") + + # And now we have two + boundary_copy = ifcopenshell.api.boundary.copy_boundary(model, boundary=boundary) + """ + result = ifcopenshell.util.element.copy(file, boundary) + if result.ConnectionGeometry: + result.ConnectionGeometry = ifcopenshell.util.element.copy_deep(file, result.ConnectionGeometry) + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/edit_attributes.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/edit_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..6980b1a2dd295e570d92a62afb93688c0de7a876 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/edit_attributes.py @@ -0,0 +1,59 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Optional + + +def edit_attributes( + file: ifcopenshell.file, + entity: ifcopenshell.entity_instance, + relating_space: ifcopenshell.entity_instance, + related_building_element: ifcopenshell.entity_instance, + parent_boundary: Optional[ifcopenshell.entity_instance] = None, + corresponding_boundary: Optional[ifcopenshell.entity_instance] = None, +) -> None: + """Modify the relationships of a space boundary relationship + + Currently this function is quite minimal and offers no advantage to + manual assignment of the space boundary attributes. + + :param entity: The IfcRelSpaceBoundary to modify + :param relating_space: The IfcSpace or IfcExternalSpatialElement that + the space boundary is related to. + :param related_building_element: The IfcElement that defines the + boundary, typically an IfcWall. + :param parent_boundary: A parent IfcRelSpaceBoundary, only provided if + this is an inner boundary. This can apply to 1st and 2nd level + boundaries. + :param corresponding_boundary: The other IfcRelSpaceBoundary on the + other side of the related element. The pair together represents a + thermal boundary. This only applies to 2nd level boundaries. + :return: None + """ + entity = entity + relating_space = relating_space + related_building_element = related_building_element + parent_boundary = parent_boundary + corresponding_boundary = corresponding_boundary + + entity.RelatingSpace = relating_space + entity.RelatedBuildingElement = related_building_element + if hasattr(entity, "ParentBoundary"): + entity.ParentBoundary = parent_boundary + if hasattr(entity, "CorrespondingBoundary"): + entity.CorrespondingBoundary = corresponding_boundary diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/remove_boundary.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/remove_boundary.py new file mode 100644 index 0000000000000000000000000000000000000000..4aadabcbce289cda20e894d06a30fa1e7f02b718 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/boundary/remove_boundary.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_boundary(file: ifcopenshell.file, boundary: ifcopenshell.entity_instance) -> None: + """Removes a space boundary + + The relating space or related building element is untouched. Only the + boundary and its connection geometry is removed. + + :param boundary: The IfcRelSpaceBoundary you want to remove. + :return: None + + Example: + + # A boring boundary with no geometry. Note that this boundary is + # invalid and does not relate to any space or building element. + boundary = ifcopenshell.api.root.create_entity(model, ifc_class="IfcRelSpaceBoundary") + + # Let's remove it! + ifcopenshell.api.boundary.remove_boundary(model, boundary=boundary) + """ + geometry = boundary.ConnectionGeometry + if geometry: + boundary.ConnectionGeometry = None + ifcopenshell.util.element.remove_deep2(file, geometry) + history = boundary.OwnerHistory + file.remove(boundary) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..05dd99a05cf2398c80b71698926537ba9f00a31a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/__init__.py @@ -0,0 +1,47 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Classification systems are a way of categorising objects + +Although IFC itself comes with a built-in classification hierarchy (e.g. +IfcWall and its predefined types of PARTITIONING, etc), there are many external +or custom classification systems such as Uniclass, Omniclass and more. IFC is +able to integrate with any external classification system. + +This API allows you to manage and assign external classification systems and +references. +""" + +from .. import wrap_usecases +from .add_classification import add_classification +from .add_reference import add_reference +from .edit_classification import edit_classification +from .edit_reference import edit_reference +from .remove_classification import remove_classification +from .remove_reference import remove_reference + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_classification", + "add_reference", + "edit_classification", + "edit_reference", + "remove_classification", + "remove_reference", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_classification.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..2932a5bb938396e148953c610018d58f6ee1c18a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_classification.py @@ -0,0 +1,125 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021, 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.guid +import ifcopenshell.util.schema +import ifcopenshell.util.date +from typing import Union, Any + + +def add_classification( + file: ifcopenshell.file, classification: Union[str, ifcopenshell.entity_instance] +) -> ifcopenshell.entity_instance: + """Adds a new classification system to the project + + External classification systems such as Uniclass or Omniclass are + ways of categorising elements in the AEC industry, typically + standardised or nominated by governments or companies. A system + typically contains a series of hierarchical reference codes and labels + like Pr_12_23_34. + + Classifications may be applied to many things, not just physical + elements, such as doors and windows, spatial elements, tasks, cost + items, or even resources. + + Prior to assigning classificaion references, you need to add the name + and metadata of the classification system that you will use in your + project. Classification systems may be revised over time, so this + metadata includes the edition date. + + Common classification systems are provided as an IFC library which may + be downloaded from https://github.com/Moult/IfcClassification for your + convenience. It is advised to use these to ensure that the + classification metadata is standardised. + + Adding a classification system will not add the entire hierarchy of + references available in the classification. References need to be added + separately. Typically, you'd only add the references that you use in + your project, see ifcopenshell.api.classification.add_reference for more + information. + + :param classification: If a string is provided, it is assumed to be the + name of your classification system. This is necessary if you are + creating your own custom classification system. Alternatively, you + may provide an entity_instance of an IfcClassification from an IFC + classification library. The latter approach is preferred if you are + using a commonly known system such as Uniclass, as this will ensure + all metadata is added correctly. + :return: The added IfcClassification element + + Example: + + .. code:: python + + # Option 1: adding a custom clasification from scratch + ifcopenshell.api.classification.add_classification(model, + classification="MyCustomClassification") + + # Option 2: adding a popular classification from a library + library = ifcopenshell.open("/path/to/Uniclass.ifc") + classification = library.by_type("IfcClassification")[0] + ifcopenshell.api.classification.add_classification(model, + classification=classification) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(classification) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, classification: Union[str, ifcopenshell.entity_instance]) -> ifcopenshell.entity_instance: + self.classification = classification + if isinstance(self.classification, str): + classification = self.file.create_entity("IfcClassification", Name=self.classification) + self.relate_to_project(classification) + return classification + return self.add_from_library() + + def add_from_library(self) -> ifcopenshell.entity_instance: + edition_date = None + if self.classification.EditionDate: + edition_date = ifcopenshell.util.date.ifc2datetime(self.classification.EditionDate) + self.classification.EditionDate = None + + migrator = ifcopenshell.util.schema.Migrator() + result = migrator.migrate(self.classification, self.file) + + # TODO: should auto date migration be part of the migrator? + if self.file.schema == "IFC2X3" and edition_date: + result.EditionDate = self.file.create_entity( + "IfcCalendarDate", **ifcopenshell.util.date.datetime2ifc(edition_date, "IfcCalendarDate") + ) + else: + if edition_date: + edition_date = ifcopenshell.util.date.datetime2ifc(edition_date, "IfcDate") + result.EditionDate = edition_date + + self.relate_to_project(result) + + return result + + def relate_to_project(self, classification: ifcopenshell.entity_instance) -> None: + self.file.create_entity( + "IfcRelAssociatesClassification", + GlobalId=ifcopenshell.guid.new(), + RelatedObjects=[self.file.by_type("IfcProject")[0]], + RelatingClassification=classification, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..7f3d46bc96a934ae5c9d066134d3c9f669c09e5f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/add_reference.py @@ -0,0 +1,255 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +import ifcopenshell.util.schema +from typing import Optional, Union, Any + + +def add_reference( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + reference: Optional[ifcopenshell.entity_instance] = None, + identification: Optional[str] = None, + name: Optional[str] = None, + classification: Optional[ifcopenshell.entity_instance] = None, + is_lightweight=True, +) -> Union[ifcopenshell.entity_instance, None]: + """Adds a new classification reference and assigns it to the list of products + + A classification reference is a single entry such as "Pr_12_23_34" that + is part of an external classification system (such as Uniclass or + Omniclass). + + References can be added to almost any object in IFC, including physical + objects, object types, properties, tasks, costs, resources, or even + resources such as profiles, documents, libraries, and so on. + + Classification references can be added in two ways. Option 1) specify a + custom arbitrary reference, where you have to manually specify the + identification (e.g. "Pr_12_23_45") and name (e.g. "Door Products"). + Option 2) add a reference from an IFC classification library. The latter + is preferred if you are using a common classification system such as + Uniclass, as the library will be prepopulated with all the valid + classifications already. + + Objects are allowed to have multiple classification references from + multiple classification systems. This means that adding a new reference + will not remove existing references. + + References can be inherited from types. This means that if an + IfcWallType has a classification reference of Pr_12_23_34, then all + IfcWall occurrences of that type automatically get the same + classification of Pr_12_23_34. This means that it is more efficient to + assign to types where possible. If a classification reference is + assigned to both the type and an occurrence, then the assignment at the + occurrence will override the type classification. + + :param product: The list of IFC objects, properties, or resources you want to + associate the classification reference to. + :param reference: The classification reference entity taken from an + IFC classification library. If you supply this parameter, you will + use option 2. + :param identification: If you choose option 1 and do not specify a + reference, you may manually specify an identification code. The code + is typically a short identifier and may have punctuation to separate + the levels of hierarchy in the classificaion (e.g. Pr_12_23_34). + :param name: If you choose option 1 and do not specify a reference, you + may manually specify a name. The name is typically human readable. + :param classification: The IfcClassification entity in your IFC model + (not the library, if you are doing option 2) that the reference is + part of. + :param is_lightweight: If you are doing option 2, choose whether or not + to only add that particular reference (lighweight) or also add all + of its parent references in the classification hierarchy (not + lighweight). For example, adding a lightweight reference to + Pr_12_23_34 will only add Pr_12_23_34, but adding a heavy reference + to Pr_12_23_34 will also add Pr_12_23 and Pr_12. These parent + references merely help describe the "tree" of classifications, but + is generally unnecessary. Using lightweight classifications are + recommended and is the default. + + :raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements. + + :return: The newly added IfcClassificationReference + or `None` if `products` was empty list. + + Example: + + .. code:: python + + # Option 1: adding and assigning a new reference from scratch + wall_type = model.by_type("IfcWallType")[0] + classification = ifcopenshell.api.classification.add_classification( + model, classification="MyCustomClassification") + ifcopenshell.api.classification.add_reference(model, + products=[wall_type], classification=classification, + identification="W_01", name="Interior Walls") + + # Option 2: adding a popular classification from a library + library = ifcopenshell.open("/path/to/Uniclass.ifc") + lib_classification = library.by_type("IfcClassification")[0] + classification = ifcopenshell.api.classification.add_classification( + model, classification=lib_classification) + reference = [r for r in library.by_type("IfcClassificationReference") + if r.Identification == "XYZ"][0] + ifcopenshell.api.classification.add_reference(model, + products=[wall_type], classification=classification, + reference=reference) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "products": products, + "reference": reference, + "identification": identification, + "name": name, + "classification": classification, + "is_lightweight": is_lightweight, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + if not self.settings["products"]: + return + + if self.settings["reference"]: + referenced = ifcopenshell.util.element.get_referenced_elements(self.settings["reference"]) + if set(self.settings["products"]).issubset(referenced): + # nothing to do, all elements already have this reference assigned + return self.settings["reference"] + + self.rooted_products: set[ifcopenshell.entity_instance] = set() + self.non_rooted_products: set[ifcopenshell.entity_instance] = set() + for product in self.settings["products"]: + if product.is_a("IfcRoot"): + self.rooted_products.add(product) + else: + self.non_rooted_products.add(product) + + if self.non_rooted_products and self.file.schema == "IFC2X3": + raise TypeError(f"Cannot add reference to non-IfcRoot element in IFC2X3: {self.non_rooted_products}.") + + if self.settings["reference"]: + return self.add_from_library() + return self.add_from_identification() + + def add_from_identification(self): + reference = self.get_existing_reference(self.settings["identification"]) + if not reference: + reference = self.file.createIfcClassificationReference( + Name=self.settings["name"], ReferencedSource=self.settings["classification"] + ) + if self.file.schema == "IFC2X3": + reference.ItemReference = self.settings["identification"] + else: + reference.Identification = self.settings["identification"] + + self.update_relationships(reference) + return reference + + def add_from_library(self) -> ifcopenshell.entity_instance: + if hasattr(self.settings["reference"], "ItemReference"): + identification = self.settings["reference"].ItemReference # IFC2X3 + else: + identification = self.settings["reference"].Identification + + reference = self.get_existing_reference(identification) + if not reference: + migrator = ifcopenshell.util.schema.Migrator() + + if self.settings["is_lightweight"]: + old_referenced_source = self.settings["reference"].ReferencedSource + self.settings["reference"].ReferencedSource = None + else: + classification_name = self.settings["classification"].Name + existing_classification = [ + c for c in self.file.by_type("IfcClassification") if c.Name == classification_name + ] + + reference = migrator.migrate(self.settings["reference"], self.file) + + if self.settings["is_lightweight"]: + reference.ReferencedSource = self.settings["classification"] + self.settings["reference"].ReferencedSource = old_referenced_source + elif existing_classification: + to_delete = set() + for traversed_reference in self.file.traverse(reference): + if traversed_reference.ReferencedSource.is_a("IfcClassification"): + to_delete.add(traversed_reference.ReferencedSource) + traversed_reference.ReferencedSource = existing_classification[0] + break + for element in to_delete: + self.file.remove(element) + + self.update_relationships(reference) + return reference + + def get_existing_reference(self, identification: Optional[str] = None) -> Union[ifcopenshell.entity_instance, None]: + for reference in self.file.by_type("IfcClassificationReference"): + if self.file.schema == "IFC2X3": + if reference.ItemReference == identification: + return reference + else: + if reference.Identification == identification: + return reference + + def update_relationships(self, reference: ifcopenshell.entity_instance) -> None: + root_rel, non_root_rel = None, None + if self.rooted_products: + if self.file.schema == "IFC2X3": + for rel in self.file.by_type("IfcRelAssociatesClassification"): + if rel.RelatingClassification == reference: + root_rel = rel + break + else: + root_rel = next(iter(reference.ClassificationRefForObjects), None) + + if root_rel: + related_objects = set(root_rel.RelatedObjects) | self.rooted_products + root_rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(self.file, element=root_rel) + else: + self.file.create_entity( + "IfcRelAssociatesClassification", + OwnerHistory=ifcopenshell.api.owner.create_owner_history(self.file), + GlobalId=ifcopenshell.guid.new(), + RelatedObjects=list(self.rooted_products), + RelatingClassification=reference, + ) + + if self.non_rooted_products: + # NOTE: Only Ifc4+. Ifc2x3 is already handled by raising TypeError + non_root_rel = next(iter(reference.ExternalReferenceForResources), None) + if non_root_rel: + related_objects = set(non_root_rel.RelatedResourceObjects) | self.non_rooted_products + non_root_rel.RelatedResourceObjects = list(related_objects) + else: + self.file.create_entity( + "IfcExternalReferenceRelationship", + RelatingReference=reference, + RelatedResourceObjects=list(self.non_rooted_products), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_classification.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..b2091c0eca00ba045abf6a5fa3085710e5a58344 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_classification.py @@ -0,0 +1,44 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_classification( + file: ifcopenshell.file, classification: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcClassification + + For more information about the attributes and data types of an + IfcClassification, consult the IFC documentation. + + :param classification: The IfcClassification entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + classification = model.by_type("IfcClassification")[0] + # Change the name of the classification system to "Foo" + ifcopenshell.api.classification.edit_classification(model, + classification=classification, attributes={"Name": "Foo"}) + """ + for name, value in attributes.items(): + setattr(classification, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a85d40f964203be393b3f93ad44358b556e1f1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/edit_reference.py @@ -0,0 +1,44 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_reference( + file: ifcopenshell.file, reference: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcClassificationReference + + For more information about the attributes and data types of an + IfcClassificationReference, consult the IFC documentation. + + :param reference: The IfcClassificationReference entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + reference = model.by_type("IfcClassification")[0] + # Change the name of the reference to "Foo" + ifcopenshell.api.classification.edit_reference(model, + reference=reference, attributes={"Name": "Foo"}) + """ + for name, value in attributes.items(): + setattr(reference, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_classification.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_classification.py new file mode 100644 index 0000000000000000000000000000000000000000..38382eda91990bd0727bbde6d29b38c153f3f334 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_classification.py @@ -0,0 +1,76 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_classification(file: ifcopenshell.file, classification: ifcopenshell.entity_instance) -> None: + """Removes an IfcClassification from the project and all references + + The classification and all of its relationships, children references, + and relationships between objects and child references are completely + removed from a project. + + :param classification: The IfcClassification entity you want to remove + :return: None + + Example: + + .. code:: python + + classification = model.by_type("IfcClassification")[0] + ifcopenshell.api.classification.remove_classification(model, + classification=classification) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(classification) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, classification: ifcopenshell.entity_instance) -> None: + references = self.get_references(classification) + for reference in references: + self.file.remove(reference) + self.file.remove(classification) + for rel in self.file.by_type("IfcRelAssociatesClassification"): + if not rel.RelatingClassification: + history = rel.OwnerHistory + self.file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + + if self.file.schema != "IFC2X3": + for rel in self.file.by_type("IfcExternalReferenceRelationship"): + if not rel.RelatingReference: + self.file.remove(rel) + + def get_references(self, classification: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + results = [] + if self.file.schema == "IFC2X3": + for reference in self.file.by_type("IfcClassificationReference"): + if reference.ReferencedSource == classification: + results.append(reference) + else: + for reference in classification.HasReferences: + results.append(reference) + results.extend(self.get_references(reference)) + return results diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..fe4dd3b758e4e0d83666bb12208a107ab87446bf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/classification/remove_reference.py @@ -0,0 +1,117 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def remove_reference( + file: ifcopenshell.file, + reference: ifcopenshell.entity_instance, + products: list[ifcopenshell.entity_instance], +) -> None: + """Removes a classification reference from the list of products + + If the classification reference is no longer associated to any products, + the classification reference itself is also removed. + + :param reference: The IfcClassificationReference entity of the + relationship you want to remove. + :param product: The list fo object entities of the relationship you want to + remove. + + :raises TypeError: If file is IFC2X3 and `products` has non-IfcRoot elements. + + :return: None + + Example: + + .. code:: python + + wall_type = model.by_type("IfcWallType")[0] + classification = ifcopenshell.api.classification.add_classification( + model, classification="MyCustomClassification") + reference = ifcopenshell.api.classification.add_reference(model, + products=[wall_type], classification=classification, + identification="W_01", name="Interior Walls") + ifcopenshell.api.classification.remove_reference(model, + reference=reference, products=[wall_type]) + """ + is_ifc2x3 = file.schema == "IFC2X3" + products_set = set(products) + referenced = ifcopenshell.util.element.get_referenced_elements(reference) + products_set -= products_set.difference(referenced) + + # all products are already unassigned from a reference + if not products_set: + return + + rooted_products: set[ifcopenshell.entity_instance] = set() + non_rooted_products: set[ifcopenshell.entity_instance] = set() + for product in products: + if product.is_a("IfcRoot"): + rooted_products.add(product) + else: + non_rooted_products.add(product) + + if non_rooted_products and is_ifc2x3: + raise TypeError(f"Cannot add reference to non-IfcRoot element in IFC2X3: {non_rooted_products}.") + + if rooted_products: + reference_rels: set[ifcopenshell.entity_instance] = set() + for product in rooted_products: + reference_rels.update(product.HasAssociations) + + reference_rels = { + rel + for rel in reference_rels + if rel.is_a("IfcRelAssociatesClassification") and rel.RelatingClassification == reference + } + + for rel in reference_rels: + related_objects = set(rel.RelatedObjects) - rooted_products + if related_objects: + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + if non_rooted_products: + reference_rels: set[ifcopenshell.entity_instance] = set() + for product in non_rooted_products: + rels = getattr(product, "HasExternalReferences", None) + if rels is None: + rels = getattr(product, "HasExternalReference", []) + reference_rels.update(rels) + + reference_rels = {rel for rel in reference_rels if rel.RelatingReference == reference} + for rel in reference_rels: + related_objects = set(rel.RelatedResourceObjects) - non_rooted_products + if related_objects: + rel.RelatedResourceObjects = list(related_objects) + else: + file.remove(rel) + + # TODO: we only handle lightweight classifications here + referenced_elements = ifcopenshell.util.element.get_referenced_elements(reference) + if not referenced_elements: + file.remove(reference) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bb1c7c5243b5379dc45fe6ce8cf150857c1aa9bb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/__init__.py @@ -0,0 +1,33 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +""" +Coordinate Geometry (cogo) functions primarily for survey points and control monument for layout, parcels, etc. +""" + +from .add_survey_point import add_survey_point +from .assign_survey_point import assign_survey_point +from .edit_survey_point import edit_survey_point +from .bearing2dd import bearing2dd + +__all__ = [ + "add_survey_point", + "assign_survey_point", + "bearing2dd", + "edit_survey_point", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/add_survey_point.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/add_survey_point.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a10661d30cc6fdd9dacd90073c6c6096775a8e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/add_survey_point.py @@ -0,0 +1,59 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.spatial +import ifcopenshell.util.representation +from ifcopenshell import entity_instance +from typing import Union + + +def add_survey_point( + file: ifcopenshell.file, survey_point: entity_instance, site: Union[entity_instance, None] = None +) -> entity_instance: + """ + Adds a single survey point to the model based on IFC Concept Template 4.1.7.1.2.5. + Survey points are located relative to IfcRepresentationContext.WorldCoordinateSystem + + :param survey_point: The survey point + :return: an IfcAnnotation entity + + Example: + + .. code:: python + + annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0))) + """ + context = ifcopenshell.util.representation.get_context(file, "Model", "Annotation", "MODEL_VIEW") + shape_representation = file.createIfcShapeRepresentation( + ContextOfItems=context, RepresentationIdentifier="Annotation", RepresentationType="Point", Items=[survey_point] + ) + representation = file.createIfcProductDefinitionShape(Representations=[shape_representation]) + annotation = file.createIfcAnnotation( + ifcopenshell.guid.new(), + ObjectPlacement=context.WorldCoordinateSystem, + Representation=representation, + PredefinedType="SURVEY", + ) + + if site == None: + site = file.by_type("IfcSite")[0] + + ifcopenshell.api.spatial.assign_container(file, relating_structure=site, products=[annotation]) + + return annotation diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/assign_survey_point.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/assign_survey_point.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a6ba0acc6852abc5e2f7573dbbf3ea17c772df --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/assign_survey_point.py @@ -0,0 +1,39 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +from ifcopenshell import entity_instance +import typing + + +def assign_survey_point(annotation: entity_instance, survey_point: entity_instance): + """ + Assigns a coordinate point to a survey point annotation + + :param annotaton: The survey point annotation + :param survey_point: The survey point + :return: None + + Example: + + .. code:: python + + annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0))) + ifcopenshell.api.cogo.assign_surve_point(annotation,file.createIfcCartesianPoint(4000.0,3500.0,100.0)) + """ + annotation.Representation.Representations[0].Items = [survey_point] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/bearing2dd.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/bearing2dd.py new file mode 100644 index 0000000000000000000000000000000000000000..895215f066f844dfc36c7f48ac700f33759f89a9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/bearing2dd.py @@ -0,0 +1,106 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.geolocation + + +def bearing2dd(bearing: str) -> float: + """ + Converts a quadrant bearing string to decimal degrees + + The format of the string is "N|S dd (mm (ss.s)) E|W" + where: + N|S is N or S for North or South + dd is degree (required) + mm is minute (optional, but required if second is provided) + ss.s is second (required) + E|W is E or W for East or West + + :param str: the bearing string + :return: Angle in radian + """ + error_msg = "Invalid bearing string" + + bearing = bearing.strip() # trim external white space + bearing = " ".join(bearing.split()) # make sure all parts separated by a single space + parts = bearing.split() + nParts = len(parts) + if nParts < 3 or 5 < nParts: + raise ValueError(error_msg) + + cY = parts[0] + cY = cY.upper() + if cY != "N" and cY != "S": + raise ValueError(error_msg) + + cX = parts[-1] + cX = cX.upper() + if cX != "E" and cX != "W": + raise ValueError(error_msg) + + d = 0 + m = 0 + s = 0.0 + ms = 0 + + if nParts == 3: + d = int(parts[1]) + elif nParts == 4: + d = int(parts[1]) + m = int(parts[2]) + elif nParts == 5: + d = int(parts[1]) + m = int(parts[2]) + s = float(parts[3]) + + # s in a decimal number + # need to break it into whole seconds and milliseconds + ms = 100.0 * (s - int(s)) + s = int(s) + + if d < 0 or (m < 0 or 60 <= m) or (s < 0 or 60 <= s) or ms < 0: + raise ValueError(error_msg) + + if cY == "N" and cX == "E": + angle = 90.0 + sign = -1.0 + elif cY == "N" and cX == "W": + angle = 90.0 + sign = 1.0 + elif cY == "S" and cX == "E": + angle = 270.0 + sign = 1.0 + elif cY == "S" and cX == "W": + angle = 270.0 + sign = -1.0 + + try: + dms = ifcopenshell.util.geolocation.dms2dd(d, m, s, ms) + except ValueError: + raise ValueError(error_msg) + + if dms < 0.0 or 90.0 < dms: + raise ValueError(error_msg) + + angle += sign * dms + + # S 90 E will evaluate to 360 + if angle == 360.0: + angle = 0.0 + + return angle diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/edit_survey_point.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/edit_survey_point.py new file mode 100644 index 0000000000000000000000000000000000000000..d2208dc649afd5f96e08ec27962b81aa1ef71e7e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cogo/edit_survey_point.py @@ -0,0 +1,41 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +from ifcopenshell import entity_instance +import typing + + +def edit_survey_point(annotation: entity_instance, x: float, y: float, z: float = 0.0): + """ + Edits the location of a previously defined survey point + + :param survey_point: The survey point + :return: None + + Example: + + .. code:: python + + annotation = ifcopenshell.api.cogo.add_survey_point(file,file.createIfcCartesianPoint(4000.0,3500.0))) + ifcopenshell.api.cogo.edit_surve_point(annotation,3500.0,2000.0) + """ + if annotation.Representation.Representations[0].Items[0].Dim == 2: + annotation.Representation.Representations[0].Items[0].Coordinates = (x, y) + else: + annotation.Representation.Representations[0].Items[0].Coordinates = (x, y, z) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b78f91f0261ce9d58a31c8ca0745a3fb38beaa19 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/__init__.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Constraints are an advanced feature allowing you to specify parametric +limits on properties + +Warning: usage of constraints are mostly untested in real life applications. +""" + +from .. import wrap_usecases +from .add_metric import add_metric +from .add_metric_reference import add_metric_reference +from .add_objective import add_objective +from .assign_constraint import assign_constraint +from .edit_metric import edit_metric +from .edit_objective import edit_objective +from .remove_constraint import remove_constraint +from .remove_metric import remove_metric +from .unassign_constraint import unassign_constraint + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_metric", + "add_metric_reference", + "add_objective", + "assign_constraint", + "edit_metric", + "edit_objective", + "remove_constraint", + "remove_metric", + "unassign_constraint", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..001c86a540ca5928d26d7c6e0486e11e4ccb04c6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric.py @@ -0,0 +1,54 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def add_metric(file: ifcopenshell.file, objective: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Add a new metric benchmark + + Qualitative constraints may have a series of quantitative benchmarks + linked to it known as metrics. Metrics may be parametrically linked to + computed model properties or quantities. Metrics need to be satisfied + to meet the objective of the constraint. + + :param objective: The IfcObjective that this metric is a benchmark of. + :return: The newly created IfcMetric entity + + Example: + + .. code:: python + + objective = ifcopenshell.api.constraint.add_objective(model) + metric = ifcopenshell.api.constraint.add_metric(model, + objective=objective) + """ + metric = file.create_entity( + "IfcMetric", + **{ + "Name": "Unnamed", + "ConstraintGrade": "NOTDEFINED", + "Benchmark": "EQUALTO", + }, + ) + if objective: + benchmark_values: list[ifcopenshell.entity_instance] + benchmark_values = list(objective.BenchmarkValues or []) + benchmark_values.append(metric) + objective.BenchmarkValues = benchmark_values + return metric diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..63ecfeb3c0b923c405b8013a54a5700da8556975 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_metric_reference.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def add_metric_reference( + file: ifcopenshell.file, metric: ifcopenshell.entity_instance, reference_path: str +) -> list[ifcopenshell.entity_instance]: + """ + Adds a chain of references to a metric. The reference path is a string of the form "attribute.attribute.attribute" + Used to reference a value of an attribute of an instance through a metric objective entity. + """ + references_created = [] + if reference_path: + attributes = reference_path.split(".") + for i in range(len(attributes)): + if i == 0: + reference = file.create_entity("IfcReference") + reference.AttributeIdentifier = attributes[i] + metric.ReferencePath = reference + references_created.append(reference) + else: + reference = file.create_entity("IfcReference") + reference.AttributeIdentifier = attributes[i] + references_created[i - 1].InnerReference = reference + references_created.append(reference) + return references_created diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_objective.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_objective.py new file mode 100644 index 0000000000000000000000000000000000000000..4c434a9edf3046991fefd7ceaff02e971b61e42d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/add_objective.py @@ -0,0 +1,46 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def add_objective(file: ifcopenshell.file) -> ifcopenshell.entity_instance: + """Add a new objective constraint + + Parametric constraints may be defined by the user. The constraint is defined + by first creating an objective describing the purpose of the constraint and + whether it is a hard or soft constraint. Later on, metrics may be added to + check whether the constraint has been met by connecting it to properties and + quantities. See ifcopenshell.api.constraint.add_metric for more information. + + :return: The newly created IfcObjective entity + + Example: + + .. code:: python + + # Create a new objective for code compliance requirements + objective = ifcopenshell.api.constraint.add_objective(model) + objective.ConstraintGrade = "ADVISORY" + objective.ObjectiveQualifier = "CODECOMPLIANCE" + # Note: the objective right now is purely qualitative and for + # information purposes. You may wish to add quantiative metrics. + """ + return file.create_entity( + "IfcObjective", **{"Name": "Unnamed", "ConstraintGrade": "NOTDEFINED", "ObjectiveQualifier": "NOTDEFINED"} + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/assign_constraint.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/assign_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..ac021840c75e5c583b3a0d67ce296111ea8b72e7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/assign_constraint.py @@ -0,0 +1,91 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +from typing import Union + + +def assign_constraint( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + constraint: ifcopenshell.entity_instance, +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns a constraint to a list of products + + This assigns a relationship between a product and a constraint, so that + when a product's properties and quantities do not match the requirements + of the constraint's metrics, results can be flagged. + + It is assumed (but not explicit in the IFC documentation) that + constraints are inherited from the type. This way, it is not necessary + to create lots of constraint assignments. + + :param products: The list of products the constraint applies to. This is anything + which can have properties or quantities. + :param constraint: The IfcObjective constraint + :return: The new or updated IfcRelAssociatesConstraint relationship + or `None` if `products` was an empty list. + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(products, constraint) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, products: list[ifcopenshell.entity_instance], constraint: ifcopenshell.entity_instance): + if not products: + return + products_set = set(products) + + rels = self.get_constraint_rels(constraint) + related_objects = set() + for rel in rels: + related_objects.update(rel.RelatedObjects) + + products_to_assign = products_set - related_objects + if not products_to_assign: + return rels[0] + + rel = next(iter(rels), None) + + if rel: + related_objects = set(rel.RelatedObjects) | products_to_assign + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(self.file, element=rel) + return rel + + return self.file.create_entity( + "IfcRelAssociatesConstraint", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(self.file), + "RelatingConstraint": constraint, + "RelatedObjects": list(products_to_assign), + } + ) + + def get_constraint_rels(self, constraint: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + rels = [] + for rel in self.file.get_inverse(constraint): + if rel.is_a("IfcRelAssociatesConstraint"): + rels.append(rel) + return rels diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_metric.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..39678467598dec24e5d56e24a5215b9ffa97e502 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_metric.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_metric(file: ifcopenshell.file, metric: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edit the attributes of a metric + + For more information about the attributes and data types of an + IfcMetric, consult the IFC documentation. + + :param metric: The IfcMetric you want to edit. + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + objective = ifcopenshell.api.constraint.add_objective(model) + metric = ifcopenshell.api.constraint.add_metric(model, + objective=objective) + ifcopenshell.api.constraint.edit_metric(model, + metric=metric, attributes={"ConstraintGrade": "HARD"}) + """ + for name, value in attributes.items(): + setattr(metric, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_objective.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_objective.py new file mode 100644 index 0000000000000000000000000000000000000000..3cd75356a7b34aa6cd205fe2cbeeb63f243bd04d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/edit_objective.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_objective( + file: ifcopenshell.file, objective: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edit the attributes of a objective + + For more information about the attributes and data types of an + IfcObjective, consult the IFC documentation. + + :param objective: The IfcObjective you want to edit. + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + objective = ifcopenshell.api.constraint.add_objective(model) + ifcopenshell.api.constraint.edit_objective(model, + objective=objective, attributes={"ConstraintGrade": "HARD"}) + """ + for name, value in attributes.items(): + setattr(objective, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_constraint.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..b6bd53221b1d4f0540c393db5a8c61a2c05eb601 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_constraint.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_constraint(file: ifcopenshell.file, constraint: ifcopenshell.entity_instance) -> None: + """Remove a constraint (typically an objective) + + Removes a constraint definition and all of its associations to any + products. Typically this would be an IfcObjective, although technically + you can associate IfcMetrics ith products too, though the meaning may be + unclear. + + :param constraint: The IfcObjective you want to remove. + :return: None + + Example: + + .. code:: python + + objective = ifcopenshell.api.constraint.add_objective(model) + ifcopenshell.api.constraint.remove_constraint(model, + constraint=objective) + """ + file.remove(constraint) + for rel in file.by_type("IfcRelAssociatesConstraint"): + if not rel.RelatingConstraint: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_metric.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_metric.py new file mode 100644 index 0000000000000000000000000000000000000000..96d752c534bdd6d775ac5749e7a6fba641dbe8ee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/remove_metric.py @@ -0,0 +1,68 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +import ifcopenshell.util.element + + +def remove_metric(file: ifcopenshell.file, metric: ifcopenshell.entity_instance) -> None: + """Remove a metric benchmark + + Removes a metric benchmark and all of its associations to any products + and objectives. + + :param metric: The IfcMetric you want to remove. + :return: None + + Example: + + .. code:: python + + objective = ifcopenshell.api.constraint.add_objective(model) + metric = ifcopenshell.api.constraint.add_metric(model, + objective=objective) + ifcopenshell.api.constraint.remove_metric(model, + metric=metric) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(metric) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, metric: ifcopenshell.entity_instance) -> None: + if metric.ReferencePath: + reference = metric.ReferencePath + self.delete_reference(reference) + + self.file.remove(metric) + for rel in self.file.by_type("IfcRelAssociatesConstraint"): + if not rel.RelatingConstraint: + history = rel.OwnerHistory + self.file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + for resource_rel in self.file.by_type("IfcResourceConstraintRelationship"): + if not resource_rel.RelatingConstraint: + self.file.remove(resource_rel) + + def delete_reference(self, reference: ifcopenshell.entity_instance) -> None: + if reference.InnerReference: + self.delete_reference(reference.InnerReference) + self.file.remove(reference) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/unassign_constraint.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/unassign_constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..6fb1067c2a4ebe63fd9fb666f93198db26aecc6f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/constraint/unassign_constraint.py @@ -0,0 +1,79 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_constraint( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + constraint: ifcopenshell.entity_instance, +) -> None: + """Unassigns a constraint from a list of products + + The constraint will not be deleted and is available to be assigned to + other products. + + :param products: The list of products the constraint applies to. + :param constraint: The IfcObjective constraint + :return: None + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(products, constraint) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, products_: list[ifcopenshell.entity_instance], constraint: ifcopenshell.entity_instance): + if not products_: + return + products_set = set(products_) + + rels = self.get_constraint_rels(constraint) + related_objects = set() + for rel in rels: + related_objects.update(rel.RelatedObjects) + + if not related_objects.intersection(products_set): + return + + for rel in rels: + related_objects = set(rel.RelatedObjects) + if not related_objects.intersection(products_set): + continue + related_objects -= products_set + if related_objects: + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(self.file, element=rel) + continue + + history = rel.OwnerHistory + self.file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + + def get_constraint_rels(self, cosntraint: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + rels = [] + for rel in self.file.get_inverse(cosntraint): + if rel.is_a("IfcRelAssociatesConstraint"): + rels.append(rel) + return rels diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bcc0985c1596971fb39c03545b34432f3461ba3b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/__init__.py @@ -0,0 +1,34 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Processes and costs may be controlled by other entities which indicate +constraints that determine how they can change + +This is an advanced feature mostly used in 4D/5D +""" + +from .. import wrap_usecases +from .assign_control import assign_control +from .unassign_control import unassign_control + +wrap_usecases(__path__, __name__) + +__all__ = [ + "assign_control", + "unassign_control", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/assign_control.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/assign_control.py new file mode 100644 index 0000000000000000000000000000000000000000..cd7c398a5426a4ad1a4b9f6b661fa3f69b113c32 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/assign_control.py @@ -0,0 +1,108 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +from typing import Union + + +def assign_control( + file: ifcopenshell.file, + relating_control: ifcopenshell.entity_instance, + related_objects: list[ifcopenshell.entity_instance], +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns a planning control or constraint to a list of objects. + + IFC can describe concepts that control other objects. For example, a + planning calendar controls the availability of working days for + construction planning. As another example, a cost item might constrain + or limit the ability to procure and build a product. + + This usecase lets you assign controls following the rules of the IFC + specification. This is an advanced topic and assumes knowledge of the + IFC concepts to determine what is allowed to control what. In the + future, this API will likely be deprecated in favour of multiple usecase + specific APIs. + + :param relating_control: The IfcControl entity that is creating the + control or constraint + :param related_objects: The list of IfcObjectDefinition that is being controlled + :return: The newly created IfcRelAssignsToControl. If relationship already + existed before and wasn't changed then returns None. + + Example: + + .. code:: python + + # One common usecase is to assign a calendar to a task + calendar = ifcopenshell.api.sequence.add_work_calendar(model) + schedule = ifcopenshell.api.sequence.add_work_schedule(model) + task = ifcopenshell.api.sequence.add_task(model, + work_schedule=schedule) + + # All subtasks will inherit this calendar, so assigning a single + # calendar to the root task effectively defines a "default" calendar + ifcopenshell.api.control.assign_control(model, + relating_control=calendar, related_objects=[task]) + + # Another common example might be relating a cost item and a product + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + cost_item = ifcopenshell.api.cost.add_cost_item(model, + cost_schedule=schedule) + ifcopenshell.api.control.assign_control(model, + relating_control=cost_item, related_objects=[wall]) + """ + # Filter out already assigned objects. + related_objects_set = set(related_objects) + objects_to_assign: set[ifcopenshell.entity_instance] = set() + + control_assignments = set(relating_control.Controls) + if control_assignments: + for obj in related_objects_set: + existing_assignment = next((a for a in obj.HasAssignments if a in control_assignments), None) + # Skip objects already assigned to this control. + if existing_assignment: + continue + objects_to_assign.add(obj) + else: + objects_to_assign = related_objects_set + + if not objects_to_assign: + return None + + controls: Union[ifcopenshell.entity_instance, None] + controls = next(iter(relating_control.Controls), None) + + if controls: + related_objects_new: list[ifcopenshell.entity_instance] = list(controls.RelatedObjects) + related_objects_new.extend(objects_to_assign) + controls.RelatedObjects = list(related_objects_new) + ifcopenshell.api.owner.update_owner_history(file, element=controls) + else: + controls = file.create_entity( + "IfcRelAssignsToControl", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": list(objects_to_assign), + "RelatingControl": relating_control, + }, + ) + return controls diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/unassign_control.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/unassign_control.py new file mode 100644 index 0000000000000000000000000000000000000000..57e47418ef172b60aa2b78bf1bd5eddcde00b486 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/control/unassign_control.py @@ -0,0 +1,65 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_control( + file: ifcopenshell.file, + relating_control: ifcopenshell.entity_instance, + related_objects: list[ifcopenshell.entity_instance], +) -> None: + """Unassigns a planning control or constraint to an object + + :param relating_control: The IfcControl entity that is creating the + control or constraint + :param related_objects: The list IfcObjectDefinitions that is being controlled + :return: None + + Example: + + .. code:: python + + # Let's relate a cost item and a product + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + cost_item = ifcopenshell.api.cost.add_cost_item(model, + cost_schedule=schedule) + ifcopenshell.api.control.assign_control(model, + relating_control=cost_item, related_objects=[wall]) + + # And now let's change our mind + ifcopenshell.api.control.unassign_control(model, + relating_control=cost_item, related_objects=[wall]) + """ + related_objects_set = set(related_objects) + control_assignments = set(relating_control.Controls) + rels = set(rel for obj in related_objects_set for rel in obj.HasAssignments if rel in control_assignments) + + for rel in rels: + related_objects_new = set(rel.RelatedObjects) - related_objects_set + if related_objects_new: + rel.RelatedObjects = list(related_objects_new) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5c0695b2721406663372263cdd6afeb00b9bc581 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/__init__.py @@ -0,0 +1,72 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Manage cost schedules, cost items, cost estimation and parametric quantity +take-off + +IFC supports storing cost schedules and detailed cost breakdown structures, +including formulas, subtotals, and parametric links to model element +quantities. +""" + +from .. import wrap_usecases +from .add_cost_item import add_cost_item +from .add_cost_item_quantity import add_cost_item_quantity +from .add_cost_schedule import add_cost_schedule +from .add_cost_value import add_cost_value +from .assign_cost_item_quantity import assign_cost_item_quantity +from .assign_cost_value import assign_cost_value +from .calculate_cost_item_resource_value import calculate_cost_item_resource_value +from .copy_cost_item import copy_cost_item +from .copy_cost_item_values import copy_cost_item_values +from .copy_cost_schedule import copy_cost_schedule +from .edit_cost_item import edit_cost_item +from .edit_cost_item_quantity import edit_cost_item_quantity +from .edit_cost_schedule import edit_cost_schedule +from .edit_cost_value import edit_cost_value +from .edit_cost_value_formula import edit_cost_value_formula +from .remove_cost_item import remove_cost_item +from .remove_cost_item_quantity import remove_cost_item_quantity +from .remove_cost_schedule import remove_cost_schedule +from .remove_cost_value import remove_cost_value +from .unassign_cost_item_quantity import unassign_cost_item_quantity + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_cost_item", + "add_cost_item_quantity", + "add_cost_schedule", + "add_cost_value", + "assign_cost_item_quantity", + "assign_cost_value", + "calculate_cost_item_resource_value", + "copy_cost_item", + "copy_cost_item_values", + "copy_cost_schedule", + "edit_cost_item", + "edit_cost_item_quantity", + "edit_cost_schedule", + "edit_cost_value", + "edit_cost_value_formula", + "remove_cost_item", + "remove_cost_item_quantity", + "remove_cost_schedule", + "remove_cost_value", + "unassign_cost_item_quantity", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item.py new file mode 100644 index 0000000000000000000000000000000000000000..70c0cfc06c56d1864b457505d7696c0e5c6ef7b8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item.py @@ -0,0 +1,65 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.control +import ifcopenshell.api.root +import ifcopenshell.api.nest +import ifcopenshell.guid +from typing import Optional + + +def add_cost_item( + file: ifcopenshell.file, + cost_schedule: Optional[ifcopenshell.entity_instance] = None, + cost_item: Optional[ifcopenshell.entity_instance] = None, +) -> ifcopenshell.entity_instance: + """Add a new cost item + + A cost item represents a single line item in a cost schedule. Cost items + may then be broken down into cost subitems. + + Either `cost_schedule` or `cost_item` must be provided. + + :param cost_schedule: If the cost item is to be added as a root or top + level cost item to a cost schedule, the IfcCostSchedule may be + specified. This is mutually exlclusive to the cost_item parameter. + :param cost_item: If the cost item is to be added as a subitem to an + existing cost item, the parent IfcCostItem may be specified. This is + mutually exclusive to the cost_schedule parameter. + :return: The newly created IfcCostItem + + Example: + + .. code:: python + + # The very first cost item must be in a cost schedule + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + + # You may add cost items as top level item in the schedule + item1 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # Alternatively you may add them as subitems + item2 = ifcopenshell.api.cost.add_cost_item(model, cost_item=item1) + """ + cost_item_ = ifcopenshell.api.root.create_entity(file, ifc_class="IfcCostItem") + + if cost_schedule: + ifcopenshell.api.control.assign_control(file, cost_schedule, [cost_item_]) + elif cost_item: + ifcopenshell.api.nest.assign_object(file, related_objects=[cost_item_], relating_object=cost_item) + return cost_item_ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item_quantity.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item_quantity.py new file mode 100644 index 0000000000000000000000000000000000000000..5e8fcb0b3497f4677e50fb960e8046fed25fb08a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_item_quantity.py @@ -0,0 +1,90 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api +import ifcopenshell.util.unit + + +def add_cost_item_quantity( + file: ifcopenshell.file, + cost_item: ifcopenshell.entity_instance, + ifc_class: ifcopenshell.util.unit.QUANTITY_CLASS = "IfcQuantityCount", +) -> ifcopenshell.entity_instance: + """Adds a new quantity associated with a cost item + + Cost items calculate their subtotal by multiplying the sum of the cost + item's "values" by the sum of the cost item's "quantities". The + quantities may be either parametrically linked to quantities measured on + physical product, or manually specified. + + The quantity must be of a particular type, common examples are: + + - IfcQuantityCount: to count the total occurrences of a product, useful + for things like doors, windows, and furniture + - IfcQuantityNumber: any other generic numeric quantity + - IfcQuantityLength + - IfcQuantityArea + - IfcQuantityVolume + - IfcQuantityWeight + - IfcQuantityTime + + A cost item must not mix quantities of different types. + + If an IfcQuantityCount is used, then this API will automatically count + all products that this cost item controls (see + ifcopenshell.api.controls.assign_control) and prefill that quantity. + + For all other quantity types, the quantity is left as zero and the user + must either manually specify the quantity or parametrically link it + using another API call. + + :param cost_item: The IfcCostItem to add the quantity to + :param ifc_class: The type of quantity to add + :return: The newly created quantity entity, chosen from the ifc_class + parameter + + Example: + + .. code:: python + + chair = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + ifcopenshell.api.control.assign_control(model, + relating_control=item, related_objects=[chair]) + + # Let's assume we want to count the amount of chairs to calculate our cost item + # Because this is an IfcQuantityCount the count will be automatically set to "1" chair + ifcopenshell.api.cost.add_cost_item_quantity(model, + cost_item=item, ifc_class="IfcQuantityCount") + """ + quantity = file.create_entity(ifc_class, Name="Unnamed") + # 3 IfcPhysicalSimpleQuantity Value + # This is a bold assumption + # https://forums.buildingsmart.org/t/how-does-a-cost-item-know-that-it-is-counting-a-controlled-product/3564 + if ifc_class == "IfcQuantityCount": + count = 0 + for rel in cost_item.Controls: + count += len(rel.RelatedObjects) + quantity[3] = count + else: + quantity[3] = 0.0 + quantities = list(cost_item.CostQuantities or []) + quantities.append(quantity) + cost_item.CostQuantities = quantities + return quantity diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_schedule.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..19f0762b695f9393cbdc127a00b96a146481b78b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_schedule.py @@ -0,0 +1,62 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.root +import ifcopenshell.api.sequence +from datetime import datetime +from typing import Optional + + +def add_cost_schedule( + file: ifcopenshell.file, name: Optional[str] = None, predefined_type: str = "NOTDEFINED" +) -> ifcopenshell.entity_instance: + """Add a new cost schedule + + A cost schedule is a group of cost items which typically represent a + cost plan or breakdown of the project. This may be used as an estimate, + bid, or actual cost. + + Alternatively, a cost schedule may also represent a schedule of rates, + which include cost items which capture unit rates for different elements + or processes. + + As such, creating a cost schedule is necessary prior to creating and + managing any cost items. + + :param name: The name of the cost schedule. + :param predefined_type: The predefined type of the cost schedule, chosen + from a valid type in the IFC documentation for + IfcCostScheduleTypeEnum + :return: The newly created IfcCostSchedule entity + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + # Now that we have a cost schedule, we may add cost items to it + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + """ + cost_schedule = ifcopenshell.api.root.create_entity( + file, + ifc_class="IfcCostSchedule", + predefined_type=predefined_type, + name=name, + ) + cost_schedule.UpdateDate = ifcopenshell.api.sequence.add_date_time(file, datetime.now()) + return cost_schedule diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_value.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_value.py new file mode 100644 index 0000000000000000000000000000000000000000..972849ca96f809ff406a0aa2545116016e508f1d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/add_cost_value.py @@ -0,0 +1,105 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def add_cost_value(file: ifcopenshell.file, parent: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Adds a new value or subvalue to a cost item + + A cost item's subtotal can be specified in two ways. + + Option 1 is by simply manually specifying the subtotal value, which + represents the full cost of that cost item. This option occurs when a + cost item has no quantities associated with it. + + Option 2 is by specifying a unit cost value of the cost item, which is + then multiplied by the associated quantity of the cost item, to give us + the subtotal. This option occurs when a cost item has quantities + associated with it. + + For either option 1 (full cost value) or option 2 (unit cost value), the + cost value may be specified as a single number, or as a sum of + subcomponents or formulas (e.g. multiplication by wastage factor, or + adding taxes or other adjustments). + + This function lets you add a single top level unit value to a cost item, + or alternatively price subcomponents by using the "parent" parameter. + + More advanced usage, which involves summing, subcategory-filtered costs, + and formulas are possible but not yet documented. + + :param parent: A parent IfcCostItem, if specifying a price directly to a + cost item, or a top-level price component. Alternatively, this can + be set to a IfcCostValue, if specifying price subcomponents. + :return: The newly created IfcCostValue + + Example: + + .. code:: python + + # We always need a schedule first prior to adding any cost items + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + + # Option 1: This cost item will have a full cost of 42.0 + item1 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + value = ifcopenshell.api.cost.add_cost_value(model, parent=item1) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 42.0}) + + # Option 2: This cost item will have a unit cost of 5.0 per unit + # area, multiplied by the quantity of area specified explicitly as + # 3.0, giving us a subtotal cost of 15.0. + item2 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + value = ifcopenshell.api.cost.add_cost_value(model, parent=item2) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + quantity = ifcopenshell.api.cost.add_cost_item_quantity(model, + cost_item=item2, ifc_class="IfcQuantityVolume") + ifcopenshell.api.cost.edit_cost_item_quantity(model, + physical_quantity=quantity, "attributes": {"VolumeValue": 3.0}) + + # A cost value may also be specified in terms of the sum of its + # subcomponents. In this case, it's broken down into 2 subvalues. + item1 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + value = ifcopenshell.api.cost.add_cost_value(model, parent=item1) + subvalue1 = ifcopenshell.api.cost.add_cost_value(model, parent=value) + subvalue2 = ifcopenshell.api.cost.add_cost_value(model, parent=value) + + # This specifies that the value is the sum of all subitems + # regardless of their cost category. The first subvalue is 2.0 and + # the second is 3.0, giving a total value of 5.0. + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, attributes={"Category": "*"}) + ifcopenshell.api.cost.edit_cost_value(model, + cost_value=subvalue1, attributes={"AppliedValue": 2.0}) + ifcopenshell.api.cost.edit_cost_value(model, + cost_value=subvalue2, attributes={"AppliedValue": 3.0}) + """ + value = file.create_entity("IfcCostValue") + if parent.is_a("IfcCostItem"): + values = list(parent.CostValues or []) + values.append(value) + parent.CostValues = values + elif parent.is_a("IfcConstructionResource"): + values = list(parent.BaseCosts or []) + values.append(value) + parent.BaseCosts = values + elif parent.is_a("IfcCostValue"): + values = list(parent.Components or []) + values.append(value) + parent.Components = values + return value diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_item_quantity.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_item_quantity.py new file mode 100644 index 0000000000000000000000000000000000000000..2db09c45f663455b39e125fa139df74eee0231bf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_item_quantity.py @@ -0,0 +1,159 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.cost +import ifcopenshell.api.control +from typing import Any + + +def assign_cost_item_quantity( + file: ifcopenshell.file, + cost_item: ifcopenshell.entity_instance, + products: list[ifcopenshell.entity_instance], + prop_name: str = "", +) -> None: + """Adds a cost item quantity that is parametrically connected to a product + + A cost item may have its subtotal calculated by multiplying a unit value + by a quantity associated with the cost item. That quantity may be either + manually specified or parametrically connected to a quantity on a + product. This API function lets you create that parametric connection. + + For example, you may wish to have a cost item linked to the "NetVolume" + quantity on all IfcSlabs. Each quantity has a name which you can + specify. If the quantity is updated in-place (which should occur for + Native IFC applications) then the quantity for the cost item will + automatically update as well. If the quantity is deleted and then + re-added, then the parametric relationship is also lost. + + This API also automatically assigns a control relationship between the + cost item and the product, so it is not necessary to use + ifcopenshell.api.control.assign_control. + + If cost item has just 1 quantity and it's IfcQuantityCount, API will + assume that quantity is used for counting controlled objects + and it will recalculate the quantity value at the end of the API call + as long as the RelatedObjects are not IfcConstructionResource which do not + count towards the cost item (they only provide value). + + :param cost_item: The IfcCostItem to assign parametric quantities to + :param products: The IfcObjects to assign parametric quantities to + :param prop_name: The name of the quantity. If this is not specified, + then it is assumed that there is no calculated quantity, and the + number of objects are counted instead. + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # Let's imagine a unit cost of 5.0 per unit volume + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + + slab = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSlab") + # Usually the quantity would be automatically calculated via a + # graphical authoring application but let's assign a manual quantity + # for now. + qto = ifcopenshell.api.pset.add_qto(model, product=slab, name="Qto_SlabBaseQuantities") + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"NetVolume": 42.0}) + + # Now let's parametrically link the slab's quantity to the cost + # item. If the slab is edited in the future and 42.0 changes, then + # the updated value will also automatically be applied to the cost + # item. + ifcopenshell.api.cost.assign_cost_item_quantity(model, + cost_item=item, products=[slab], prop_name="NetVolume") + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "cost_item": cost_item, + "products": products or [], + "prop_name": prop_name, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + if self.settings["prop_name"]: + self.quantities = set(self.settings["cost_item"].CostQuantities or []) + for product in self.settings["products"]: + if product.is_a("IfcSpatialElement"): + continue + self.assign_cost_control(related_object=product, cost_item=self.settings["cost_item"]) + if self.settings["prop_name"]: + if ( + self.settings["cost_item"].CostQuantities + and self.settings["cost_item"].CostQuantities[0].Name.lower() != self.settings["prop_name"].lower() + ): + continue + self.add_quantity_from_related_object(product) + if self.settings["prop_name"]: + self.settings["cost_item"].CostQuantities = list(self.quantities) + else: + self.update_cost_item_count() + + def assign_cost_control( + self, related_object: ifcopenshell.entity_instance, cost_item: ifcopenshell.entity_instance + ) -> ifcopenshell.entity_instance: + return ifcopenshell.api.control.assign_control( + self.file, + related_objects=[related_object], + relating_control=cost_item, + ) + + def add_quantity_from_related_object(self, element: ifcopenshell.entity_instance) -> None: + for relationship in element.IsDefinedBy: + if relationship.is_a("IfcRelDefinesByProperties"): + self.add_quantity_from_qto(relationship.RelatingPropertyDefinition) + + def add_quantity_from_qto(self, qto: ifcopenshell.entity_instance) -> None: + if not qto.is_a("IfcElementQuantity"): + return + for prop in qto.Quantities: + if prop.is_a("IfcPhysicalSimpleQuantity") and prop.Name.lower() == self.settings["prop_name"].lower(): + self.quantities.add(prop) + + def update_cost_item_count(self): + # This is a bold assumption + # https://forums.buildingsmart.org/t/how-does-a-cost-item-know-that-it-is-counting-a-controlled-product/3564 + if not self.settings["cost_item"].CostQuantities: + ifcopenshell.api.cost.add_cost_item_quantity( + self.file, + cost_item=self.settings["cost_item"], + ifc_class="IfcQuantityCount", + ) + if len(self.settings["cost_item"].CostQuantities) == 1: + quantity = self.settings["cost_item"].CostQuantities[0] + if quantity.is_a("IfcQuantityCount"): + count = 0 + for rel in self.settings["cost_item"].Controls: + for obj in rel.RelatedObjects: + # Only increment if not a resource + if not obj.is_a("IfcConstructionResource"): + count += 1 + quantity[3] = count diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_value.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_value.py new file mode 100644 index 0000000000000000000000000000000000000000..d012c02c5b853ebb94a99f24a3a25e9d37c9a022 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/assign_cost_value.py @@ -0,0 +1,71 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.cost + + +def assign_cost_value( + file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance, cost_rate: ifcopenshell.entity_instance +) -> None: + """Assigns a cost value to a cost item from a schedule of rates + + Instead of assigning cost values from scratch for each cost item in a + cost schedule, the cost values may instead be assigned from a schedule + of rates. + + A schedule of rates is just another cost schedule which have cost values + but no quantities. This API will allow you to "copy" the values from a + cost item in the schedule of rates into another cost item in your own + cost schedule. When the schedule of rates value is updated, then your + cost item values will also be updated. You can think of the schedule of + rates as a "template" to quickly populate your rates from. + + :param cost_item: The IfcCostItem that you want to copy the values to + :param cost_rate: The IfcCostItem that you want to copy the values from + :return: None + + Example: + + .. code:: python + + # Let's create a schedule of rates with a single rate in it of 5.0 + rate_tables = ifcopenshell.api.cost.add_cost_schedule(model, + predefined_type="SCHEDULEOFRATES") + rate = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + value = ifcopenshell.api.cost.add_cost_value(model, parent=rate) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + + # And this schedule will be for our actual cost plan / estimate / etc + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # Now the cost item has the same rate as the one from the schedule of rate's item + ifcopenshell.api.cost.assign_cost_value(model, cost_item=item, cost_rate=rate) + """ + if cost_item.CostValues: + [ + ifcopenshell.api.cost.remove_cost_value( + file, + parent=cost_item, + cost_value=cost_value, + ) + for cost_value in cost_item.CostValues + ] + # This is an assumption, and not part of the official IFC documentation + cost_item.CostValues = cost_rate.CostValues diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/calculate_cost_item_resource_value.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/calculate_cost_item_resource_value.py new file mode 100644 index 0000000000000000000000000000000000000000..fc53e2ff3daf7387afb45eb520c2047155dcf94e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/calculate_cost_item_resource_value.py @@ -0,0 +1,113 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.cost +import ifcopenshell.util.date +import ifcopenshell.util.resource + + +def calculate_cost_item_resource_value(file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance) -> None: + """Calculates the total cost of all resources associated with a cost item + + A cost item may have construction resources (e.g. equipment, material, + etc) assigned to it. Construction resources may be assigned directly to + the cost item, or assigned first to a task, and the task is then + assigned to the cost item. + + The cost of a resource is calculated by the total sum of all of its base + costs. If no quantity is provided, that sum is considered to be the + total cost. Otherwise, it is considered to be a unit cost, and is then + multiplied by the resource quantity. The quantity is either stored as a + base quantity (such as a volume) for a things like material resources, + or as a duration as a daily rate for labour resources. + + The final calculated cost is set as the cost item's value. Any + previously existing values are removed. + + :param cost_item: The IfcCostItem to calculate + :return: None + + Example: + + .. code:: python + + # First, we need a cost schedule and item + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # Let's imagine we have our own formworking crew + crew = ifcopenshell.api.resource.add_resource(model, ifc_class="IfcCrewResource") + + # ... and they need concrete + concrete = ifcopenshell.api.resource.add_resource(model, + ifc_class="IfcConstructionMaterialResource", parent_resource=crew) + ifcopenshell.api.control.assign_control(model, + relating_control=item, related_objects=[concrete]) + # ... which has a unit price of 42.0 per m3 + value = ifcopenshell.api.cost.add_cost_value(model, parent=concrete) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 42.0}) + # ... and a volume of 200m3 + quantity = ifcopenshell.api.resource.add_resource_quantity(model, + resource=concrete, ifc_class="IfcQuantityVolume") + ifcopenshell.api.resource.edit_resource_quantity(model, + physical_quantity=quantity, "attributes": {"VolumeValue": 200.0}) + + # Let's say they also need some equipment + equipment = ifcopenshell.api.resource.add_resource(model, + ifc_class="IfcConstructionEquipmentResource", parent_resource=crew) + ifcopenshell.api.control.assign_control(model, + relating_control=item, related_objects=[equipment]) + # ... with a fixed price of 50,000 + value = ifcopenshell.api.cost.add_cost_value(model, parent=concrete) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 42.0}) + + # (42 * 200) + 50000 = 58400 is our calculated cost + ifcopenshell.api.cost.calculate_cost_item_resource_value(model, cost_item=item) + """ + for cost_value in cost_item.CostValues or []: + ifcopenshell.api.cost.remove_cost_value(file, parent=cost_item, cost_value=cost_value) + + resources = [] + for rel in cost_item.Controls or []: + for related_object in rel.RelatedObjects: + if related_object.is_a("IfcConstructionResource"): + resources.append(related_object) + elif related_object.is_a("IfcTask"): + for rel2 in related_object.OperatesOn or []: + for related_object2 in rel2.RelatedObjects: + if related_object2.is_a("IfcConstructionResource"): + resources.append(related_object2) + + for resource in resources: + cost, unit = ifcopenshell.util.resource.get_cost(resource) + if cost is None: + # Concept to standardise - Not defined in schema, but this makes manual scheduling of resources 10x faster and less duplicate data. + parent_cost = ifcopenshell.util.resource.get_parent_cost(resource) + if parent_cost: + cost, unit = parent_cost + quantity = ifcopenshell.util.resource.get_quantity(resource) + if cost is None: + continue + if unit and "day" in unit: + quantity = quantity / 8 # Assume 8 hour working day - TODO implement resource calendar + formula = "{}*{}".format(cost, quantity) + cost_value = ifcopenshell.api.cost.add_cost_value(file, parent=cost_item) + cost_value.Name = resource.Name + ifcopenshell.api.cost.edit_cost_value_formula(file, cost_value=cost_value, formula=formula) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item.py new file mode 100644 index 0000000000000000000000000000000000000000..fcf298ff7c039d6f552c715064a4806d06aa9979 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item.py @@ -0,0 +1,114 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.nest +import ifcopenshell.util.element +from typing import Union + + +def copy_cost_item( + file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance +) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]]: + """Copies all cost items and related relationships + + The following relationships are also duplicated: + + * The copy will have the same attributes and property sets as the original cost item + * The copy will be assigned to the parent cost schedule + * The copy will have duplicated nested cost items + + :param cost_item: The cost item to be duplicated + :return: The duplicated cost item or the list of duplicated cost items if the latter has children + + Example: + .. code:: python + + # We have a cost item + cost_item = CostItem(name="Design new feature", deadline="2023-03-01") + + # And now we have two + duplicated_cost_item = project.duplicate_cost_item(cost_item) + + + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(cost_item) + + +class Usecase: + file: ifcopenshell.file + new_cost_items: list[ifcopenshell.entity_instance] + + def execute( + self, cost_item: ifcopenshell.entity_instance + ) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]]: + self.new_cost_items = [] + self.duplicate_cost_item(cost_item) + return self.new_cost_items[0] if len(self.new_cost_items) == 1 else self.new_cost_items + + def duplicate_cost_item(self, cost_item: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + new_cost_item = ifcopenshell.util.element.copy_deep(self.file, cost_item) + self.new_cost_items.append(new_cost_item) + self.copy_indirect_attributes(cost_item, new_cost_item) + return new_cost_item + + def copy_indirect_attributes( + self, from_element: ifcopenshell.entity_instance, to_element: ifcopenshell.entity_instance + ) -> None: + for inverse in self.file.get_inverse(from_element): + if inverse.is_a("IfcRelDefinesByProperties"): + inverse = ifcopenshell.util.element.copy(self.file, inverse) + inverse.RelatedObjects = [to_element] + pset = ifcopenshell.util.element.copy_deep(self.file, inverse.RelatingPropertyDefinition) + inverse.RelatingPropertyDefinition = pset + elif inverse.is_a("IfcRelNests") and inverse.RelatingObject == from_element: + nested_cost_items = [e for e in inverse.RelatedObjects] + if nested_cost_items: + new_cost_items = [] + for cost_item in nested_cost_items: + new_cost_item = self.duplicate_cost_item(cost_item) + new_cost_items.append(new_cost_item) + inverse = ifcopenshell.util.element.copy(self.file, inverse) + inverse.RelatingObject = to_element + inverse.RelatedObjects = new_cost_items + ifcopenshell.api.nest.unassign_object(self.file, related_objects=new_cost_items) + ifcopenshell.api.nest.assign_object( + self.file, related_objects=new_cost_items, relating_object=to_element + ) + # elif inverse.is_a("IfcRelAssignsToProduct"): + # continue + # to_element.IsDefinedBy = inverse.RelatingOrder + # elif inverse.is_a("IfcRelAssignsToProcess"): + # to_element.IsDefinedBy = inverse.RelatingProcess + # elif inverse.is_a("IfcRelAssignsToResource"): + # continue + # elif inverse.is_a("IfcRelAssignsToControl"): + # continue + # elif inverse.is_a("IfcRelDefinesByObject"): + # continue + else: + for i, value in enumerate(inverse): + if value == from_element: + new_inverse = ifcopenshell.util.element.copy(self.file, inverse) + new_inverse[i] = to_element + elif isinstance(value, (tuple, list)) and from_element in value: + new_value = list(value) + new_value.append(to_element) + inverse[i] = new_value diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item_values.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item_values.py new file mode 100644 index 0000000000000000000000000000000000000000..01d0a029762be4a01b36c089650a069cd3e3d8ae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_item_values.py @@ -0,0 +1,58 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element +import ifcopenshell.api.cost + + +def copy_cost_item_values( + file: ifcopenshell.file, source: ifcopenshell.entity_instance, destination: ifcopenshell.entity_instance +) -> None: + """Copies all cost values from one cost item to another + + Any previously existing values will be removed. The entire value is + copied, including all components and formulas. However they are not + parametrically linked, so if one value changes, the other will not. + + :param source: The IfcCostItem to copy cost values from + :param destination: The IfcCostItem to copy cost values from + :return: None + + Example: + + .. code:: python + + # Assume we have a schedule with multiple items in it + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item1 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + item2 = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # One of the items has a value + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5000.0}) + + # Let's copy the value from one item to another + ifcopenshell.api.cost.copy_cost_item_values(model, source=item1, destination=item2) + """ + for cost_value in destination.CostValues or []: + ifcopenshell.api.cost.remove_cost_value(file, source, cost_value=cost_value) + copied_cost_values = [] + for cost_value in source.CostValues or []: + copied_cost_values.append(ifcopenshell.util.element.copy_deep(file, cost_value)) + destination.CostValues = copied_cost_values diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_schedule.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..3101e820c2ad0d8e93ae219232353e701cdf228c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/copy_cost_schedule.py @@ -0,0 +1,49 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.control +import ifcopenshell.api.cost +import ifcopenshell.util.element + + +def copy_cost_schedule( + file: ifcopenshell.file, cost_schedule: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + """Copy a cost schedule. + + :param cost_schedule: IfcCostSchedule to copy. + :return: The duplicated IfcCostSchedule entity + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + new_schedule = ifcopenshell.api.cost.copy_cost_schedule(schedule) + """ + # Shared code logic with copy_work_schedule. + new_schedule = ifcopenshell.util.element.copy(file, cost_schedule) + + for rel in cost_schedule.Controls: + for cost_item in rel.RelatedObjects: + duplicated_cost_item = ifcopenshell.api.cost.copy_cost_item(file, cost_item) + if isinstance(duplicated_cost_item, list): + # All other nested items are not connected to the cost schedule explicitly. + duplicated_cost_item = duplicated_cost_item[0] + ifcopenshell.api.control.assign_control(file, new_schedule, [duplicated_cost_item]) + return new_schedule diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item.py new file mode 100644 index 0000000000000000000000000000000000000000..813e306bc8a48d05489b7a8e0d5f759b2a70a199 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_cost_item( + file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcCostItem + + For more information about the attributes and data types of an + IfcCostItem, consult the IFC documentation. + + :param cost_item: The IfcCostItem entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + ifcopenshell.api.cost.edit_cost_item(model, cost_item=item, attributes={"Name": "Foo"}) + """ + for name, value in attributes.items(): + setattr(cost_item, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item_quantity.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item_quantity.py new file mode 100644 index 0000000000000000000000000000000000000000..697d028a37448e881c0bce8965dd0ef445dc2f28 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_item_quantity.py @@ -0,0 +1,51 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_cost_item_quantity( + file: ifcopenshell.file, physical_quantity: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcPhysicalQuantity + + For more information about the attributes and data types of an + IfcPhysicalQuantity, consult the IFC documentation. + + :param physical_quantity: The IfcPhysicalQuantity entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # This cost item will have a unit cost of 5 and a volume of 3 + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + quantity = ifcopenshell.api.cost.add_cost_item_quantity(model, + cost_item=item, ifc_class="IfcQuantityVolume") + ifcopenshell.api.cost.edit_cost_item_quantity(model, + physical_quantity=quantity, "attributes": {"VolumeValue": 3.0}) + """ + for name, value in attributes.items(): + setattr(physical_quantity, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_schedule.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..d55e93330e446f98c092d70aa7c1ac72d24ebd99 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_schedule.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_cost_schedule( + file: ifcopenshell.file, cost_schedule: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcCostSchedule + + For more information about the attributes and data types of an + IfcCostSchedule, consult the IFC documentation. + + :param cost_schedule: The IfcCostSchedule entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + ifcopenshell.api.cost.edit_cost_schedule(model, + cost_schedule=schedule, attributes={"Name": "Foo"}) + """ + for name, value in attributes.items(): + setattr(cost_schedule, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc09ed34c0344d236e6944d19a22d2adecfc058 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value.py @@ -0,0 +1,63 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.unit +import ifcopenshell.util.element +from typing import Any + + +def edit_cost_value( + file: ifcopenshell.file, cost_value: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcCostValue + + For more information about the attributes and data types of an + IfcCostValue, consult the IFC documentation. + + :param cost_value: The IfcCostValue entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # This cost item will have a total cost of 42 + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 42.0}) + """ + for name, value in attributes.items(): + if name == "AppliedValue" and value is not None: + # TODO: support all applied value select types + value = file.createIfcMonetaryMeasure(value) + elif name == "UnitBasis": + old_unit_basis = cost_value.UnitBasis + if value: + value_component = file.create_entity( + ifcopenshell.util.unit.get_unit_measure_class(value["UnitComponent"].UnitType), + value["ValueComponent"], + ) + value = file.create_entity("IfcMeasureWithUnit", value_component, value["UnitComponent"]) + if old_unit_basis and file.get_total_inverses(old_unit_basis) == 0: + ifcopenshell.util.element.remove_deep(file, old_unit_basis) + setattr(cost_value, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value_formula.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value_formula.py new file mode 100644 index 0000000000000000000000000000000000000000..2f68a66023a78d64c656bd0e53f09f72dc70c0e3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/edit_cost_value_formula.py @@ -0,0 +1,81 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.cost +import ifcopenshell.util.cost +import ifcopenshell.util.unit +import ifcopenshell.util.element +from typing import Any + + +def edit_cost_value_formula(file: ifcopenshell.file, cost_value: ifcopenshell.entity_instance, formula: str) -> None: + """Sets a cost value based on a formula, similar to formulas in spreadsheets + + Costs may be made up of many components (e.g. labour, material, waste + factor, taxes, etc). This can be easily represented in the form of a + formula similar thta would be used in spreadsheet applications. + + For more information, see ifcopenshell.util.cost + + :param cost_value: The IfcCostValue to set the values of + :param formula: The formula following the language of ifcopenshell.util.cost + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value_formula(model, cost_value=value, + formula="5000 * 1.19") + """ + usecase = Usecase() + usecase.file = file + usecase.settings = {"cost_value": cost_value, "formula": formula or {}} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + try: + data = ifcopenshell.util.cost.unserialise_cost_value(self.settings["formula"], self.settings["cost_value"]) + except: + return + self.edit_cost_value(data) + + def edit_cost_value(self, data, parent=None): + ifc = data.get("ifc", None) + if not ifc: + ifc = ifcopenshell.api.cost.add_cost_value(self.file, parent=parent) + if "AppliedValue" in data: + if data["AppliedValue"]: + ifc.AppliedValue = self.file.createIfcMonetaryMeasure(data["AppliedValue"]) + else: + ifc.AppliedValue = None + ifc.Category = data["Category"] if "Category" in data else None + ifc.ArithmeticOperator = data["ArithmeticOperator"] if "ArithmeticOperator" in data else None + if "Components" in data: + for component in data["Components"]: + self.edit_cost_value(component, ifc) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item.py new file mode 100644 index 0000000000000000000000000000000000000000..ce1aa5545effa2c3764e7f11326a45eb6025a6b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item.py @@ -0,0 +1,63 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.cost +import ifcopenshell.util.element + + +def remove_cost_item(file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance) -> None: + """Removes a cost item + + All associated relationships with the cost item are also removed, + however the related resources, products, and tasks themselves are + retained. + + :param cost_item: The IfcCostItem entity you want to remove + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + ifcopenshell.api.cost.remove_cost_item(model, cost_item=item) + """ + # TODO: do a deep purge + for inverse in file.get_inverse(cost_item): + if inverse.is_a("IfcRelNests"): + if inverse.RelatingObject == cost_item: + for related_object in inverse.RelatedObjects: + ifcopenshell.api.cost.remove_cost_item(file, cost_item=related_object) + elif inverse.RelatedObjects == (cost_item,): + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + elif inverse.is_a("IfcRelAssignsToControl"): + if len(inverse.RelatedObjects) >= 2 or inverse.RelatingControl == cost_item: + continue + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + history = cost_item.OwnerHistory + file.remove(cost_item) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item_quantity.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item_quantity.py new file mode 100644 index 0000000000000000000000000000000000000000..80f330ce0b1996afc2534d212f180e8490246866 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_item_quantity.py @@ -0,0 +1,51 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_cost_item_quantity( + file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance, physical_quantity: ifcopenshell.entity_instance +) -> None: + """Removes a quantity assigned to a cost item + + If the quantity is part of a product (e.g. wall), then the quantity will + still exist and merely the relationship to the cost item will be + removed. + + :param cost_item: The IfcCostItem that the quantity is assigned to + :param physical_quantity: The IfcPhysicalQuantity to remove + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + quantity = ifcopenshell.api.cost.add_cost_item_quantity(model, + cost_item=item, ifc_class="IfcQuantityVolume") + # Let's change our mind and delete it + ifcopenshell.api.cost.remove_cost_item(model, + cost_item=item, physical_quantity=quantity) + """ + if file.get_total_inverses(physical_quantity) == 1: + file.remove(physical_quantity) + return + quantities = list(cost_item.CostQuantities or []) + quantities.remove(physical_quantity) + cost_item.CostQuantities = quantities diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_schedule.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_schedule.py new file mode 100644 index 0000000000000000000000000000000000000000..70d7461a696ad6c16dbdeebb7125041bb8a832f3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_schedule.py @@ -0,0 +1,52 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.cost +import ifcopenshell.util.element + + +def remove_cost_schedule(file: ifcopenshell.file, cost_schedule: ifcopenshell.entity_instance) -> None: + """Removes a cost schedule + + All associated relationships with the cost schedule are also removed, + including all cost items. + + :param cost_schedule: The IfcCostSchedule entity you want to remove + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + ifcopenshell.api.cost.remove_cost_schedule(model, cost_schedule=schedule) + """ + # TODO: do a deep purge + for inverse in file.get_inverse(cost_schedule): + if inverse.is_a("IfcRelAssignsToControl"): + [ + ifcopenshell.api.cost.remove_cost_item(file, cost_item=related_object) + for related_object in inverse.RelatedObjects + if related_object.is_a("IfcCostItem") + ] + history = cost_schedule.OwnerHistory + file.remove(cost_schedule) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_value.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_value.py new file mode 100644 index 0000000000000000000000000000000000000000..b578cd713425873d4a959824b0cb1a0643c80932 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/remove_cost_value.py @@ -0,0 +1,62 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_cost_value( + file: ifcopenshell.file, parent: ifcopenshell.entity_instance, cost_value: ifcopenshell.entity_instance +) -> None: + """Removes a cost value + + The cost value may be assigned either to a cost item, a construction + resource, or another cost value (i.e. it is a subcomponent of a cost) + + :param parent: The IfcCostItem, IfcConstructionResource, or IfcCostValue + that the IfcCostValue is assigned to. + :param cost_value: The IfcCostValue that you want to remove + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # This cost item will have a unit cost of 5 and a volume of 3 + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + + ifcopenshell.api.cost.remove_cost_value(model, parent=item, cost_value=value) + """ + if file.get_total_inverses(cost_value) == 1: + file.remove(cost_value) + # TODO deep purge + elif parent.is_a("IfcCostItem"): + values = list(parent.CostValues) + values.remove(cost_value) + parent.CostValues = values if values else None + elif parent.is_a("IfcConstructionResource"): + values = list(parent.BaseCosts) + values.remove(cost_value) + parent.BaseCosts = values if values else None + elif parent.is_a("IfcCostValue"): + components = list(parent.Components) + components.remove(cost_value) + parent.Components = components if components else None diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/unassign_cost_item_quantity.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/unassign_cost_item_quantity.py new file mode 100644 index 0000000000000000000000000000000000000000..1119935ccde27be53aae0d478928ecf1e8aab72a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/cost/unassign_cost_item_quantity.py @@ -0,0 +1,106 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.control + + +def unassign_cost_item_quantity( + file: ifcopenshell.file, cost_item: ifcopenshell.entity_instance, products: list[ifcopenshell.entity_instance] +) -> None: + """Removes quantities of a cost item that are calculated on products + + A cost item may have quantities that are parametrically calculated on + physical products. This lets you remove those quantities. This means + that any future changes in the physical product's dimensions will not + have any impact on the cost item. + + :param cost_item: The IfcCostItem to remove quantities from + :param products: A list of IfcProducts that may have parametrically + connected quantities to the cost item + :return: None + + Example: + + .. code:: python + + schedule = ifcopenshell.api.cost.add_cost_schedule(model) + item = ifcopenshell.api.cost.add_cost_item(model, cost_schedule=schedule) + + # Let's imagine a unit cost of 5.0 per unit volume + value = ifcopenshell.api.cost.add_cost_value(model, parent=item) + ifcopenshell.api.cost.edit_cost_value(model, cost_value=value, + attributes={"AppliedValue": 5.0}) + + slab = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSlab") + # Usually the quantity would be automatically calculated via a + # graphical authoring application but let's assign a manual quantity + # for now. + qto = ifcopenshell.api.pset.add_qto(model, product=slab, name="Qto_SlabBaseQuantities") + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"NetVolume": 42.0}) + + # Now let's parametrically link the slab's quantity to the cost + # item. If the slab is edited in the future and 42.0 changes, then + # the updated value will also automatically be applied to the cost + # item. + ifcopenshell.api.cost.assign_cost_item_quantity(model, + cost_item=item, products=[slab], prop_name="NetVolume") + + # Let's change our mind and remove the parametric connection + ifcopenshell.api.cost.unassign_cost_item_quantity(model, + cost_item=item, products=[slab]) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(cost_item, products or []) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, cost_item: ifcopenshell.entity_instance, products: list[ifcopenshell.entity_instance]) -> None: + quantities = set(cost_item.CostQuantities or []) + for quantity in cost_item.CostQuantities or []: + for inverse in self.file.get_inverse(quantity): + if not inverse.is_a("IfcElementQuantity"): + continue + for rel in inverse.DefinesOccurrence or []: + for related_object in rel.RelatedObjects: + if related_object in products: + quantities.remove(quantity) + cost_item.CostQuantities = list(quantities) + for product in products: + ifcopenshell.api.control.unassign_control( + self.file, + related_objects=[product], + relating_control=cost_item, + ) + self.update_cost_item_count(cost_item) + + def update_cost_item_count(self, cost_item: ifcopenshell.entity_instance) -> None: + # This is a bold assumption + # https://forums.buildingsmart.org/t/how-does-a-cost-item-know-that-it-is-counting-a-controlled-product/3564 + if len(cost_item.CostQuantities) == 1: + quantity = cost_item.CostQuantities[0] + if quantity.is_a("IfcQuantityCount"): + count = 0 + for rel in cost_item.Controls: + count += len(rel.RelatedObjects) + if count: + quantity[3] = count + else: + self.file.remove(quantity) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6560ce9080d862b76cff865e17957f8452dd3c21 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/__init__.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Reference external project documents and associate them to model elements + +Some project information (drawings, specifications, certificates, reports, etc) +may be stored in external documents (locally or in a CDE). IFC lets you store a +register of documents with metadata and associate them with elements (both +physical and non-physical). +""" + +from .. import wrap_usecases +from .add_information import add_information +from .add_reference import add_reference +from .assign_document import assign_document +from .edit_information import edit_information +from .edit_reference import edit_reference +from .remove_information import remove_information +from .remove_reference import remove_reference +from .unassign_document import unassign_document + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_information", + "add_reference", + "assign_document", + "edit_information", + "edit_reference", + "remove_information", + "remove_reference", + "unassign_document", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_information.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_information.py new file mode 100644 index 0000000000000000000000000000000000000000..a5018c63cb5caa63b8f1c51940624688248e1f06 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_information.py @@ -0,0 +1,82 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.guid +import ifcopenshell.api.owner +from typing import Optional + + +def add_information( + file: ifcopenshell.file, parent: Optional[ifcopenshell.entity_instance] = None +) -> ifcopenshell.entity_instance: + """Adds a new document information to the project + + An IFC document information is a document associated with the project. + It may be a drawing, specification, schedule, certificate, warranty + guarantee, manual, contract, and so on. They are often used for drawings + and facility management purposes. + + A document may also be a subdocument of a larger document, this is + useful for superseding documents or tracking older versions. The parent + is considered the latest version and the children are older revisions. + + :param parent: The parent document, if necessary. + :return: The newly created IfcDocumentInformation entity + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + # A document typically has a unique drawing or document name (which + # follows a coding system depending on the project), as well as a + # title. This should match what is shown on the titleblock or title + # page of the document. At a minimum you'd also want to specify a + # URI location. The location may be on local, or on a CDE, or any + # other platform. + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + """ + id_attribute = "DocumentId" if file.schema == "IFC2X3" else "Identification" + information = file.create_entity("IfcDocumentInformation", **{id_attribute: "X", "Name": "Unnamed"}) + + if not parent and not (parent := next(iter(file.by_type("IfcProject")), None)): + raise Exception("IfcProject is not found.") + + if parent.is_a("IfcProject") or parent.is_a("IfcContext"): + file.create_entity( + "IfcRelAssociatesDocument", + GlobalId=ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(file), + RelatingDocument=information, + RelatedObjects=[parent], + ) + elif parent.is_a("IfcDocumentInformation"): + if parent.IsPointer: + rel = parent.IsPointer[0] + documents = set(rel.RelatedDocuments) + documents.add(information) + rel.RelatedDocuments = list(documents) + else: + file.create_entity( + "IfcDocumentInformationRelationship", RelatingDocument=parent, RelatedDocuments=[information] + ) + return information diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..ae56b0b93599199aa96d6a2f7ebb231a8d0b4837 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/add_reference.py @@ -0,0 +1,71 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def add_reference(file: ifcopenshell.file, information: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Creates a new reference to a document to assign to products + + A document may be associated with physical products, tasks, cost items, + and so on. For example, spaces, storeys, and buildings may have a list + of associated drawings so you can see which drawings (e.g. plans, + sections, details) are documenting that location. Alternatively, + equipment may have associated training manuals, operation and + maintenance manuals or detailed assembly drawings. Resources may be + training certification required, schedules may have gantt charts or bid + documents, and so on. + + In order to associate a document with an object, a reference to that + document needs to be created. It could be a reference to the entire + document, or a reference to a particular page or chapter. See + ifcopenshell.api.document.assign_document for more information. + + :param information: The IfcDocumentInformation that the reference will + be created for + :return: The newly created IfcDocumentReference entity + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + + # In this case, we don't specify any more information, and so the + # reference is for the entire document, as opposed to a single page or + # chapter or section. + reference = ifcopenshell.api.document.add_reference(model, information=document) + + # Alternatively, we can specify a single section, such as by a + # subheading code. + reference2 = ifcopenshell.api.document.add_reference(model, information=document) + ifcopenshell.api.document.edit_reference(model, + reference=reference2, attributes={"Identification": "2.1.15"}) + """ + if file.schema == "IFC2X3": + reference = file.create_entity("IfcDocumentReference", ItemReference="X") + if information: + references = list(information.DocumentReferences or []) + references.append(reference) + information.DocumentReferences = references + return reference + return file.create_entity("IfcDocumentReference", ReferencedDocument=information, Identification="X") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/assign_document.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/assign_document.py new file mode 100644 index 0000000000000000000000000000000000000000..a86a178e86110bfa17272eabe9b2005f3b56ed83 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/assign_document.py @@ -0,0 +1,102 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Union + + +def assign_document( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + document: ifcopenshell.entity_instance, +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns a document to a list of products + + An object may be assigned to zero, one, or multiple documents. Almost + any object or property may be assigned to a document, though typically + we'd only use it for spaces, types, physical products and schedules. + Adding a new assignment is typically done using a document reference and + an object. IFC technically allows association with a document + information and an object, but this is not encouraged because it is not + consistent with other external relationships (such as classification + systems or libraries). + + :param product: The list of objects to associate the document to. This could be + almost any sensible object in IFC. + :param document: The IfcDocumentReference to associate to, or + alternatively an IfcDocumentInformation, though this is not + recommended. + :return: The IfcRelAssociatesDocument relationship + or `None` if `products` was an empty list or all products were + already assigned to the `document`. + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + reference = ifcopenshell.api.document.add_reference(model, information=document) + + # Let's imagine storey represents an IfcBuildingStorey for the ground floor + ifcopenshell.api.document.assign_document(model, products=[storey], document=reference) + """ + + # TODO: do we need to support non-ifcroot elements like we do in classification.add_reference? + # NOTE: reuses code from `library.assign_reference` + + referenced_elements = ifcopenshell.util.element.get_referenced_elements(document) + products_set: set[ifcopenshell.entity_instance] = set(products) + products_set = products_set - referenced_elements + + if not products_set: + return + + if file.schema == "IFC2X3": + rel = next( + (r for r in file.by_type("IfcRelAssociatesDocument") if r.RelatingDocument == document), + None, + ) + else: + ifc_class = document.is_a() + if ifc_class == "IfcDocumentReference": + rel = next(iter(document.DocumentRefForObjects), None) + elif ifc_class == "IfcDocumentInformation": + rel = next(iter(document.DocumentInfoForObjects), None) + else: + assert False, f"Unexpected document type: {ifc_class}" + + if not rel: + return file.create_entity( + "IfcRelAssociatesDocument", + GlobalId=ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(file), + RelatedObjects=list(products_set), + RelatingDocument=document, + ) + + related_objects = set(rel.RelatedObjects) | products_set + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + return rel diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_information.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_information.py new file mode 100644 index 0000000000000000000000000000000000000000..56c1d40df4ab017a576340621c81426a159da15a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_information.py @@ -0,0 +1,47 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_information( + file: ifcopenshell.file, + information: ifcopenshell.entity_instance, + attributes: dict[str, Any], +) -> None: + """Edits the attributes of an IfcDocumentInformation + + For more information about the attributes and data types of an + IfcDocumentInformation, consult the IFC documentation. + + :param reference: The IfcDocumentInformation entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + """ + for name, value in attributes.items(): + setattr(information, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..51ad195bf315d6fc12c01f119f1f775768598297 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/edit_reference.py @@ -0,0 +1,50 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_reference( + file: ifcopenshell.file, + reference: ifcopenshell.entity_instance, + attributes: dict[str, Any], +) -> None: + """Edits the attributes of an IfcDocumentReference + + For more information about the attributes and data types of an + IfcDocumentReference, consult the IFC documentation. + + :param reference: The IfcDocumentReference entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + reference = ifcopenshell.api.document.add_reference(model, information=document) + ifcopenshell.api.document.edit_reference(model, + reference=reference, attributes={"Identification": "2.1.15"}) + """ + for name, value in attributes.items(): + setattr(reference, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_information.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_information.py new file mode 100644 index 0000000000000000000000000000000000000000..e60112e2f9074d51fb5adbb8f42c270a25b10a69 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_information.py @@ -0,0 +1,70 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import ifcopenshell +import ifcopenshell.api.document +import ifcopenshell.util.element + + +def remove_information(file: ifcopenshell.file, information: ifcopenshell.entity_instance) -> None: + """Removes a document information + + All references and associations are also removed. + + :param information: The IfcDocumentInformation to remove + :return: None + + Example: + + .. code:: python + + # Add a document + document = ifcopenshell.api.document.add_information(model) + # ... and remove it! + ifcopenshell.api.document.remove_information(model, information=document) + """ + + if file.schema == "IFC2X3": + references = information.DocumentReferences or [] + else: + references = information.HasDocumentReferences + + for reference in references: + ifcopenshell.api.document.remove_reference(file, reference=reference) + + for rel in information.IsPointer or []: + for info in rel.RelatedDocuments: + ifcopenshell.api.document.remove_information(file, information=info) + + for rel in information.IsPointedTo or []: + if rel.RelatedDocuments == (information,): + # This relationship is non-rooted + file.remove(rel) + + if file.schema == "IFC2X3": + rels = [r for r in file.by_type("IfcRelAssociatesDocument") if r.RelatingDocument == information] + else: + rels = information.DocumentInfoForObjects + + for rel in rels: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + file.remove(information) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_reference.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_reference.py new file mode 100644 index 0000000000000000000000000000000000000000..e0dbd414c64342706b01cb2a4084f9d50cc43f43 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/remove_reference.py @@ -0,0 +1,50 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_reference(file: ifcopenshell.file, reference: ifcopenshell.entity_instance) -> None: + """Remove a document reference + + All associations with objects are removed. + + :param reference: The IfcDocumentReference to remove + :return: None + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + reference = ifcopenshell.api.document.add_reference(model, information=document) + ifcopenshell.api.document.remove_reference(model, reference=reference) + """ + + if file.schema == "IFC2X3": + rels = [r for r in file.get_inverse(reference) if r.is_a("IfcRelAssociatesDocument")] + else: + rels = reference.DocumentRefForObjects + + for rel in rels: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + file.remove(reference) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/unassign_document.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/unassign_document.py new file mode 100644 index 0000000000000000000000000000000000000000..0e9f2b2d966759b1b2c5c1568bc7a614ae3bac28 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/document/unassign_document.py @@ -0,0 +1,76 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_document( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + document: ifcopenshell.entity_instance, +) -> None: + """Unassigns a document and an association to the list of products + + :param product: The list of objects that the document reference or information is + related to. + :param document: The IfcDocumentReference (typically) or in rare cases + the IfcDocumentInformation that is associated with the product + :return: None + + Example: + + .. code:: python + + document = ifcopenshell.api.document.add_information(model) + ifcopenshell.api.document.edit_information(model, + information=document, + attributes={"Identification": "A-GA-6100", "Name": "Overall Plan", + "Location": "A-GA-6100 - Overall Plan.pdf"}) + reference = ifcopenshell.api.document.add_reference(model, information=document) + + # Let's imagine storey represents an IfcBuildingStorey for the ground floor + ifcopenshell.api.document.assign_document(model, products=[storey], document=reference) + + # Now let's change our mind and remove the association + ifcopenshell.api.document.unassign_document(model, products=[storey], document=reference) + """ + + # TODO: do we need to support non-ifcroot elements like we do in classification.add_reference? + # NOTE: reuses code from `library.un assign_reference` + + reference_rels: set[ifcopenshell.entity_instance] = set() + products_set = set(products) + for product in products_set: + reference_rels.update(product.HasAssociations) + + reference_rels = { + rel for rel in reference_rels if rel.is_a("IfcRelAssociatesDocument") and rel.RelatingDocument == document + } + + for rel in reference_rels: + related_objects = set(rel.RelatedObjects) - products_set + if related_objects: + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..41c7c27a6c46a1f25d48083ff1e9282dd311161a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/__init__.py @@ -0,0 +1,41 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Create relationships between features (e.g. openings) and physical elements + +A feature is a special element (created using +:func:`ifcopenshell.api.root.create_entity`) that may then be used to create +geometric changes in other elements (such as walls and slabs). Most commonly, a +feature would be an opening void. These voids may then be filled with doors, +trapdoors, skylights, and so on. +""" + +from .. import wrap_usecases +from .add_feature import add_feature +from .add_filling import add_filling +from .remove_feature import remove_feature +from .remove_filling import remove_filling + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_feature", + "add_filling", + "remove_feature", + "remove_filling", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_feature.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..5de3f2cf42419af2758aa6f70f7480004a558671 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_feature.py @@ -0,0 +1,149 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.api.geometry +import ifcopenshell.api.aggregate +import ifcopenshell.guid +import ifcopenshell.util.element +import ifcopenshell.util.placement + + +def add_feature( + file: ifcopenshell.file, feature: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + """Create a projecting, voiding, or surface feature in an element + + There are three main types of features: those that add, remove, or + influence geometry of a parent object. + + The most common of these is an opening. For example, it is often necessary + to cut out openings in elements like walls and slabs to make space to + insert doors, windows, and other services that go through these + penetrations. + + Whereas it is possible to simply draw the wall as a rectangle with a + hole in it for the opening, often these openings have specific meanings. + For example, an opening might be filled with a window, and so when the + window moves, the opening should move with it. Alternatively, the + opening itself might have fire or acoustic requirements, such that any + service or equipment passing through that space must also comply with + those requirements. For these types of semantic openings, you should + have a distinct opening element which voids your regular element. For + example, your wall will still be a rectangular prism with no hole in it, + and a separate opening element will have a box representing the extents + of the opening for a window. The opening element will automatically + perform a geometric boolean operation to cut out the wall's geometry. + + Whenever you have an opening in you project, you should determine + whether or not the opening is semantic (i.e. should be represented by a + distinct opening object) or non-semantic (i.e. should simply be + booleaned or be part of the shape of the object). + + :param feature: The IfcFeatureElement to affect the element. + :param element: The IfcElement to add the feature to. + :return: The new IfcRelVoidsElement relationship + + Example: + + .. code:: python + + # A bit of preparation, let's create some geometric contexts since + # we want to create some geometry for our wall and opening. + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Create a wall + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's use the "3D Body" representation we created earlier to add a + # new wall-like body geometry, 5 meters long, 3 meters high, and + # 200mm thick + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.2) + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + + # Create an opening, such as for a service penetration with fire and + # acoustic requirements. + opening = ifcopenshell.api.root.create_entity(model, ifc_class="IfcOpeningElement") + + # Let's create an opening representation of a 950mm x 2100mm door. + # Notice how the thickness is greater than the wall thickness, this + # helps resolve floating point resolution errors in 3D. + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=.95, height=2.1, thickness=0.4) + ifcopenshell.api.geometry.assign_representation(model, + product=opening, representation=representation) + + # Let's shift our door 1 meter along the wall and 100mm along the + # wall, to create a nice overlap for the opening boolean. + matrix = np.identity(4) + matrix[:,3] = [1, -.1, 0, 0] + ifcopenshell.api.geometry.edit_object_placement(model, product=opening, matrix=matrix) + + # The opening will now void the wall. + ifcopenshell.api.feature.add_feature(model, feature=opening, element=wall) + """ + if feature.is_a("IfcFeatureElementSubtraction"): + rels = feature.VoidsElements + ifc_class = "IfcRelVoidsElement" + elif feature.is_a("IfcFeatureElementAddition"): + rels = feature.ProjectsElements + ifc_class = "IfcRelProjectsElement" + elif feature.is_a("IfcSurfaceFeature"): + if file.schema == "IFC4": + return ifcopenshell.api.aggregate.assign_object(file, [feature], element) + rels = feature.AdheresToElement + ifc_class = "IfcRelAdheresToElement" + + if rels: + if rels[0][4] == element: + return rels[0] + elif ifc_class == "IfcRelAdheresToElement" and len(rels[0].RelatedSurfaceFeatures) != 1: + rels[0].RelatedSurfaceFeatures = list(set(rels[0].RelatedSurfaceFeatures) - {feature}) + else: + history = rels[0].OwnerHistory + file.remove(rels[0]) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + rel = file.create_entity( + ifc_class, + ifcopenshell.guid.new(), + ifcopenshell.api.owner.create_owner_history(file), + None, + None, + element, + [feature] if ifc_class == "IfcRelAdheresToElement" else feature, + ) + + if (placement := feature.ObjectPlacement) and placement.is_a("IfcLocalPlacement"): + ifcopenshell.api.geometry.edit_object_placement( + file, + product=feature, + matrix=ifcopenshell.util.placement.get_local_placement(placement), + is_si=False, + ) + + return rel diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_filling.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_filling.py new file mode 100644 index 0000000000000000000000000000000000000000..bb6035cd79595ab6593b28b035a91527de26fd63 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/add_filling.py @@ -0,0 +1,117 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.guid +import ifcopenshell.util.element + + +def add_filling( + file: ifcopenshell.file, opening: ifcopenshell.entity_instance, element: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + """Fill an opening with an element + + Physical elements may have openings in them. For example, a wall might + have an opening for a door. That opening is then filled by the door. + This indicates that when the door moves, the opening will move with it. + Or if the door is removed, then the opening may remain and need to be + filled. + + :param opening: The IfcOpeningElement to fill with the element. + :param element: The IfcElement to be inserted into the opening. + :return: The new IfcRelFillsElement relationship + + Example: + + .. code:: python + + # A bit of preparation, let's create some geometric contexts since + # we want to create some geometry for our wall and opening. + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Create a wall + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's use the "3D Body" representation we created earlier to add a + # new wall-like body geometry, 5 meters long, 3 meters high, and + # 200mm thick + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.2) + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + + # Create an opening, such as for a service penetration with fire and + # acoustic requirements. + opening = ifcopenshell.api.root.create_entity(model, ifc_class="IfcOpeningElement") + + # Let's create an opening representation of a 950mm x 2100mm door. + # Notice how the thickness is greater than the wall thickness, this + # helps resolve floating point resolution errors in 3D. + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=.95, height=2.1, thickness=0.4) + ifcopenshell.api.geometry.assign_representation(model, + product=opening, representation=representation) + + # Let's shift our door 1 meter along the wall and 100mm along the + # wall, to create a nice overlap for the opening boolean. + matrix = np.identity(4) + matrix[:,3] = [1, -.1, 0, 0] + ifcopenshell.api.geometry.edit_object_placement(model, product=opening, matrix=matrix) + + # The opening will now void the wall. + ifcopenshell.api.feature.add_feature(model, feature=opening, element=wall) + + # Create a door + door = ifcopenshell.api.root.create_entity(model, ifc_class="IfcDoor") + + # Let's create a door representation of a 950mm x 2100mm door. + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=.95, height=2.1, thickness=0.05) + ifcopenshell.api.geometry.assign_representation(model, + product=door, representation=representation) + + # Let's shift our door 1 meter along the wall and 100mm along the + # wall, which lines up with our opening. + matrix = np.identity(4) + matrix[:,3] = [1, .05, 0, 0] + ifcopenshell.api.geometry.edit_object_placement(model, product=door, matrix=matrix) + + # The door will now fill the opening. + ifcopenshell.api.feature.add_filling(model, opening=opening, element=door) + """ + fills_voids = element.FillsVoids + + if fills_voids: + if fills_voids[0].RelatingOpeningElement == opening: + return fills_voids[0] + history = fills_voids[0].OwnerHistory + file.remove(fills_voids[0]) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + return file.create_entity( + "IfcRelFillsElement", + GlobalId=ifcopenshell.guid.new(), + RelatingOpeningElement=opening, + RelatedBuildingElement=element, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_feature.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_feature.py new file mode 100644 index 0000000000000000000000000000000000000000..6a1d5e5610b0441f6f35ebbf3c50ce6b14f1eb02 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_feature.py @@ -0,0 +1,66 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.root +import ifcopenshell.api.aggregate +import ifcopenshell.util.element + + +def remove_feature(file: ifcopenshell.file, feature: ifcopenshell.entity_instance) -> None: + """Remove a feature + + Fillings are retained as orphans. Featured elements remain. Features + cannot exist by themselves, so not only is the relationship removed, the + feature is also removed. + + :param feature: The IfcFeatureElement to remove. + + Example: + + .. code:: python + + # Create an orphaned opening. Note that an orphaned opening is + # invalid, as an opening can only exist when voiding another + # element. + feature = ifcopenshell.api.root.create_entity(model, ifc_class="IfcOpeningElement") + + # Remove it. This brings us back to a valid model. + ifcopenshell.api.feature.remove_feature(model, feature=feature) + """ + if feature.is_a("IfcFeatureElementSubtraction"): + rels = feature.VoidsElements + elif feature.is_a("IfcFeatureElementAddition"): + rels = feature.ProjectsElements + elif feature.is_a("IfcSurfaceFeature"): + if file.schema == "IFC4": + ifcopenshell.api.aggregate.unassign_object(file, products=[feature]) + rels = [] + else: + rels = feature.ProjectsElements + for rel in rels: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + if feature.is_a("IfcOpeningElement"): + for rel in feature.HasFillings: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + ifcopenshell.api.root.remove_product(file, product=feature) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_filling.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_filling.py new file mode 100644 index 0000000000000000000000000000000000000000..b009b1e0c40c101026989a2ecabe6bb988c6ec5c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/feature/remove_filling.py @@ -0,0 +1,59 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_filling(file: ifcopenshell.file, element: ifcopenshell.entity_instance) -> None: + """Remove a filling relationship + + If an element is filling an opening, this removes the relationship such + that the opening and element both still exist, but the element no longer + fills the opening. + + :param element: The element filling an opening. + :return: None + + Example: + + .. code:: python + + # Create a wall + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Create an opening, such as for a service penetration with fire and + # acoustic requirements. + opening = ifcopenshell.api.root.create_entity(model, ifc_class="IfcOpeningElement") + + # Create a door + door = ifcopenshell.api.root.create_entity(model, ifc_class="IfcDoor") + + # The door will now fill the opening. + ifcopenshell.api.feature.add_filling(model, opening=opening, element=door) + + # Not anymore! + ifcopenshell.api.feature.remove_filling(model, element=door) + """ + for rel in file.by_type("IfcRelFillsElement"): + if rel.RelatedBuildingElement == element: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + break diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..44728c2902262fe92968d8f5c71a0cdbdd289f1b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/__init__.py @@ -0,0 +1,88 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Create geometric representations and assign them to elements + +These functions support both the creation of arbitrary geometry as well as +geometry that follows parametric rules (e.g. layered geometry or profiled +geometry extrusions). +""" + +from .. import wrap_usecases +from .add_axis_representation import add_axis_representation +from .add_boolean import add_boolean +from .add_door_representation import add_door_representation +from .add_footprint_representation import add_footprint_representation +from .add_mesh_representation import add_mesh_representation +from .add_profile_representation import add_profile_representation +from .add_railing_representation import add_railing_representation + +try: + from .add_representation import add_representation +except (ModuleNotFoundError, ImportError): + # ImportError - in case if user has fake-bpy modules. + pass # Silently fail. This is Blender / Bonsai specific and on its way out. +from .add_shape_aspect import add_shape_aspect +from .add_slab_representation import add_slab_representation +from .add_wall_representation import add_wall_representation +from .add_window_representation import add_window_representation +from .assign_representation import assign_representation +from .connect_element import connect_element +from .connect_path import connect_path +from .connect_wall import connect_wall +from .create_2pt_wall import create_2pt_wall +from .disconnect_element import disconnect_element +from .disconnect_path import disconnect_path +from .edit_object_placement import edit_object_placement +from .map_representation import map_representation +from .regenerate_wall_representation import regenerate_wall_representation +from .remove_boolean import remove_boolean +from .remove_representation import remove_representation +from .unassign_representation import unassign_representation +from .validate_type import validate_type + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_axis_representation", + "add_boolean", + "add_door_representation", + "add_footprint_representation", + "add_mesh_representation", + "add_profile_representation", + "add_railing_representation", + "add_representation", + "add_shape_aspect", + "add_slab_representation", + "add_wall_representation", + "add_window_representation", + "assign_representation", + "connect_element", + "connect_path", + "connect_wall", + "create_2pt_wall", + "disconnect_element", + "disconnect_path", + "edit_object_placement", + "map_representation", + "regenerate_wall_representation", + "remove_boolean", + "remove_representation", + "unassign_representation", + "validate_type", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_axis_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_axis_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..02bd057cc60b6e4b85d88c7792f2663150828e06 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_axis_representation.py @@ -0,0 +1,110 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.unit +from typing import Union, Any + +COORD = Union[tuple[float, float], tuple[float, float, float]] + + +def add_axis_representation( + file: ifcopenshell.file, context: ifcopenshell.entity_instance, axis: tuple[COORD, COORD] +) -> ifcopenshell.entity_instance: + """Adds a new axis representation + + Certain objects are typically "axis-based", such as walls, beams, + and columns. This means you can represent them abstractly by simply + drawing a single line either in 2D (such as for walls) or 3D (for beams + and columns). Humans can understand this axis-based representation as + being a simplification of a layered extrusion or a profile that is being + extruded along that axis and joined to other elements. + + Using an axis-based representation makes it easy for users and computers + to analyse connectivity and spatial relationships, as well as makes it + easy to parametrically edit these objects by simply stretching the start + or end of the axis. + + For now, only simple straight line axes are supported, represented by a + start and end coordinate. The order is important. For walls, the start + must be at the minimum local X ordinate, and the end at the maximum + local X ordinate. For beams and columns, the start is at the minimum + local Z ordinate, and the end of the maximum local Z ordinate. The first + coordinate is the "start" and the second coordinate is the "end". This + stat and end is then used to determine any parametric junctions with + other elements. + + Using an axis-representation is optional, but highly recommended for + "standard" representations of walls, beams, columns, and other + structural members. A rule of thumb is that if you can draw it as a line + on paper, you can probably represent it using an axis. + + :param context: The IfcGeometricRepresentationContext that the + representation is part of. This must be either a + Model/Axis/GRAPH_VIEW (3D) or Plan/Axis/GRAPH_VIEW (2D). + :param axis: The axis, as a list of two coordinates, the coordinates + being either a list of 2 or 3 float coordinates depending on whether + the axis is 2D or 3D. + :return: The newly created IfcShapeRepresentation entity + + Example: + + .. code:: python + + context = ifcopenshell.util.representation.get_context(model, "Plan", "Axis", "GRAPH_VIEW") + axis = ifcopenshell.api.geometry.add_axis_representation(model, + context=context, axis=[(0.0, 0.0), (1.0, 0.0)]) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "context": context, + "axis": axis or [], + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + self.settings["unit_scale"] = ifcopenshell.util.unit.calculate_unit_scale(self.file) + is_2d = len(self.settings["axis"][0]) == 2 + points = [self.convert_si_to_unit(p) for p in self.settings["axis"]] + if self.file.schema == "IFC2X3": + curve = self.file.createIfcPolyline([self.file.createIfcCartesianPoint(p) for p in points]) + else: + if is_2d: + curve = self.file.createIfcIndexedPolyCurve( + self.file.createIfcCartesianPointList2D(points), None, False + ) + else: + curve = self.file.createIfcIndexedPolyCurve( + self.file.createIfcCartesianPointList3D(points), None, False + ) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Curve2D" if is_2d else "Curve3D", + [curve], + ) + + def convert_si_to_unit(self, co): + if isinstance(co, (tuple, list)): + return [self.convert_si_to_unit(o) for o in co] + return co / self.settings["unit_scale"] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_boolean.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_boolean.py new file mode 100644 index 0000000000000000000000000000000000000000..f5d0a314560d7150c97cc9a4aa5c7d4a22e1f0a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_boolean.py @@ -0,0 +1,126 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import ifcopenshell.util.element +from typing import Literal + + +def add_boolean( + file: ifcopenshell.file, + first_item: ifcopenshell.entity_instance, + second_items: list[ifcopenshell.entity_instance], + operator: Literal["DIFFERENCE", "INTERSECTION", "UNION"] = "DIFFERENCE", +) -> list[ifcopenshell.entity_instance]: + """Adds a boolean operation to two or more representation items + + If an IfcBooleanOperand is part of the top level items in an + IfcShapeRepresentation, it will be removed from that level whilst being + added to the IfcBooleanResult. This is because it is generally intuitive + that an item is either participating in a boolean operation, or being an + item in its own right, but not both. + + However, if an IfcBooleanOperand is part of another boolean operation + already, it will not be removed from the existing operation. A new + operation will be created, and therefore it will participate in two + operations. + + This function protects against recursive booleans. + + After a boolean operation is made, since the items of + IfcShapeRepresentation may be modified, it is not guaranteed that the + RepresentationType is still valid. After performing all your booleans, it + is recommended to run :func:`ifcopenshell.api.geometry.validate_csg` to + ensure correctness. + + :param first_item: The IfcBooleanOperand that the operation is performed upon + :param second_items: The IfcBooleanOperands that the operation will be + performed with, in the order given of the list. + :param operator: The type of boolean operation to perform + :return: A list of newly created IfcBooleanResult in the order of boolean + operations (based on the order of second items). If nothing was + created, the list will be empty. + """ + + def is_operand(item): + return ( + item.is_a("IfcBooleanResult") + or item.is_a("IfcCsgPrimitive3D") + or item.is_a("IfcHalfSpaceSolid") + or item.is_a("IfcSolidModel") + or item.is_a("IfcTessellatedFaceSet") + ) + + if not is_operand(first_item): + return [] + + original_first_item = first_item + + second_items = [i for i in second_items if i != first_item and is_operand(i)] + + while True: + is_part_of_boolean = False + for inverse in file.get_inverse(first_item): + if inverse.is_a("IfcBooleanResult"): + is_part_of_boolean = True + first_item = inverse + if inverse.FirstOperand == original_first_item and inverse.SecondOperand in second_items: + second_items.remove(inverse.SecondOperand) + elif inverse.SecondOperand == original_first_item and inverse.FirstOperand in second_items: + second_items.remove(inverse.FirstOperand) + break + if not is_part_of_boolean: + break + + if not second_items: + return [] + + # Don't replace style or aspect relationships. + to_replace = set( + [i for i in file.get_inverse(first_item) if i.is_a("IfcShapeRepresentation") or i.is_a("IfcBooleanResult")] + ) + + first = first_item + + booleans = [] + for second_item in second_items: + for inverse in file.get_inverse(second_item): + if inverse.is_a("IfcShapeRepresentation"): + inverse.Items = list(set(inverse.Items) - {second_item}) + if first.is_a("IfcTesselatedFaceSet"): + first.Closed = True # For now, trust the user to do the right thing. + if second_item.is_a("IfcTesselatedFaceSet"): + second_item.Closed = True # For now, trust the user to do the right thing. + if ( + operator == "DIFFERENCE" + and second_item.is_a("IfcHalfSpaceSolid") + and ( + first.is_a("IfcSweptAreaSolid") + or first.is_a("IfcSweptDiskSolid") + or first.is_a("IfcBooleanClippingResult") + ) + ): + first = file.create_entity("IfcBooleanClippingResult", operator, first, second_item) + else: + first = file.create_entity("IfcBooleanResult", operator, first, second_item) + booleans.append(first) + + for inverse in to_replace: + ifcopenshell.util.element.replace_attribute(inverse, first_item, first) + + return booleans diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_door_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_door_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..d91b7b0327342672768c8e19025cf1b35f53170c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_door_representation.py @@ -0,0 +1,680 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import sys +import ifcopenshell.util.unit +import ifcopenshell.api.geometry +import dataclasses +import numpy as np +from ifcopenshell.util.shape_builder import ShapeBuilder, V +from ifcopenshell.api.geometry.add_window_representation import create_ifc_window +from math import cos, radians +from typing import Any, Optional, Literal, Union, get_args, overload + +DATACLASS_SLOTS = {} if sys.version_info < (3, 10) else {"slots": True} + + +DOOR_TYPE = Literal[ + "SINGLE_SWING_LEFT", + "SINGLE_SWING_RIGHT", + "DOUBLE_SWING_RIGHT", + "DOUBLE_SWING_LEFT", + "DOUBLE_DOOR_SINGLE_SWING", + "DOUBLE_DOOR_DOUBLE_SWING", + "SLIDING_TO_LEFT", + "SLIDING_TO_RIGHT", + "DOUBLE_DOOR_SLIDING", +] +SUPPORTED_DOOR_TYPES = get_args(DOOR_TYPE) + + +def mm(x: float) -> float: + """mm to meters shortcut for readability""" + return x / 1000 + + +def create_ifc_door_lining( + builder: ShapeBuilder, size: np.ndarray, thickness: Union[list[float], float], position: Optional[np.ndarray] = None +) -> ifcopenshell.entity_instance: + """`thickness` of the profile is defined as list in the following order: `(SIDE, TOP)` + + `thickness` can be also defined just as 1 float value. + """ + np_X, np_Y, np_Z = 0, 1, 2 + np_XZ = [0, 2] + if not isinstance(thickness, list): + thickness = [thickness, thickness] + + th_side, th_up = thickness + + points = V( + [ + (0.0, 0.0, 0.0), + (0.0, 0.0, size[np_Z]), + (size[np_X], 0.0, size[np_Z]), + (size[np_X], 0.0, 0.0), + (size[np_X] - th_side, 0.0, 0.0), + (size[np_X] - th_side, 0.0, size[np_Z] - th_up), + (th_side, 0.0, size[np_Z] - th_up), + (th_side, 0.0, 0.0), + ] + ) + + points = points[:, np_XZ] + door_lining = builder.polyline(points, closed=True) + door_lining = builder.extrude(door_lining, size[np_Y], **builder.extrude_kwargs("Y")) + if position is None: + position = np.zeros(3) + builder.translate(door_lining, position) + + return door_lining + + +def create_ifc_box( + builder: ShapeBuilder, size: np.ndarray, position: Optional[np.ndarray] = None +) -> ifcopenshell.entity_instance: + np_Z, np_XY = 2, slice(2) + rect = builder.rectangle(size[np_XY]) + if position is None: + position = np.zeros(3) + box = builder.extrude(rect, size[np_Z], position=position, extrusion_vector=(0, 0, 1)) + return box + + +# we use dataclass as we need default values for arguments +# it's okay to use slots since we don't need dynamic attributes +@dataclasses.dataclass(**DATACLASS_SLOTS) +class DoorLiningProperties: + LiningDepth: Optional[float] = None + """Optional, defaults to 50mm.""" + + LiningThickness: Optional[float] = None + """Optional, defaults to 50mm.""" + + LiningOffset: Optional[float] = None + """Offset from the outer side of the wall (by Y-axis). Optional, defaults to 0.0.""" + + LiningToPanelOffsetX: Optional[float] = None + """Offset from the wall. Optional, defaults to 25mm.""" + + LiningToPanelOffsetY: Optional[float] = None + """Offset from the X-axis (unlike windows). Optional, defaults to 25mm.""" + + TransomThickness: Optional[float] = None + """Vertical distance between door and window panels. Optional, defaults to 0.0.""" + + TransomOffset: Optional[float] = None + """Distance from the bottom door opening + to the beginning of the transom + unlike windows TransomOffset which goes to the center of the transom. + Optional, defaults 1.525m.""" + + ShapeAspectStyle: None = None + """Optional. Deprecated argument.""" + + CasingDepth: Optional[float] = None + """Casing cover wall faces around the opening + on the left, right and upper sides + Casing should be either on both sides of the wall or no casing + If `LiningOffset` is present then therefore casing is not possible on outer wall + therefore there will be no casing on inner wall either. Optional, defaults to 5mm.""" + + CasingThickness: Optional[float] = None + """Casing thickness by Z-axis. Optional, defaults to 75mm.""" + + ThresholdDepth: Optional[float] = None + """Threshold covers the bottom side of the opening. Optional, defaults to 100mm.""" + + ThresholdThickness: Optional[float] = None + """Theshold thickness by Z-axis. Optional, defaults to 25mm.""" + + ThresholdOffset: Optional[float] = None + """Threshold offset by Y-axis. Optional, defaults to 0.0.""" + + def initialize_properties(self, unit_scale: float) -> None: + # in meters + # fmt: off + default_values: dict[str, float] = dict( + LiningDepth = mm(50), + LiningThickness = mm(50), + LiningOffset = 0.0, + LiningToPanelOffsetX = mm(25), + LiningToPanelOffsetY = mm(25), + TransomThickness = 0.0, + TransomOffset = mm(1525), + CasingDepth = mm(5), + CasingThickness = mm(75), + ThresholdDepth = mm(100), + ThresholdThickness = mm(25), + ThresholdOffset = 0.0, + ) + # fmt: on + + si_conversion = 1 / unit_scale + for attr, default_value in default_values.items(): + if getattr(self, attr) is not None: + continue + setattr(self, attr, default_value * si_conversion) + + +@dataclasses.dataclass(**DATACLASS_SLOTS) +class DoorPanelProperties: + PanelDepth: Optional[float] = None + """Frame thickness by Y axis. Optional, defaults to 35 mm.""" + + PanelWidth: float = 1.0 + """Ratio to the clear door opening. Optional, defaults to 1.0.""" + + FrameDepth: Optional[float] = None + """Frame thickness by Y axis. Optional, defaults to 35 mm.""" + + FrameThickness: Optional[float] = None + """Frame thickness by X axis. Optional, defaults to 35 mm.""" + + PanelPosition: None = None + """Optional, value is never used""" + + PanelOperation: None = None + """Optional, value is never used. + Defines the basic ways to describe how door panels operate.""" + + ShapeAspectStyle: None = None + """Optional. Deprecated argument.""" + + def initialize_properties(self, unit_scale: float) -> None: + # in meters + # fmt: off + default_values: dict[str, float] = dict( + PanelDepth = mm(35), + FrameDepth = mm(35), + FrameThickness = mm(35), + ) + # fmt: on + + si_conversion = 1 / unit_scale + for attr, default_value in default_values.items(): + if getattr(self, attr) is not None: + continue + setattr(self, attr, default_value * si_conversion) + + +def add_door_representation( + file: ifcopenshell.file, + *, # keywords only as this API implementation is probably not final + context: ifcopenshell.entity_instance, + overall_height: Optional[float] = None, + overall_width: Optional[float] = None, + # door type + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcDoorTypeOperationEnum.htm + operation_type: DOOR_TYPE = "SINGLE_SWING_LEFT", + lining_properties: Optional[Union[DoorLiningProperties, dict[str, Any]]] = None, + panel_properties: Optional[Union[DoorPanelProperties, dict[str, Any]]] = None, + part_of_product: Optional[ifcopenshell.entity_instance] = None, + unit_scale: Optional[float] = None, +) -> Union[ifcopenshell.entity_instance, None]: + """Add a geometric representation for a door. + + units in usecase_settings expected to be in ifc project units + + :param context: IfcGeometricRepresentationContext for the representation. + :param overall_height: Overall door height. Defaults to 2m. + :param overall_width: Overall door width. Defaults to 0.9m. + :param operation_type: Type of the door. Defaults to SINGLE_SWING_LEFT. + :param lining_properties: DoorLiningProperties or a dictionary to create one. + See DoorLiningProperties description for details. + :param panel_properties: DoorPanelProperties or a dictionary to create one. + See DoorPanelProperties description for details. + :param unit_scale: The unit scale as calculated by + ifcopenshell.util.unit.calculate_unit_scale. If not provided, it + will be automatically calculated for you. + :return: IfcShapeRepresentation for a door. + """ + usecase = Usecase() + usecase.file = file + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcDoor.htm + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcDoorLiningProperties.htm + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcDoorPanelProperties.htm + # define unit_scale first as it's going to be used setting default arguments + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) if unit_scale is None else unit_scale + settings: dict[str, Any] = {"unit_scale": unit_scale} + + if lining_properties is None: + lining_properties = DoorLiningProperties() + elif not isinstance(lining_properties, DoorLiningProperties): + lining_properties = DoorLiningProperties(**lining_properties) + lining_properties.initialize_properties(unit_scale) + lining_properties = dataclasses.asdict(lining_properties) + + if panel_properties is None: + panel_properties = DoorPanelProperties() + elif not isinstance(panel_properties, DoorPanelProperties): + panel_properties = DoorPanelProperties(**panel_properties) + panel_properties.initialize_properties(unit_scale) + panel_properties = dataclasses.asdict(panel_properties) + + settings.update( + { + "context": context, + "overall_height": overall_height if overall_height is not None else usecase.convert_si_to_unit(2.0), + "overall_width": overall_width if overall_width is not None else usecase.convert_si_to_unit(0.9), + "operation_type": operation_type, + "lining_properties": lining_properties, + "panel_properties": panel_properties, + "part_of_product": part_of_product, + } + ) + usecase.settings = settings + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self) -> Union[ifcopenshell.entity_instance, None]: + builder = ShapeBuilder(self.file) + + np_X, np_Y, np_Z = 0, 1, 2 + np_XY = slice(2) + np_YX = [1, 0] + + overall_height: float = self.settings["overall_height"] + overall_width: float = self.settings["overall_width"] + door_type: DOOR_TYPE = self.settings["operation_type"] + double_swing_door = "DOUBLE_SWING" in door_type + double_door = "DOUBLE_DOOR" in door_type + sliding_door = "SLIDING" in door_type + + if self.settings["context"].TargetView == "ELEVATION_VIEW": + rect = builder.rectangle((overall_width, 0, overall_height)) + representation_evelevation = builder.get_representation(self.settings["context"], rect) + return representation_evelevation + + panel_props = self.settings["panel_properties"] + lining_props = self.settings["lining_properties"] + + # lining params + lining_depth: float = lining_props["LiningDepth"] + lining_thickness_default: float = lining_props["LiningThickness"] + lining_offset: float = lining_props["LiningOffset"] + lining_to_panel_offset_x: float = ( + lining_props["LiningToPanelOffsetX"] if not sliding_door else lining_thickness_default + ) + panel_depth: float = panel_props["PanelDepth"] + lining_to_panel_offset_y_full: float = ( + lining_props["LiningToPanelOffsetY"] if not sliding_door else -panel_depth + ) + + transom_thickness: float = lining_props["TransomThickness"] / 2 + transfom_offset: float = lining_props["TransomOffset"] + if transom_thickness == 0: + transfom_offset = 0 + window_lining_height = overall_height - transfom_offset - transom_thickness + + side_lining_thickness = lining_thickness_default + panel_lining_overlap_x = max(lining_thickness_default - lining_to_panel_offset_x, 0) if not sliding_door else 0 + + top_lining_thickness = transom_thickness or lining_thickness_default + panel_top_lining_overlap_x = max(top_lining_thickness - lining_to_panel_offset_x, 0) if not sliding_door else 0 + door_opening_width = overall_width - lining_to_panel_offset_x * 2 + if double_swing_door: + side_lining_thickness = side_lining_thickness - panel_lining_overlap_x + top_lining_thickness = top_lining_thickness - panel_top_lining_overlap_x + + threshold_thickness: float = lining_props["ThresholdThickness"] + threshold_depth: float = lining_props["ThresholdDepth"] + threshold_offset: float = lining_props["ThresholdOffset"] + threshold_width = overall_width - side_lining_thickness * 2 + + casing_thickness: float = lining_props["CasingThickness"] + casing_depth: float = lining_props["CasingDepth"] + + # panel params + panel_width: float = door_opening_width * panel_props["PanelWidth"] + frame_depth: float = panel_props["FrameDepth"] + frame_thickness: float = panel_props["FrameThickness"] + frame_height = window_lining_height - lining_to_panel_offset_x * 2 + glass_thickness = self.convert_si_to_unit(0.01) + + # handle dimensions (hardcoded) + handle_size = self.convert_si_to_unit(V(120, 40, 20) * 0.001) + handle_offset = self.convert_si_to_unit(V(60, 0, 1000) * 0.001) # to the handle center + handle_center_offset = V(handle_size[np_Y] / 2, 0, handle_size[np_Z]) / 2 + slider_arrow_symbol_size = self.convert_si_to_unit(30 * 0.001) + + if transfom_offset: + panel_height = transfom_offset + transom_thickness - lining_to_panel_offset_x - threshold_thickness + lining_height = transfom_offset + transom_thickness + else: + panel_height = overall_height - lining_to_panel_offset_x - threshold_thickness + lining_height = overall_height + + # add lining + lining_size = V(overall_width, lining_depth, lining_height) + lining_thickness = [side_lining_thickness, top_lining_thickness] + + def l_shape_check(lining_thickness: list[float]) -> bool: + return lining_to_panel_offset_y_full < lining_depth and any( + lining_to_panel_offset_x < th for th in lining_thickness + ) + + # create 2d representation + if self.settings["context"].TargetView == "PLAN_VIEW": + items_2d: list[ifcopenshell.entity_instance] = [] + panel_size = V(panel_width, panel_depth) + if not sliding_door: + panel_position = V(lining_to_panel_offset_x, lining_depth) + else: + panel_position = V(lining_to_panel_offset_x, -panel_size[np_Y]) + + if self.settings["context"].ContextIdentifier == "Annotation": + # only sliding door has annotation representation + if not sliding_door: + return None + + # arrow symbol + arrow_symbol: list[ifcopenshell.entity_instance] = [] + arrow_offset = slider_arrow_symbol_size / cos(radians(15)) + arrow_symbol.append( + builder.polyline( + points=((0.35 * panel_size[np_X], 0), (0.65 * panel_size[np_X], 0)), + ) + ) + arrow_symbol.append( + builder.polyline( + points=( + (slider_arrow_symbol_size, arrow_offset), + (0, 0), + (slider_arrow_symbol_size, -arrow_offset), + ), + position_offset=(0.35 * panel_size[np_X], 0), + ) + ) + + builder.translate(arrow_symbol, panel_position + (0, -arrow_offset * 1.5)) + + items_2d.extend(arrow_symbol) + + representation_2d = builder.get_representation(self.settings["context"], items_2d, "Curve2D") + return representation_2d + + door_items: list[ifcopenshell.entity_instance] = [] + # create lining + if l_shape_check([side_lining_thickness]): + lining_points = [ + (0, 0), + (0, lining_depth), + (lining_to_panel_offset_x, lining_depth), + (lining_to_panel_offset_x, lining_to_panel_offset_y_full), + (lining_thickness_default, lining_to_panel_offset_y_full), + (lining_thickness_default, 0), + ] + lining = builder.polyline(lining_points, closed=True) + else: + lining = builder.rectangle((side_lining_thickness, lining_depth)) + + items_2d.append(lining) + items_2d.append( + builder.mirror(lining, mirror_axes=V(1, 0), mirror_point=V(overall_width / 2, 0), create_copy=True) + ) + + # TODO: make second swing lines dashed + def create_ifc_door_panel_2d( + panel_size: np.ndarray, + panel_position: np.ndarray, + door_swing_type: Literal["LEFT", "RIGHT"], + sliding: bool = False, + ) -> list[ifcopenshell.entity_instance]: + if sliding: + return create_ifc_door_sliding_panel_2d(panel_size, panel_position, door_swing_type) + + door_items: list[ifcopenshell.entity_instance] = [] + panel_size = panel_size[np_YX] + # create semi-semi-circle + if double_swing_door: + trim_points_mask = (3, 1) + second_swing_line = builder.polyline( + points=( + (0, 0), + (0, -panel_size[np_Y]), + (panel_size[np_X], -panel_size[np_Y]), + ) + ) + door_items.append(second_swing_line) + else: + trim_points_mask = (0, 1) + semicircle = builder.create_ellipse_curve( + panel_size[np_Y] - panel_size[np_X], + panel_size[np_Y], + trim_points_mask=trim_points_mask, + position=(panel_size[np_X], 0), + ) + door_items.append(semicircle) + + # create door + door = builder.rectangle(panel_size) + door_items.append(door) + + builder.translate(door_items, panel_position) + + if door_swing_type == "RIGHT": + mirror_point = panel_position + (panel_size[np_Y] / 2, 0) + builder.mirror(door_items, mirror_axes=(1, 0), mirror_point=mirror_point) + return door_items + + def create_ifc_door_sliding_panel_2d( + panel_size: np.ndarray, panel_position: np.ndarray, door_swing_type: Literal["LEFT", "RIGHT"] + ) -> list[ifcopenshell.entity_instance]: + door = builder.rectangle(panel_size, position=panel_position - (panel_size[np_X] * 0.5, 0)) + + if door_swing_type == "RIGHT": + mirror_point = panel_position + (panel_size[np_X] / 2, 0) + builder.mirror(door, mirror_axes=(1, 0), mirror_point=mirror_point) + return [door] + + door_items: list[ifcopenshell.entity_instance] = [] + if double_door: + panel_size[np_X] = panel_size[np_X] / 2 + door_items.extend(create_ifc_door_panel_2d(panel_size, panel_position, "LEFT", sliding_door)) + + mirror_point = panel_position + V(door_opening_width / 2, 0) + door_items.extend( + builder.mirror(door_items, mirror_axes=(1, 0), mirror_point=mirror_point, create_copy=True) + ) + else: + door_swing_type = "LEFT" if door_type.endswith("LEFT") else "RIGHT" + door_items.extend(create_ifc_door_panel_2d(panel_size, panel_position, door_swing_type, sliding_door)) + items_2d.extend(door_items) + + builder.translate(items_2d, (0, lining_offset)) + representation_2d = builder.get_representation(self.settings["context"], items_2d) + return representation_2d + + lining_items: list[ifcopenshell.entity_instance] = [] + main_lining_size = lining_size + + # need to check offsets to decide whether lining should be rectangle + # or L shaped + if l_shape_check(lining_thickness): + main_lining_size = lining_size.copy() + main_lining_size[np_Y] = lining_to_panel_offset_y_full + + second_lining_size = lining_size.copy() + second_lining_size[np_Y] = lining_size[np_Y] - lining_to_panel_offset_y_full + second_lining_position = V(0, lining_to_panel_offset_y_full, 0) + second_lining_thickness = [min(th, lining_to_panel_offset_x) for th in lining_thickness] + + second_lining = create_ifc_door_lining( + builder, second_lining_size, second_lining_thickness, second_lining_position + ) + lining_items.append(second_lining) + + main_lining = create_ifc_door_lining(builder, main_lining_size, lining_thickness) + lining_items.append(main_lining) + + # add threshold + threshold_items: list[ifcopenshell.entity_instance] + if not threshold_thickness: + threshold_items = [] + else: + threshold_size = V(threshold_width, threshold_depth, threshold_thickness) + threshold_position = V(side_lining_thickness, threshold_offset, 0) + threshold_items = [create_ifc_box(builder, threshold_size, threshold_position)] + + # add casings + casing_items: list[ifcopenshell.entity_instance] = [] + if not lining_offset and casing_thickness: + casing_wall_overlap = max(casing_thickness - lining_thickness_default, 0) + inner_casing_thickness = [ + casing_thickness - panel_lining_overlap_x, + casing_thickness - panel_top_lining_overlap_x, + ] + outer_casing_thickness = inner_casing_thickness.copy() if double_swing_door else casing_thickness + + casing_size = V(overall_width + casing_wall_overlap * 2, casing_depth, overall_height + casing_wall_overlap) + casing_position = V(-casing_wall_overlap, -casing_depth, 0) + outer_casing = create_ifc_door_lining(builder, casing_size, outer_casing_thickness, casing_position) + casing_items.append(outer_casing) + + inner_casing_position = V(-casing_wall_overlap, lining_depth, 0) + inner_casing = create_ifc_door_lining(builder, casing_size, inner_casing_thickness, inner_casing_position) + casing_items.append(inner_casing) + + def create_ifc_door_panel( + panel_size: np.ndarray, panel_position: np.ndarray, door_swing_type: Literal["LEFT", "RIGHT"] + ) -> list[ifcopenshell.entity_instance]: + door_items: list[ifcopenshell.entity_instance] = [] + # add door panel + door_items.append(create_ifc_box(builder, panel_size, panel_position)) + # add door handle + handle_points = [ + (0, 0), + (0, -handle_size[np_Y]), + (handle_size[np_X], -handle_size[np_Y]), + (handle_size[np_X], -handle_size[np_Y] / 2), + (handle_size[np_Y] / 2, -handle_size[np_Y] / 2), + (handle_size[np_Y] / 2, 0), + ] + handle_polyline = builder.polyline(handle_points, closed=True) + + handle_position = panel_position + handle_offset - handle_center_offset + + door_handle = builder.extrude(handle_polyline, handle_size[np_Z], position=handle_position) + door_items.append(door_handle) + + if door_swing_type == "LEFT": + builder.mirror( + door_handle, mirror_axes=(1, 0), mirror_point=panel_position[np_XY] + (panel_size[np_X] / 2, 0) + ) + + door_handle_mirrored = builder.mirror( + door_handle, + mirror_axes=(0, 1), + mirror_point=handle_position[np_XY] + (0, panel_size[np_Y] / 2), + create_copy=True, + ) + door_items.append(door_handle_mirrored) + return door_items + + door_items: list[ifcopenshell.entity_instance] = [] + panel_size = V(panel_width, panel_depth, panel_height) + panel_position = V(lining_to_panel_offset_x, lining_to_panel_offset_y_full, threshold_thickness) + + if double_door: + # keeping a little space between doors for readibility + double_door_offset = self.convert_si_to_unit(0.001) + panel_size[np_X] = panel_size[np_X] / 2 - double_door_offset + door_items.extend(create_ifc_door_panel(panel_size, panel_position, "LEFT")) + + mirror_point = panel_position + V(door_opening_width / 2, 0, 0) + door_items.extend( + builder.mirror(door_items, mirror_axes=(1, 0), mirror_point=mirror_point[np_XY], create_copy=True) + ) + else: + door_swing_type = "LEFT" if door_type.endswith("LEFT") else "RIGHT" + door_items.extend(create_ifc_door_panel(panel_size, panel_position, door_swing_type)) + + # add on top window + if not transom_thickness: + window_lining_items = [] + frame_items = [] + glass_items = [] + else: + window_lining_thickness = [ + side_lining_thickness, + lining_thickness_default, + side_lining_thickness, + transom_thickness, + ] + window_lining_size = V(overall_width, lining_depth, window_lining_height) + window_position = V(0, 0, overall_height - window_lining_height) + frame_size = V(door_opening_width, frame_depth, frame_height) + current_window_items = create_ifc_window( + builder, + window_lining_size, + window_lining_thickness, + lining_to_panel_offset_x, + lining_to_panel_offset_y_full, + frame_size, + frame_thickness, + glass_thickness, + window_position, + ) + window_lining_items = current_window_items["Lining"] + frame_items = current_window_items["Framing"] + glass_items = current_window_items["Glazing"] + + lining_offset_items = lining_items + door_items + window_lining_items + frame_items + glass_items + builder.translate(lining_offset_items, (0, lining_offset, 0)) + + output_items = lining_offset_items + threshold_items + casing_items + + representation = builder.get_representation(self.settings["context"], output_items) + if self.settings["part_of_product"]: + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Lining", + items=lining_items + window_lining_items + threshold_items + casing_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Framing", + items=door_items + frame_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + if glass_items: + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Glazing", + items=glass_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + return representation + + @overload + def convert_si_to_unit(self, value: float) -> float: ... + @overload + def convert_si_to_unit(self, value: np.ndarray) -> np.ndarray: ... + def convert_si_to_unit(self, value: Union[float, np.ndarray]) -> Union[float, np.ndarray]: + si_conversion = 1 / self.settings["unit_scale"] + return value * si_conversion diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_footprint_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_footprint_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5fe9f20bc4408559e2561a47ee32a3a101debb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_footprint_representation.py @@ -0,0 +1,34 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.unit + + +def add_footprint_representation( + file, + # IfcGeometricRepresentationContext + context: ifcopenshell.entity_instance, + # A list of IFC curves to include in the curve set + curves: list[ifcopenshell.entity_instance], +) -> ifcopenshell.entity_instance: + return file.createIfcShapeRepresentation( + context, + context.ContextIdentifier, + "GeometricCurveSet", + [file.createIfcGeometricCurveSet(curves)], + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_mesh_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_mesh_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4b41a4dfddc919dc710c35bbea6203f589d1c7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_mesh_representation.py @@ -0,0 +1,132 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.unit +import numpy as np +import numpy.typing as npt +from ifcopenshell.util.shape_builder import ShapeBuilder, SequenceOfVectors, VectorType +from typing import Optional, TypeVar + +T = TypeVar("T") +COORD_3D = tuple[float, float, float] + + +def add_mesh_representation( + file: ifcopenshell.file, + context: ifcopenshell.entity_instance, + vertices: list[SequenceOfVectors], + edges: Optional[list[list[tuple[int, int]]]] = None, + # Optional faces is not supported currently. + faces: list[list[list[int]]] = None, + coordinate_offset: Optional[VectorType] = None, + unit_scale: Optional[float] = None, + force_faceted_brep: bool = False, +) -> ifcopenshell.entity_instance: + """ + Add a mesh representation. + + Vertices, edges, and faces are given in the form of: ``[item1, item2, item3, ...]``. + Each ``itemN`` is a sublist representing data for a separate IfcRepresentationItem to add. + + You can provide either ``edges`` or ``faces``, no need to provide both. + But currently ``edges`` argument is not supported. + + :param context: The IfcGeometricRepresentationContext for the representation. + :param vertices: A list of coordinates. + where ``itemN = [(0., 0., 0.), (1., 1., 1.), (x, y, z), ...]`` + :param edges: A list of edges, represented by vertex index pairs + where ``itemN = [(0, 1), (1, 2), (v1, v2), ...]`` + :param faces: A list of polygons, represented by vertex indices. + where ``itemN = [(0, 1, 2), (5, 4, 2, 3), (v1, v2, v3, ... vN), ...]`` + :param coordinate_offset: Optionally apply a vector offset to all coordinates. + In project units. + :param unit_scale: Scale factor for ``vertices`` units. + + If omitted, it is assumed that ``vertices`` are in SI units. + + If other value is provided ``vertices`` coords will be divided by ``unit_scale``. + :param force_faceted_brep: Force using IfcFacetedBreps instead of IfcPolygonalFaceSets. + :return: IfcShapeRepresentation. + """ + # TODO: Support edges without faces. + assert faces is not None, f"Currently 'faces' argument is not optional." + assert len(faces) != 0 + assert len(vertices) != 0 + assert len(faces) == len(vertices) + + usecase = Usecase() + usecase.file = file + + # Process arguments. + if unit_scale is None: + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) + np_vertices = np.array(vertices, dtype=np.float64) * (1 / unit_scale) + if coordinate_offset is not None: + np_vertices += coordinate_offset + + return usecase.execute(context, np_vertices, faces, force_faceted_brep) + + +class Usecase: + file: ifcopenshell.file + + vertices: npt.NDArray[np.float64] + """In project units.""" + + def execute( + self, + context: ifcopenshell.entity_instance, + vertices: npt.NDArray[np.float64], + faces: list[list[list[int]]], + force_faceted_brep: bool, + ) -> ifcopenshell.entity_instance: + self.builder = ShapeBuilder(self.file) + self.vertices = vertices + self.faces = faces + self.context = context + self.force_faceted_brep = force_faceted_brep + return self.create_mesh_representation() + + def create_mesh_representation(self) -> ifcopenshell.entity_instance: + if self.force_faceted_brep or self.file.schema == "IFC2X3": + return self.create_faceted_brep() + return self.create_polygonal_face_set() + + def create_faceted_brep(self) -> ifcopenshell.entity_instance: + items: list[ifcopenshell.entity_instance] = [] + for i in range(0, len(self.vertices)): + items.append(self.builder.faceted_brep(self.vertices[i], self.faces[i])) + return self.file.create_entity( + "IfcShapeRepresentation", + self.context, + self.context.ContextIdentifier, + "Brep", + items, + ) + + def create_polygonal_face_set(self) -> ifcopenshell.entity_instance: + items: list[ifcopenshell.entity_instance] = [] + for i in range(0, len(self.vertices)): + items.append(self.builder.polygonal_face_set(self.vertices[i], self.faces[i])) + return self.file.create_entity( + "IfcShapeRepresentation", + self.context, + self.context.ContextIdentifier, + "Tessellation", + items, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_profile_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_profile_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..94581310464a1804b62c9ab5523f2c6ea046d6fa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_profile_representation.py @@ -0,0 +1,223 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.geom +import ifcopenshell.util.element +import ifcopenshell.util.shape +import ifcopenshell.util.unit +from ifcopenshell.util.data import Clipping +from typing import Any, Union, Optional, Literal, get_args + +VECTOR_3D = tuple[float, float, float] +CardinalPointNumeric = Literal[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19] +CardinalPointString = Literal[ + "bottom left", + "bottom centre", + "bottom right", + "mid-depth left", + "mid-depth centre", + "mid-depth right", + "top left", + "top centre", + "top right", + "geometric centroid", + "bottom in line with the geometric centroid", + "left in line with the geometric centroid", + "right in line with the geometric centroid", + "top in line with the geometric centroid", + "shear centre", + "bottom in line with the shear centre", + "left in line with the shear centre", + "right in line with the shear centre", + "top in line with the shear centre", +] +CARDINAL_POINT_VALUES: tuple[CardinalPointString, ...] = get_args(CardinalPointString) +CardinalPoint = Union[CardinalPointNumeric, CardinalPointString] + + +def add_profile_representation( + file: ifcopenshell.file, + context: ifcopenshell.entity_instance, + profile: ifcopenshell.entity_instance, + depth: float = 1.0, + # TODO: None makes more sense as default value? + cardinal_point: Union[CardinalPoint, None] = 5, + clippings: Optional[list[Union[Clipping, dict[str, Any]]]] = None, + placement_zx_axes: tuple[Union[VECTOR_3D, None], Union[VECTOR_3D, None]] = (None, None), +) -> ifcopenshell.entity_instance: + """Add profile representation. + + :param context: The IfcGeometricRepresentationContext for the representation, + only Model/Body/MODEL_VIEW type of representations are currently supported. + :param profile: The IfcProfileDef to extrude. + :param depth: The depth of the extrusion in meters. + :param cardinal_point: The cardinal point of the profile. + :param clippings: A list of planes that define clipping half space solids. + Planes are defined either by Clipping objects + or by dictionaries of arguments for `Clipping.parse`. + :param placement_zx_axes: A tuple of two vectors that define the placement of the profile. + The first vector is the Z axis, the second vector is the X axis. + :return: IfcShapeRepresentation. + """ + usecase = Usecase() + usecase.file = file + clippings = clippings if clippings is not None else [] + return usecase.execute(context, profile, depth, cardinal_point, clippings, placement_zx_axes) + + +class Usecase: + file: ifcopenshell.file + clippings: list[Clipping] + + def execute( + self, + context: ifcopenshell.entity_instance, + profile: ifcopenshell.entity_instance, + depth: float, + cardinal_point: Union[CardinalPoint, None], + clippings: list[Union[Clipping, dict[str, Any]]], + placement_zx_axes: tuple[Union[VECTOR_3D, None], Union[VECTOR_3D, None]], + ) -> ifcopenshell.entity_instance: + if isinstance(cardinal_point, int): + cardinal_point = CARDINAL_POINT_VALUES[cardinal_point - 1] + + self.cardinal_point = cardinal_point + self.profile = profile + self.clippings = [Clipping.parse(c) for c in clippings] + self.depth = depth + self.placement_zx_axes = placement_zx_axes + self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file) + return self.file.create_entity( + "IfcShapeRepresentation", + context, + context.ContextIdentifier, + "Clipping" if self.clippings else "SweptSolid", + [self.create_item()], + ) + + def create_item(self) -> ifcopenshell.entity_instance: + point = self.get_point() + placement = self.file.createIfcAxis2Placement3D( + point, + self.file.create_entity("IfcDirection", self.placement_zx_axes[0] or (0.0, 0.0, 1.0)), + self.file.create_entity("IfcDirection", self.placement_zx_axes[1] or (1.0, 0.0, 0.0)), + ) + extrusion = self.file.create_entity( + "IfcExtrudedAreaSolid", + self.profile, + placement, + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.convert_si_to_unit(self.depth), + ) + if self.clippings: + return self.apply_clippings(extrusion) + return extrusion + + def apply_clippings(self, first_operand: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + while self.clippings: + clipping = self.clippings.pop() + if isinstance(clipping, ifcopenshell.entity_instance): + new = ifcopenshell.util.element.copy(self.file, clipping) + new.FirstOperand = first_operand + first_operand = new + else: # Clipping + first_operand = clipping.apply(self.file, first_operand, self.unit_scale) + return first_operand + + def convert_si_to_unit(self, co: float) -> float: + return co / self.unit_scale + + def get_point(self) -> ifcopenshell.entity_instance: + if not self.cardinal_point: + return self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + elif self.cardinal_point == "bottom left": + return self.file.createIfcCartesianPoint((-self.get_x() / 2, self.get_y() / 2, 0.0)) + elif self.cardinal_point == "bottom centre": + return self.file.createIfcCartesianPoint((0.0, self.get_y() / 2, 0.0)) + elif self.cardinal_point == "bottom right": + return self.file.createIfcCartesianPoint((self.get_x() / 2, self.get_y() / 2, 0.0)) + elif self.cardinal_point == "mid-depth left": + return self.file.createIfcCartesianPoint((-self.get_x() / 2, 0.0, 0.0)) + elif self.cardinal_point == "mid-depth centre": + return self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + elif self.cardinal_point == "mid-depth right": + return self.file.createIfcCartesianPoint((self.get_x() / 2, 0.0, 0.0)) + elif self.cardinal_point == "top left": + return self.file.createIfcCartesianPoint((-self.get_x() / 2, -self.get_y() / 2, 0.0)) + elif self.cardinal_point == "top centre": + return self.file.createIfcCartesianPoint((0.0, -self.get_y() / 2, 0.0)) + elif self.cardinal_point == "top right": + return self.file.createIfcCartesianPoint((self.get_x() / 2, -self.get_y() / 2, 0.0)) + # TODO other cardinal points + return self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + + def get_x(self) -> float: + if self.profile.is_a("IfcAsymmetricIShapeProfileDef"): + return self.profile.OverallWidth + elif self.profile.is_a("IfcCShapeProfileDef"): + return self.profile.Width + elif self.profile.is_a("IfcCircleProfileDef"): + return self.profile.Radius * 2 + elif self.profile.is_a("IfcEllipseProfileDef"): + return self.profile.SemiAxis1 * 2 + elif self.profile.is_a("IfcIShapeProfileDef"): + return self.profile.OverallWidth + elif self.profile.is_a("IfcLShapeProfileDef"): + return self.profile.Width + elif self.profile.is_a("IfcRectangleProfileDef"): + return self.profile.XDim + elif self.profile.is_a("IfcTShapeProfileDef"): + return self.profile.FlangeWidth + elif self.profile.is_a("IfcUShapeProfileDef"): + return self.profile.FlangeWidth + elif self.profile.is_a("IfcZShapeProfileDef"): + return (self.profile.FlangeWidth * 2) - self.profile.WebThickness + else: + settings = ifcopenshell.geom.settings() + settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS) + shape = ifcopenshell.geom.create_shape(settings, self.profile) + return self.convert_si_to_unit(ifcopenshell.util.shape.get_x(shape)) + return 0.0 + + def get_y(self) -> float: + if self.profile.is_a("IfcAsymmetricIShapeProfileDef"): + return self.profile.OverallDepth + elif self.profile.is_a("IfcCShapeProfileDef"): + return self.profile.Depth + elif self.profile.is_a("IfcCircleProfileDef"): + return self.profile.Radius * 2 + elif self.profile.is_a("IfcEllipseProfileDef"): + return self.profile.SemiAxis2 * 2 + elif self.profile.is_a("IfcIShapeProfileDef"): + return self.profile.OverallDepth + elif self.profile.is_a("IfcLShapeProfileDef"): + return self.profile.Depth + elif self.profile.is_a("IfcRectangleProfileDef"): + return self.profile.YDim + elif self.profile.is_a("IfcTShapeProfileDef"): + return self.profile.Depth + elif self.profile.is_a("IfcUShapeProfileDef"): + return self.profile.Depth + elif self.profile.is_a("IfcZShapeProfileDef"): + return self.profile.Depth + else: + settings = ifcopenshell.geom.settings() + settings.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS) + shape = ifcopenshell.geom.create_shape(settings, self.profile) + return self.convert_si_to_unit(ifcopenshell.util.shape.get_y(shape)) + return 0.0 diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_railing_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_railing_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..5f81c51fd034b3c8972d217b211e6b63ff8fcaed --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_railing_representation.py @@ -0,0 +1,403 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import ifcopenshell.util.unit +from ifcopenshell.util.shape_builder import ( + ShapeBuilder, + V, + SequenceOfVectors, + is_x, + np_angle, + np_angle_signed, + np_normalized, + np_to_3d, + np_normal, + np_intersect_line_line, + np_lerp, +) +from math import pi, cos, sin, tan, radians +from typing import Literal, Optional, Any +from typing_extensions import assert_never + + +def mm(x: float) -> float: + """mm to meters shortcut for readability""" + return x / 1000 + + +TERMINAL_TYPE = Literal[ + "180", + "TO_END_POST", + "TO_WALL", + "TO_FLOOR", + "TO_END_POST_AND_FLOOR", +] + + +def add_railing_representation( + file: ifcopenshell.file, + *, # keywords only as this API implementation is probably not final + # IfcGeometricRepresentationContext + context: ifcopenshell.entity_instance, + railing_type: Literal["WALL_MOUNTED_HANDRAIL"] = "WALL_MOUNTED_HANDRAIL", + railing_path: SequenceOfVectors, + use_manual_supports: bool = False, + support_spacing: Optional[float] = None, + railing_diameter: Optional[float] = None, + clear_width: Optional[float] = None, + terminal_type: TERMINAL_TYPE = "180", + height: Optional[float] = None, + looped_path: bool = False, + unit_scale: Optional[float] = None, +) -> ifcopenshell.entity_instance: + """ + Units are expected to be in IFC project units. + + :param context: IfcGeometricRepresentationContext for the representation. + :param railing_type: Type of the railing. Defaults to "WALL_MOUNTED_HANDRAIL". + :param railing_path: A list of points coordinates for the railing path, + coordinates are expected to be at the top of the railing, not at the center. + If not provided, default path [(0, 0, 1), (1, 0, 1), (2, 0, 1)] (in meters) will be used + :param use_manual_supports: If enabled, supports are added on every vertex on the edges of the railing path. + If disabled, supports are added automatically based on the support spacing. Default to False. + :param support_spacing: Distance between supports if automatic supports are used. Defaults to 1m. + :param railing_diameter: Railing diameter. Defaults to 50mm. + :param clear_width: Clear width between the railing and the wall. Defaults to 40mm. + :param terminal_type: type of the cap. Defaults to "180". + :param height: defaults to 1m + :param looped_path: Whether to end the railing on the first point of `railing_path`. Defaults to False. + :param unit_scale: The unit scale as calculated by + ifcopenshell.util.unit.calculate_unit_scale. If not provided, it + will be automatically calculated for you. + :return: IfcShapeRepresentation for a railing. + """ + usecase = Usecase() + usecase.file = file + # define unit_scale first as it's going to be used setting default arguments + settings: dict[str, Any] = { + "unit_scale": ifcopenshell.util.unit.calculate_unit_scale(file) if unit_scale is None else unit_scale, + } + settings.update( + { + "context": context, + "railing_type": railing_path, + "railing_path": ( + railing_path + if railing_path is not None + else usecase.path_si_to_units(V([(0, 0, 1), (1, 0, 1), (2, 0, 1)])) + ), + "use_manual_supports": use_manual_supports, + "support_spacing": support_spacing if support_spacing is not None else usecase.convert_si_to_unit(mm(1000)), + "railing_diameter": ( + railing_diameter if railing_diameter is not None else usecase.convert_si_to_unit(mm(50)) + ), + "clear_width": clear_width if clear_width is not None else usecase.convert_si_to_unit(mm(40)), + "terminal_type": terminal_type, + "height": height if height is not None else usecase.convert_si_to_unit(mm(1000)), + "looped_path": looped_path, + } + ) + usecase.settings = settings + + if railing_type != "WALL_MOUNTED_HANDRAIL": + raise Exception('Only "WALL_MOUNTED_HANDRAIL" railing_type is supported at the moment.') + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + arc_points: list[np.ndarray] = [] + items_3d: list[ifcopenshell.entity_instance] = [] + builder = ShapeBuilder(self.file) + z_down = V(0, 0, -1) + + # measurements + # from settings + use_manual_supports: bool = self.settings["use_manual_supports"] + railing_radius: float = self.settings["railing_diameter"] / 2 + support_spacing: float = self.settings["support_spacing"] + clear_width: float = self.settings["clear_width"] + # for calculations purposes we use height without railing radius + height: float = self.settings["height"] - railing_radius + cap_type: TERMINAL_TYPE = self.settings["terminal_type"] + ifc_context: ifcopenshell.entity_instance = self.settings["context"] + railing_coords: SequenceOfVectors = self.settings["railing_path"] + looped_path: bool = self.settings["looped_path"] + railing_coords: np.ndarray + railing_coords = np.subtract(railing_coords, z_down * railing_radius) + + # constant + terminal_radius = self.convert_si_to_unit(mm(150)) + railing_fillet_radius = self.convert_si_to_unit(mm(100)) + support_length = clear_width + railing_radius + support_radius = self.convert_si_to_unit(mm(10)) + support_disk_radius = railing_radius + support_disk_depth = self.convert_si_to_unit(mm(20)) + + # util functions + def collinear(d0: np.ndarray, d1: np.ndarray) -> bool: + return is_x(np_angle(d0, d1), 0) + + np_Z = 2 + np_XY = slice(2) + np_YX = [1, 0] + + def add_support_on_point( + point: np.ndarray, railing_direction: np.ndarray + ) -> tuple[ifcopenshell.entity_instance, ...]: + """create a support arc and a disk based on the position and direction of the railing""" + ortho_dir = railing_direction[np_YX] * (1, -1) + ortho_dir = np_normalized(np_to_3d(ortho_dir)) + arc_center = point + ortho_dir * support_length + support_points: list[np.ndarray] = [ + point, + arc_center - ortho_dir * support_length * cos(pi / 4) + z_down * support_length * sin(pi / 4), + arc_center + z_down * support_length, + ] + polyline = builder.polyline(support_points, closed=False, arc_points=(1,)) + solid = builder.create_swept_disk_solid(polyline, support_radius) + + support_disk_circle = builder.circle(radius=support_disk_radius) + + angle = np_angle_signed((0, 1), ortho_dir[np_XY]) + y_extrusion_kwargs = builder.rotate_extrusion_kwargs_by_z(builder.extrude_kwargs("Y"), angle) + support_disk = builder.extrude( + support_disk_circle, support_disk_depth, position=support_points[-1], **y_extrusion_kwargs + ) + return (solid, support_disk) + + def get_fillet_points(v0: np.ndarray, v1: np.ndarray, v2: np.ndarray, radius: float) -> list[np.ndarray]: + """get fillet points between edges v0v1 and v1v2""" + dir1 = np_normalized(v0 - v1) + dir2 = np_normalized(v2 - v1) + edge_angle = np_angle(dir1, dir2) + slide_distance = radius / tan(edge_angle / 2) + + fillet_v1co = v1 + (dir1 * slide_distance) + fillet_v2co = v1 + (dir2 * slide_distance) + + normal = np_normal([v0, v1, v2]) + center = np_intersect_line_line( + fillet_v1co, + fillet_v1co + np.cross(normal, dir1), + fillet_v2co, + fillet_v2co + np.cross(normal, dir2), + )[0] + + dir_ = np_normalized(np_lerp(fillet_v1co, fillet_v2co, 0.5) - center) + midpointco = center + dir_ * radius + return [fillet_v1co, midpointco, fillet_v2co] + + def add_arcs_on_turnings_points(base_points: np.ndarray) -> np.ndarray: + """add 3 point fillet arcs on turning points of the railing path""" + if len(base_points) < 3: + return base_points + + # looking for turning points by checking non-collinear edges + output_points: list[np.ndarray] = list(base_points[:1]) + prev_dir = np_normalized(base_points[1] - base_points[0]) + i = 1 + while i < len(base_points) - 1: + cur_dir = np_normalized(base_points[i + 1] - base_points[i]) + + if collinear(cur_dir, prev_dir): + output_points.append(base_points[i]) + else: + fillet_points = get_fillet_points( + base_points[i - 1], base_points[i], base_points[i + 1], railing_fillet_radius + ) + output_points.extend(fillet_points) + arc_points.append(fillet_points[1]) + + prev_dir = cur_dir + i = i + 1 + + if looped_path: + output_points[0] = output_points[-1] + else: + output_points.append(base_points[-1]) + return V(output_points) + + def create_supports_items( + railing_coords: np.ndarray, manual_supports: bool = False + ) -> list[ifcopenshell.entity_instance]: + """create supports items based on the railing coordinates""" + supports_items: list[ifcopenshell.entity_instance] = [] + + # simplified_coords is a list of points that form non-collinear edges + simplified_coords: list[np.ndarray] = [railing_coords[0]] + prev_dir = np_normalized(railing_coords[1] - railing_coords[0]) + + # iterating over each edge of the railing path + for i in range(1, len(railing_coords) - 1): + cur_dir = np_normalized(railing_coords[i + 1] - railing_coords[i]) + + if not collinear(cur_dir, prev_dir): + simplified_coords.append(railing_coords[i]) + prev_dir = cur_dir + + # for manual supports each vertex on the railing path edge + # will be a point for a support + elif manual_supports: + supports_items.extend(add_support_on_point(point=railing_coords[i], railing_direction=cur_dir)) + + simplified_coords.append(railing_coords[-1]) + + if manual_supports: + return supports_items + + # create automatic supports based on the support spacing + for i in range(0, len(simplified_coords) - 1): + v0, v1 = simplified_coords[i : i + 2] + edge = v1 - v0 + length: float = np.linalg.norm(edge) + edge_dir = np_normalized(edge) + n_supports, support_offset = divmod(length, support_spacing) + n_supports = int(n_supports) + 1 + support_offset /= 2 + + start_position = v0 + support_offset * edge_dir + for support_i in range(n_supports): + support_position = start_position + support_i * support_spacing * edge_dir + supports_items.extend(add_support_on_point(point=support_position, railing_direction=edge)) + + return supports_items + + def add_cap(railing_coords: np.ndarray, arc_points: list[np.ndarray], start: bool = False): + """add handrail terminal cap""" + railing_coords_for_cap = railing_coords[::-1] if start else railing_coords + arc_points = arc_points[::-1] if start else arc_points + + start_point: np.ndarray = railing_coords_for_cap[-1] + cap_dir = railing_coords_for_cap[-1] - railing_coords_for_cap[-2] + cap_dir = np_normalized(cap_dir) + ortho_dir = np_to_3d(cap_dir[np_YX] * (1, -1)) + ortho_dir = np_normalized(ortho_dir) + local_z_down = np.cross(cap_dir, ortho_dir) + if start: + ortho_dir = -ortho_dir + + arc_middle_point_cos = sin(radians(45)) + + if cap_type in ("180", "TO_END_POST"): + arc_point = start_point + cap_dir * terminal_radius + terminal_radius * local_z_down + arc_points.append(arc_point) + cap_coords = [arc_point, start_point + terminal_radius * 2 * local_z_down] + + if cap_type == "TO_END_POST": + end_point = railing_coords_for_cap[-2].copy() + end_point[np_Z] -= terminal_radius * 2 + cap_coords.append(end_point) + + elif cap_type == "TO_WALL": + arc_point = ( + start_point + + cap_dir * clear_width * arc_middle_point_cos + + ortho_dir * clear_width * (1 - arc_middle_point_cos) + ) + arc_points.append(arc_point) + cap_coords = [arc_point, start_point + ortho_dir * clear_width + cap_dir * clear_width] + + elif cap_type == "TO_FLOOR": + arc_point = ( + start_point + + cap_dir * terminal_radius * arc_middle_point_cos + + z_down * terminal_radius * (1 - arc_middle_point_cos) + ) + arc_points.append(arc_point) + arc_end = start_point + cap_dir * terminal_radius + terminal_radius * z_down + cap_coords = [ + arc_point, + arc_end, + arc_end + z_down * (height - terminal_radius), + ] + + elif cap_type == "TO_END_POST_AND_FLOOR": + first_arc_end = start_point + cap_dir * terminal_radius + terminal_radius * local_z_down + first_arc_coords = get_fillet_points( + start_point, start_point + cap_dir * terminal_radius, first_arc_end, terminal_radius + ) + arc_points.append(first_arc_coords[1]) + + end_point = railing_coords_for_cap[-2].copy() + end_point[np_Z] -= height + second_arc_coords = get_fillet_points( + first_arc_end, first_arc_end + local_z_down * terminal_radius, end_point, terminal_radius + ) + arc_points.append(second_arc_coords[1]) + cap_coords = [start_point] + first_arc_coords + second_arc_coords + [end_point] + else: + assert_never(cap_type) + + railing_coords = np.vstack((railing_coords_for_cap, cap_coords)) + + if start: + railing_coords = railing_coords[::-1] + arc_points = arc_points[::-1] + return railing_coords, arc_points + + # need to add first two points to the path + # to create the turning arcs and supports on the last segment of the loop + if looped_path: + railing_coords = np.vstack((railing_coords, railing_coords[:2])) + + items_3d.extend(create_supports_items(railing_coords, manual_supports=use_manual_supports)) + railing_coords = add_arcs_on_turnings_points(railing_coords) + + if not looped_path and cap_type != "NONE": + railing_coords, arc_points = add_cap(railing_coords, arc_points, start=True) + railing_coords, arc_points = add_cap(railing_coords, arc_points, start=False) + + def get_arc_indices(points: np.ndarray, arc_points: list[np.ndarray]) -> list[int]: + points_ = points.copy() + arc_indices = [] + i_base = 0 + for arc_point in arc_points: + for i, point in enumerate(points_): + if np.allclose(arc_point, point): + current_index = i + i_base + arc_indices.append(current_index) + i_base = current_index + 1 + break + else: + raise Exception( + f"Arc point '{arc_point}' is not present in points:\n{points_}\nFull points data:\n{points}" + ) + points_ = points_[i + 1 :] + return arc_indices + + railing_path = builder.polyline( + railing_coords, + closed=False, + arc_points=get_arc_indices(railing_coords, arc_points), + ) + railing_solid = builder.create_swept_disk_solid(railing_path, railing_radius) + items_3d.append(railing_solid) + representation = builder.get_representation(ifc_context, items=items_3d) + return representation + + def convert_si_to_unit(self, value: float) -> float: + return value / self.settings["unit_scale"] + + def path_si_to_units(self, path: np.ndarray) -> np.ndarray: + """converts list of vectors from SI to ifc project units""" + return path / self.settings["unit_scale"] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3a9881a7b8173bb8a7321e0f24a1321f98e7c9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_representation.py @@ -0,0 +1,1028 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +from __future__ import annotations +import bpy.types +import math +import bmesh +import ifcopenshell.util.shape_builder +import ifcopenshell.util.unit +import numpy as np +import numpy.typing as npt +from mathutils import Vector, Matrix +from typing import Union, Optional, Literal, Any, TYPE_CHECKING +from ifcopenshell.util.shape_builder import ifc_safe_vector_type, VectorType + +if TYPE_CHECKING: + import bonsai.tool as tool + from bonsai.bim.module.geometry.helper import Helper + + +Z_AXIS = Vector((0, 0, 1)) +X_AXIS = Vector((1, 0, 0)) +EPSILON = 1e-6 + + +def add_representation( + file: ifcopenshell.file, + *, # keywords only as this API implementation is probably not final + context: ifcopenshell.entity_instance, + blender_object: bpy.types.Object, + geometry: Union[bpy.types.Mesh, bpy.types.Curve], + coordinate_offset: Optional[npt.NDArray[np.float64]] = None, + total_items: int = 1, + unit_scale: Optional[float] = None, + should_force_faceted_brep: bool = False, + should_force_triangulation: bool = False, + should_generate_uvs: bool = False, + ifc_representation_class: Optional[ + Literal[ + "IfcExtrudedAreaSolid/IfcRectangleProfileDef", + "IfcExtrudedAreaSolid/IfcCircleProfileDef", + "IfcExtrudedAreaSolid/IfcArbitraryClosedProfileDef", + "IfcExtrudedAreaSolid/IfcArbitraryProfileDefWithVoids", + "IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage", + "IfcGeometricCurveSet/IfcTextLiteral", + "IfcTextLiteral", + ] + ] = None, + profile_set_usage: Optional[ifcopenshell.entity_instance] = None, + text_literal: Optional[ifcopenshell.entity_instance] = None, +) -> Union[ifcopenshell.entity_instance, None]: + """Add an IfcShapeRepresentation. + + :param context: The IfcGeometricRepresentationContext. + :param blender_object: This is (currently) a Blender object, hence this depends on Blender now. + :param geometry: This is (currently) a Blender data object, hence this depends on Blender now. + :param coordinate_offset: Optionally apply a vector offset to all coordinates (in SI units). + :param total_items: How many representation items to create. + :param unit_scale: A scale factor to apply for all vectors in case the unit is different. + :param should_force_faceted_brep: If we should force faceted breps for meshes. + :param should_force_triangulation: If we should force triangulation for meshes. + :param should_generate_uvs: If UV coordinates should also be generated. + :param ifc_representation_class: Whether to cast a mesh into a particular class + :param profile_set_usage: The material profile set if the extrusion requires it + :param text_literal: The text literal if the representation requires it + :return: IfcShapeRepresentation or None if couldn't create representation + for the provided context. + """ + # lazy import Helper to avoid circular import + if "Helper" not in globals(): + import bonsai.tool as tool + from bonsai.bim.module.geometry.helper import Helper + + globals()["Helper"] = Helper + globals()["tool"] = tool + + usecase = Usecase() + # TODO: This usecase currently depends on Blender's data model + usecase.file = file + usecase.settings = { + "context": context, + "blender_object": blender_object, + "geometry": geometry, + "coordinate_offset": coordinate_offset if coordinate_offset is not None else None, + "total_items": total_items, + "unit_scale": unit_scale, + "should_force_faceted_brep": should_force_faceted_brep, + "should_force_triangulation": should_force_triangulation, + "should_generate_uvs": should_generate_uvs, + "ifc_representation_class": ifc_representation_class, + "profile_set_usage": profile_set_usage, + "text_literal": text_literal, + } + usecase.ifc_vertices = [] + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + ifc_vertices: list[ifcopenshell.entity_instance] + coordinate_offset: Union[npt.NDArray[np.float64], None] + geometry: Union[bpy.types.Mesh, bpy.types.Curve, bpy.types.Camera] + blender_object: bpy.types.Object + + def execute(self) -> Union[ifcopenshell.entity_instance, None]: + self.is_manifold = None + self.coordinate_offset = self.settings["coordinate_offset"] + self.geometry = self.settings["geometry"] + self.blender_object = self.settings["blender_object"] + + if isinstance(self.geometry, bpy.types.Mesh) and self.geometry == self.blender_object.data: + self.evaluate_geometry() + if self.settings["unit_scale"] is None: + self.settings["unit_scale"] = ifcopenshell.util.unit.calculate_unit_scale(self.file) + if self.settings["context"].ContextType == "Model": + return self.create_model_representation() + elif self.settings["context"].ContextType == "Plan": + return self.create_plan_representation() + return self.create_variable_representation() + + def should_triangulate_face(self, face: bmesh.types.BMFace, threshold: float = EPSILON) -> bool: + vz = face.normal + co = face.verts[0].co + if vz.length < 0.5: + return True + if abs(vz.z) < 0.5: + vx = vz.cross(Z_AXIS) + else: + vx = vz.cross(X_AXIS) + vy = vx.cross(vz) + assert isinstance(vy, Vector) + tM = Matrix( + [[vx.x, vy.x, vz.x, co.x], [vx.y, vy.y, vz.y, co.y], [vx.z, vy.z, vz.z, co.z], [0, 0, 0, 1]] + ).inverted() + + return any([abs((tM @ v.co).z) > threshold for v in face.verts]) + + def evaluate_geometry(self) -> None: + for modifier in self.blender_object.modifiers: + if modifier.type == "BOOLEAN": + modifier.show_viewport = False + + mesh = self.blender_object.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh() + bm = bmesh.new() + bm.from_mesh(mesh) + + self.is_manifold = True + for edge in bm.edges: + if not edge.is_manifold: + self.is_manifold = False + break + + if self.settings["should_force_triangulation"]: + faces = bm.faces + else: + faces = [f for f in bm.faces if self.should_triangulate_face(f)] + bmesh.ops.triangulate(bm, faces=faces) + bm.to_mesh(mesh) + mesh.update() + bm.free() + del bm + + self.settings["geometry"] = mesh + + for modifier in self.blender_object.modifiers: + if modifier.type == "BOOLEAN": + modifier.show_viewport = True + + def create_model_representation(self) -> Union[ifcopenshell.entity_instance, None]: + if self.settings["context"].is_a() == "IfcGeometricRepresentationContext": + return self.create_variable_representation() + elif self.settings["ifc_representation_class"] == "IfcTextLiteral": + return self.create_text_representation(is_2d=False) + elif self.settings["ifc_representation_class"] == "IfcGeometricCurveSet/IfcTextLiteral": + shape_representation = self.create_geometric_curve_set_representation(is_2d=True) + shape_representation.RepresentationType = "Annotation3D" + items = list(shape_representation.Items) + items.append(self.create_text()) + shape_representation.Items = items + return shape_representation + elif self.settings["context"].ContextIdentifier == "Annotation": + return self.create_annotation3d_representation() + elif self.settings["context"].ContextIdentifier == "Axis": + return self.create_curve3d_representation() + elif self.settings["context"].ContextIdentifier == "Body": + return self.create_variable_representation() + elif self.settings["context"].ContextIdentifier == "Box": + return self.create_box_representation() + elif self.settings["context"].ContextIdentifier == "Clearance": + return self.create_variable_representation() + elif self.settings["context"].ContextIdentifier == "CoG": + return self.create_cog_representation() + elif self.settings["context"].ContextIdentifier == "FootPrint": + return self.create_variable_representation() + elif self.settings["context"].ContextIdentifier == "Reference": + if self.settings["context"].TargetView == "GRAPH_VIEW": + return self.create_structural_reference_representation() + return self.create_variable_representation() + elif self.settings["context"].ContextIdentifier == "Profile": + return self.create_curve3d_representation() + elif self.settings["context"].ContextIdentifier == "SurveyPoints": + return self.create_geometric_curve_set_representation() + elif self.settings["context"].ContextIdentifier == "Lighting": + return self.create_lighting_representation() + + def create_plan_representation(self) -> Union[ifcopenshell.entity_instance, None]: + if self.settings["ifc_representation_class"] == "IfcTextLiteral": + return self.create_text_representation(is_2d=True) + elif self.settings["ifc_representation_class"] == "IfcGeometricCurveSet/IfcTextLiteral": + shape_representation = self.create_geometric_curve_set_representation(is_2d=True) + shape_representation.RepresentationType = "Annotation2D" + items = list(shape_representation.Items) + items.append(self.create_text()) + shape_representation.Items = items + return shape_representation + elif self.settings["context"].ContextIdentifier == "Annotation": + return self.create_annotation2d_representation() + elif self.settings["context"].ContextIdentifier == "Axis": + return self.create_curve2d_representation() + elif self.settings["context"].ContextIdentifier == "Body": + return self.create_annotation2d_representation() + elif self.settings["context"].ContextIdentifier == "Box": + pass + elif self.settings["context"].ContextIdentifier == "Clearance": + pass + elif self.settings["context"].ContextIdentifier == "CoG": + pass + elif self.settings["context"].ContextIdentifier == "FootPrint": + if self.settings["context"].TargetView in ["SKETCH_VIEW", "PLAN_VIEW", "REFLECTED_PLAN_VIEW"]: + return self.create_geometric_curve_set_representation(is_2d=True) + elif self.settings["context"].ContextIdentifier == "Reference": + pass + elif self.settings["context"].ContextIdentifier == "Profile": + pass + elif self.settings["context"].ContextIdentifier == "SurveyPoints": + pass + else: + return self.create_annotation2d_representation() + + def create_lighting_representation(self) -> ifcopenshell.entity_instance: + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "LightSource", + [self.create_light_source()], + ) + + def create_light_source(self) -> Union[ifcopenshell.entity_instance, None]: + if self.settings["geometry"].type == "POINT": + return self.create_light_source_positional() + + def create_light_source_positional(self) -> ifcopenshell.entity_instance: + return self.file.create_entity( + "IfcLightSourcePositional", + **{ + "LightColour": self.file.createIfcColourRgb(None, *self.settings["geometry"].color), + "Position": self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)), + "Radius": self.convert_si_to_unit(self.settings["geometry"].shadow_soft_size), + }, + ) + + def create_text_representation(self, is_2d: bool = False) -> ifcopenshell.entity_instance: + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Annotation2D" if is_2d else "Annotation3D", + [self.create_text()], + ) + + def create_text(self) -> ifcopenshell.entity_instance: + if self.settings["text_literal"]: + return self.settings["text_literal"] + origin = self.file.createIfcAxis2Placement3D( + self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)), + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.file.createIfcDirection((1.0, 0.0, 0.0)), + ) + + # TODO: Planar extent right now is wrong ... + return self.file.createIfcTextLiteralWithExtent( + "TEXT", origin, "RIGHT", self.file.createIfcPlanarExtent(1000, 1000), "bottom-left" + ) + + def create_variable_representation(self) -> Union[ifcopenshell.entity_instance, None]: + if isinstance(self.settings["geometry"], bpy.types.Curve) and self.settings["geometry"].bevel_depth: + return self.create_swept_disk_solid_representation() + elif isinstance(self.settings["geometry"], bpy.types.Curve): + return self.create_curve3d_representation() + elif isinstance(self.geometry, bpy.types.Camera): + if self.geometry.type == "ORTHO": + return self.create_camera_block_representation() + elif self.geometry.type == "PERSP": + return self.create_camera_pyramid_representation() + else: + raise ValueError(f"Unsupported camera type: '{self.geometry.type}'.") + elif not len(self.settings["geometry"].edges): + return self.create_point_cloud_representation() + elif not len(self.settings["geometry"].polygons): + return self.create_curve3d_representation() + elif self.settings["ifc_representation_class"] == "IfcExtrudedAreaSolid/IfcRectangleProfileDef": + return self.create_rectangle_extrusion_representation() + elif self.settings["ifc_representation_class"] == "IfcExtrudedAreaSolid/IfcCircleProfileDef": + return self.create_circle_extrusion_representation() + elif self.settings["ifc_representation_class"] == "IfcExtrudedAreaSolid/IfcArbitraryClosedProfileDef": + return self.create_arbitrary_extrusion_representation() + elif self.settings["ifc_representation_class"] == "IfcExtrudedAreaSolid/IfcArbitraryProfileDefWithVoids": + return self.create_arbitrary_void_extrusion_representation() + elif self.settings["ifc_representation_class"] == "IfcExtrudedAreaSolid/IfcMaterialProfileSetUsage": + return self.create_material_profile_set_extrusion_representation() + return self.create_mesh_representation() + + def create_camera_block_representation(self) -> ifcopenshell.entity_instance: + assert isinstance(self.geometry, bpy.types.Camera) + props = tool.Drawing.get_camera_props(self.geometry) + raster_x = props.raster_x + raster_y = props.raster_y + + if self.is_camera_landscape(): + width = self.settings["geometry"].ortho_scale + height = width / raster_x * raster_y + else: + height = self.settings["geometry"].ortho_scale + width = height / raster_y * raster_x + + block = self.file.create_entity( + "IfcBlock", + Position=self.file.createIfcAxis2Placement3D( + self.create_cartesian_point(-width / 2, -height / 2, -self.settings["geometry"].clip_end) + ), + XLength=self.convert_si_to_unit(width), + YLength=self.convert_si_to_unit(height), + ZLength=self.convert_si_to_unit(self.settings["geometry"].clip_end), + ) + + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "CSG", + [self.file.createIfcCsgSolid(block)], + ) + + def create_camera_pyramid_representation(self) -> ifcopenshell.entity_instance: + assert isinstance(self.geometry, bpy.types.Camera) + props = tool.Drawing.get_camera_props(self.geometry) + raster_x = props.raster_x + raster_y = props.raster_y + fov = self.settings["geometry"].angle + + clip_end = self.settings["geometry"].clip_end + clip_start = self.settings["geometry"].clip_start + + if self.is_camera_landscape(): + half_width = math.tan(fov / 2) * clip_end + half_height = half_width * raster_y / raster_x + else: + half_height = math.tan(fov / 2) * clip_end + half_width = half_height * raster_x / raster_y + + x_length = 2 * half_width + y_length = 2 * half_height + + pyramid = self.file.create_entity( + "IfcRectangularPyramid", + Position=self.file.createIfcAxis2Placement3D( + self.create_cartesian_point(-x_length / 2, -y_length / 2, -clip_end) + ), + XLength=self.convert_si_to_unit(x_length), + YLength=self.convert_si_to_unit(y_length), + Height=self.convert_si_to_unit(clip_end), + ) + + surface = self.file.createIfcPlane( + self.file.createIfcAxis2Placement3D(self.create_cartesian_point(0, 0, -clip_start)) + ) + half_space = self.file.createIfcHalfSpaceSolid(surface, False) + + clipping_result = self.file.create_entity("IfcBooleanResult", "DIFFERENCE", pyramid, half_space) + + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "CSG", + [self.file.createIfcCsgSolid(clipping_result)], + ) + + def is_camera_landscape(self) -> bool: + assert isinstance(self.geometry, bpy.types.Camera) + props = tool.Drawing.get_camera_props(self.geometry) + return props.raster_x > props.raster_y + + def create_swept_disk_solid_representation(self) -> ifcopenshell.entity_instance: + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "AdvancedSweptSolid", + self.create_swept_disk_solids(), + ) + + def create_curve3d_representation(self) -> Union[ifcopenshell.entity_instance, None]: + if curves := self.create_curves(): + return self.file.createIfcShapeRepresentation( + self.settings["context"], self.settings["context"].ContextIdentifier, "Curve3D", curves + ) + + def create_curve2d_representation(self) -> ifcopenshell.entity_instance: + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Curve2D", + self.create_curves(is_2d=True), + ) + + def create_curve_bounded_planes(self, is_2d: bool = False) -> list[ifcopenshell.entity_instance]: + items = [] + if self.file.schema != "IFC2X3": + points = self.create_cartesian_point_list_from_vertices(self.settings["geometry"].vertices, is_2d=False) + for polygon in self.settings["geometry"].polygons: + plane = self.create_plane(polygon) + if self.file.schema == "IFC2X3": + curve = self.create_curve_from_polygon_ifc2x3(polygon, is_2d=False) + else: + curve = self.create_curve_from_polygon(points, polygon, is_2d=False) + items.append(self.file.createIfcCurveBoundedPlane(BasisSurface=plane, OuterBoundary=curve)) + return items + + def create_plane(self, polygon: bpy.types.MeshPolygon) -> ifcopenshell.entity_instance: + return self.file.createIfcPlane( + Position=self.file.createIfcAxis2Placement3D( + Location=self.file.createIfcCartesianPoint(polygon.center), + Axis=self.file.createIfcDirection(polygon.normal), + ) + ) + + def create_annotation_fill_areas(self, is_2d: bool = False) -> list[ifcopenshell.entity_instance]: + items = [] + if self.file.schema != "IFC2X3": + points = self.create_cartesian_point_list_from_vertices(self.settings["geometry"].vertices, is_2d=is_2d) + for polygon in self.settings["geometry"].polygons: + if self.file.schema == "IFC2X3": + curve = self.create_curve_from_polygon_ifc2x3(polygon, is_2d=is_2d) + else: + curve = self.create_curve_from_polygon(points, polygon, is_2d=is_2d) + items.append(self.file.createIfcAnnotationFillArea(OuterBoundary=curve)) + return items + + def create_curve_from_polygon( + self, points: ifcopenshell.entity_instance, polygon: bpy.types.MeshPolygon, is_2d: bool = False + ) -> ifcopenshell.entity_instance: + indices = list(polygon.vertices) + indices.append(indices[0]) + edge_loop = [self.file.createIfcLineIndex((v1 + 1, v2 + 1)) for v1, v2 in zip(indices, indices[1:])] + return self.file.createIfcIndexedPolyCurve(points, edge_loop) + + def create_curve_from_polygon_ifc2x3( + self, polygon: bpy.types.MeshPolygon, is_2d: bool = False + ) -> ifcopenshell.entity_instance: + indices = list(polygon.vertices) + indices.append(indices[0]) + points = [ + self.create_cartesian_point(v.co.x, v.co.y, v.co.z if not is_2d else None) + for v in self.settings["geometry"].vertices + ] + return self.file.createIfcPolyline([points[i] for i in indices]) + + def create_swept_disk_solids(self) -> list[ifcopenshell.entity_instance]: + curves = self.create_curves() + results = [] + radius = self.convert_si_to_unit(round(self.settings["geometry"].bevel_depth, 3)) + for curve in curves: + results.append(self.file.createIfcSweptDiskSolid(curve, radius)) + return results + + def is_mesh_curve_consecutive(self, geom_data: bpy.types.Mesh) -> bool: + import bonsai.tool as tool + + bm = tool.Blender.get_bmesh_for_mesh(geom_data) + bm.verts.ensure_lookup_table() + start_vert = bm.verts[0] + n_verts = len(bm.verts) + cur_edges = bm.verts[0].link_edges + + if len(cur_edges) > 2: + return False + elif cur_edges == 2: + edge0, edge1 = cur_edges + else: + edge0, edge1 = cur_edges[0], None + + processed_verts = set() + processed_verts.add(start_vert) + + def validate_edge(edge, start_vert, processed_verts): + cur_vert = edge.other_vert(start_vert) + while True: + if cur_vert == start_vert: + break + if cur_vert in processed_verts: + return + processed_verts.add(cur_vert) + edges = cur_vert.link_edges + if len(edges) > 2: + return + elif len(edges) == 1: + return True + edge = next(e for e in edges if e != edge) + cur_vert = edge.other_vert(cur_vert) + return True + + if not validate_edge(edge0, start_vert, processed_verts): + return False + + if edge1 and not validate_edge(edge1, start_vert, processed_verts): + return False + + if len(processed_verts) != n_verts: + return False + return True + + def create_curves( + self, should_exclude_faces: bool = False, is_2d: bool = False, ignore_non_loose_edges: bool = False + ) -> list[ifcopenshell.entity_instance]: + geom_data = self.settings["geometry"] + + if isinstance(geom_data, bpy.types.Mesh): + if self.is_mesh_curve_consecutive(geom_data): + if self.file.schema == "IFC2X3": + return self.create_curves_from_mesh_ifc2x3(should_exclude_faces=should_exclude_faces, is_2d=is_2d) + return self.create_curves_from_mesh(should_exclude_faces=should_exclude_faces, is_2d=is_2d) + + import bonsai.tool as tool + + selected_objects = bpy.context.selected_objects + active_object = bpy.context.active_object + + # create dummy object that will have more detailed curves + # since now we do not really support splines curves natively + obj = self.blender_object + dummy = bpy.data.objects.new("Dummy", obj.data.copy()) + bpy.context.scene.collection.objects.link(dummy) + tool.Blender.select_and_activate_single_object(bpy.context, dummy) + if not isinstance(geom_data, bpy.types.Mesh): + bpy.ops.object.convert(target="MESH") + self.remove_doubles_from_mesh(dummy.data) + bpy.ops.object.convert(target="CURVE") + + if self.file.schema == "IFC2X3": + curves = self.create_curves_from_curve_ifc2x3(is_2d=is_2d, curve_object_data=dummy.data) + else: + curves = self.create_curves_from_curve(is_2d=is_2d, curve_object_data=dummy.data) + + # restore objects selection + bpy.data.objects.remove(dummy) + tool.Blender.set_objects_selection(bpy.context, active_object, selected_objects) + return curves + + def create_curves_from_mesh( + self, should_exclude_faces: bool = False, is_2d: bool = False + ) -> list[ifcopenshell.entity_instance]: + geom_data = self.settings["geometry"].copy() + self.remove_doubles_from_mesh(geom_data) + curves = [] + points = self.create_cartesian_point_list_from_vertices(geom_data.vertices, is_2d=is_2d) + edge_loops = [] + previous_edge = None + edge_loop = [] + face_edges = set() + if should_exclude_faces: + [face_edges.union([geom_data.edge_keys.index(ek) for ek in p.edge_keys]) for p in geom_data.polygons] + for i, edge in enumerate(geom_data.edges): + if should_exclude_faces and i in face_edges: + continue + elif previous_edge is None: + edge_loop = [self.file.createIfcLineIndex((edge.vertices[0] + 1, edge.vertices[1] + 1))] + elif edge.vertices[0] == previous_edge.vertices[1]: + edge_loop.append(self.file.createIfcLineIndex((edge.vertices[0] + 1, edge.vertices[1] + 1))) + else: + edge_loops.append(edge_loop) + edge_loop = [self.file.createIfcLineIndex((edge.vertices[0] + 1, edge.vertices[1] + 1))] + previous_edge = edge + edge_loops.append(edge_loop) + for edge_loop in edge_loops: + curves.append(self.file.createIfcIndexedPolyCurve(points, edge_loop)) + return curves + + def remove_doubles_from_mesh(self, mesh: bpy.types.Mesh) -> None: + import bonsai.tool as tool + + bm = tool.Blender.get_bmesh_for_mesh(mesh) + bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=0.0001) + tool.Blender.apply_bmesh(mesh, bm) + + def create_curves_from_mesh_ifc2x3( + self, should_exclude_faces=False, is_2d=False + ) -> list[ifcopenshell.entity_instance]: + geom_data = self.settings["geometry"].copy() + self.remove_doubles_from_mesh(geom_data) + curves = [] + points = [ + self.create_cartesian_point(v.co.x, v.co.y, v.co.z if not is_2d else None) for v in geom_data.vertices + ] + coord_list = [p.Coordinates for p in points] + edge_loops = [] + previous_edge = None + edge_loop = [] + face_edges = set() + if should_exclude_faces: + [face_edges.union([geom_data.edge_keys.index(ek) for ek in p.edge_keys]) for p in geom_data.polygons] + for i, edge in enumerate(geom_data.edges): + if should_exclude_faces and i in face_edges: + continue + elif previous_edge is None: + edge_loop = [edge.vertices] + elif edge.vertices[0] == previous_edge.vertices[1]: + edge_loop.append(edge.vertices) + else: + edge_loops.append(edge_loop) + edge_loop = [edge.vertices] + previous_edge = edge + edge_loops.append(edge_loop) + for edge_loop in edge_loops: + loop_points = [points[p[0]] for p in edge_loop] + loop_points.append(points[edge_loop[-1][1]]) + curves.append(self.file.createIfcPolyline(loop_points)) + return curves + + def create_curves_from_curve_ifc2x3( + self, is_2d: bool = False, curve_object_data: Optional[bpy.types.Curve] = None + ) -> list[ifcopenshell.entity_instance]: + # TODO: support interpolated curves, not just polylines + if not curve_object_data: + curve_object_data = self.settings["geometry"] + dim = (lambda v: v.xy) if is_2d else (lambda v: v.xyz) + results = [] + for spline in curve_object_data.splines: + points = self.get_spline_points(spline) + ifc_points = [self.create_cartesian_point(*dim(point.co)) for point in points] + results.append(self.file.createIfcPolyline(ifc_points)) + return results + + def create_curves_from_curve( + self, is_2d: bool = False, curve_object_data: Optional[bpy.types.Curve] = None + ) -> list[ifcopenshell.entity_instance]: + # TODO: support interpolated curves, not just polylines + if not curve_object_data: + curve_object_data = self.settings["geometry"] + dim = (lambda v: v.xy) if is_2d else (lambda v: v.xyz) + to_units = lambda v: Vector([self.convert_si_to_unit(i) for i in v]) + builder = ifcopenshell.util.shape_builder.ShapeBuilder(self.file) + results = [] + + for spline in curve_object_data.splines: + points = spline.bezier_points[:] + spline.points[:] + + points = [to_units(dim(p.co)) for p in points] + closed_polyline = spline.use_cyclic_u and len(points) > 1 + results.append(builder.polyline(points, closed=closed_polyline)) + + return results + + def create_point_cloud_representation(self, is_2d: bool = False) -> ifcopenshell.entity_instance: + if self.file.schema == "IFC2X3": + geometric_set = [] + for point in self.settings["geometry"].vertices: + if is_2d: + geometric_set.append(self.create_cartesian_point(point.co.x, point.co.y)) + else: + geometric_set.append(self.create_cartesian_point(point.co.x, point.co.y, point.co.z)) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "GeometricSet", + geometric_set, + ) + + point_cloud = self.create_cartesian_point_list_from_vertices(self.settings["geometry"].vertices, is_2d) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Point" if self.file.schema == "IFC4X3" else "PointCloud", + [point_cloud], + ) + + def create_rectangle_extrusion_representation(self) -> ifcopenshell.entity_instance: + helper = Helper(self.file) + indices = helper.auto_detect_rectangle_profile_extruded_area_solid(self.settings["geometry"]) + profile_def = helper.create_rectangle_profile_def(self.settings["geometry"], indices["profile"]) + item = helper.create_extruded_area_solid(self.settings["geometry"], indices["extrusion"], profile_def) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "SweptSolid", + [item], + ) + + def create_circle_extrusion_representation(self) -> ifcopenshell.entity_instance: + helper = Helper(self.file) + indices = helper.auto_detect_circle_profile_extruded_area_solid(self.settings["geometry"]) + profile_def = helper.create_circle_profile_def(self.settings["geometry"], indices["profile"]) + item = helper.create_extruded_area_solid(self.settings["geometry"], indices["extrusion"], profile_def) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "SweptSolid", + [item], + ) + + def create_arbitrary_extrusion_representation(self) -> ifcopenshell.entity_instance: + helper = Helper(self.file) + indices = helper.auto_detect_arbitrary_closed_profile_extruded_area_solid(self.settings["geometry"]) + profile_def = helper.create_arbitrary_closed_profile_def(self.settings["geometry"], indices["profile"]) + item = helper.create_extruded_area_solid(self.settings["geometry"], indices["extrusion"], profile_def) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "SweptSolid", + [item], + ) + + def create_arbitrary_void_extrusion_representation(self) -> ifcopenshell.entity_instance: + helper = Helper(self.file) + indices = helper.auto_detect_arbitrary_profile_with_voids_extruded_area_solid(self.settings["geometry"]) + if not indices["inner_curves"]: + return self.create_arbitrary_extrusion_representation() + profile_def = helper.create_arbitrary_profile_def_with_voids( + self.settings["geometry"], indices["profile"], indices["inner_curves"] + ) + item = helper.create_extruded_area_solid(self.settings["geometry"], indices["extrusion"], profile_def) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "SweptSolid", + [item], + ) + + def create_material_profile_set_extrusion_representation(self) -> ifcopenshell.entity_instance: + profile_set = self.settings["profile_set_usage"].ForProfileSet + profile_def = profile_set.CompositeProfile or profile_set.MaterialProfiles[0].Profile + position = None + if self.file.schema == "IFC2X3": + position = self.file.createIfcAxis2Placement3D( + self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)), + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.file.createIfcDirection((1.0, 0.0, 0.0)), + ) + item = self.file.createIfcExtrudedAreaSolid( + profile_def, + position, + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.convert_si_to_unit(self.blender_object.dimensions[2]), + ) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "SweptSolid", + [item], + ) + + def create_mesh_representation(self) -> ifcopenshell.entity_instance: + if self.file.schema == "IFC2X3" or self.settings["should_force_faceted_brep"]: + return self.create_faceted_brep() + if self.settings["should_force_triangulation"]: + return self.create_triangulated_face_set() + return self.create_polygonal_face_set() + + def create_faceted_brep(self) -> ifcopenshell.entity_instance: + self.create_vertices() + ifc_raw_items = [None] * self.settings["total_items"] + for i, value in enumerate(ifc_raw_items): + ifc_raw_items[i] = [] + for polygon in self.settings["geometry"].polygons: + ifc_raw_items[polygon.material_index % self.settings["total_items"]].append( + self.file.createIfcFace( + [ + self.file.createIfcFaceOuterBound( + self.file.createIfcPolyLoop([self.ifc_vertices[vertice] for vertice in polygon.vertices]), + True, + ) + ] + ) + ) + # TODO: May not actually be a closed shell, but who checks anyway? + items = [self.file.createIfcFacetedBrep(self.file.createIfcClosedShell(i)) for i in ifc_raw_items if i] + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Brep", + items, + ) + + def create_triangulated_face_set(self) -> ifcopenshell.entity_instance: + ifc_raw_items = [None] * self.settings["total_items"] + if self.settings["should_generate_uvs"]: + ifc_raw_uv_items = [None] * self.settings["total_items"] + for i, value in enumerate(ifc_raw_items): + ifc_raw_items[i] = [] + if self.settings["should_generate_uvs"]: + ifc_raw_uv_items[i] = [] + for polygon in self.settings["geometry"].polygons: + ifc_raw_items[polygon.material_index % self.settings["total_items"]].append( + [v + 1 for v in polygon.vertices] + ) + if self.settings["should_generate_uvs"]: + ifc_raw_uv_items[polygon.material_index % self.settings["total_items"]].append( + [uv + 1 for uv in polygon.loop_indices] + ) + + coordinates = self.create_cartesian_point_list_from_vertices(self.settings["geometry"].vertices) + + if self.settings["should_generate_uvs"]: + # Blender supports multiple UV layers. We don't. Too bad. + tex_coords = self.file.createIfcTextureVertexList( + [tuple(x.uv) for x in self.settings["geometry"].uv_layers[0].data] + ) + items = [] + for i, coord_index in enumerate(ifc_raw_items): + if not coord_index: + continue + tex_coords_index = ifc_raw_uv_items[i] + face_set = self.file.createIfcTriangulatedFaceSet(coordinates, None, None, coord_index) + texture_map = self.file.createIfcIndexedTriangleTextureMap( + MappedTo=face_set, TexCoords=tex_coords, TexCoordIndex=tex_coords_index + ) + items.append(face_set) + else: + items = [self.file.createIfcTriangulatedFaceSet(coordinates, None, None, i) for i in ifc_raw_items if i] + + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Tessellation", + items, + ) + + def create_polygonal_face_set(self) -> ifcopenshell.entity_instance: + ifc_raw_items = [None] * self.settings["total_items"] + for i, value in enumerate(ifc_raw_items): + ifc_raw_items[i] = [] + for polygon in self.settings["geometry"].polygons: + ifc_raw_items[polygon.material_index % self.settings["total_items"]].append( + self.file.createIfcIndexedPolygonalFace([v + 1 for v in polygon.vertices]) + ) + coordinates = self.create_cartesian_point_list_from_vertices(self.settings["geometry"].vertices) + items = [self.file.createIfcPolygonalFaceSet(coordinates, self.is_manifold, i) for i in ifc_raw_items if i] + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Tessellation", + items, + ) + + def create_vertices(self, is_2d: bool = False) -> None: + if is_2d: + for v in self.settings["geometry"].vertices: + co = self.convert_si_to_unit(v.co) + self.ifc_vertices.append(self.file.createIfcCartesianPoint((co[0], co[1]))) + return + self.ifc_vertices.extend( + [ + self.file.createIfcCartesianPoint(self.convert_si_to_unit(v.co)) + for v in self.settings["geometry"].vertices + ] + ) + + def create_cartesian_point( + self, x: float, y: float, z: Optional[float] = None, is_model_coords: bool = True + ) -> ifcopenshell.entity_instance: + """Create IfcCartesianPoint. + + x, y, z coords are provided in SI units. + """ + if is_model_coords and self.coordinate_offset is not None: + x += self.coordinate_offset[0] + y += self.coordinate_offset[1] + if z is not None: + z += self.coordinate_offset[2] + x = self.convert_si_to_unit(x) + y = self.convert_si_to_unit(y) + if z is None: + return self.file.createIfcCartesianPoint((x, y)) + z = self.convert_si_to_unit(z) + return self.file.createIfcCartesianPoint((x, y, z)) + + def create_cartesian_point_list_from_vertices( + self, vertices: bpy.types.MeshVertices, is_2d: bool = False, is_model_coords: bool = True + ) -> ifcopenshell.entity_instance: + # Catch values as floats to benefit from fast buffer copy. + coords = np.empty(len(vertices) * 3, dtype="f") + vertices.foreach_get("co", coords) + coords = coords.reshape(-1, 3) + + if is_2d: + coords = coords[:, :2] + coords_class = "IfcCartesianPointList2D" + else: + coords_class = "IfcCartesianPointList3D" + + if is_model_coords and (offset := self.coordinate_offset) is not None: + coords = coords.astype("d") + if is_2d: + offset = offset[:2] + coords += offset + + return self.file.create_entity(coords_class, ifc_safe_vector_type(self.convert_si_to_unit(coords))) + + def convert_si_to_unit(self, co): + return co / self.settings["unit_scale"] + + def create_annotation2d_representation(self) -> ifcopenshell.entity_instance: + if isinstance(self.settings["geometry"], bpy.types.Mesh) and len(self.settings["geometry"].polygons): + items = self.create_annotation_fill_areas(is_2d=True) + elif isinstance(self.settings["geometry"], bpy.types.Mesh) and not len(self.settings["geometry"].edges): + return self.create_point_cloud_representation(is_2d=True) + else: + items = [self.file.createIfcGeometricCurveSet(self.create_curves(is_2d=True))] + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Annotation2D", + items, + ) + + def create_annotation3d_representation(self) -> ifcopenshell.entity_instance: + items = [] + if isinstance(self.settings["geometry"], bpy.types.Mesh) and len(self.settings["geometry"].polygons): + items = self.create_annotation_fill_areas(is_2d=False) + else: + items = [self.file.createIfcGeometricCurveSet(self.create_curves(is_2d=False))] + # TODO Unsure when it is appropriate to use curve bounded planes + # surfaces = self.create_curve_bounded_planes() + # if surfaces: + # items.append(self.file.createIfcGeometricSet(surfaces)) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "GeometricSet", + items, + ) + + def create_geometric_curve_set_representation(self, is_2d: bool = False) -> ifcopenshell.entity_instance: + geometric_curve_set = self.file.createIfcGeometricCurveSet(self.create_curves(is_2d=is_2d)) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "GeometricCurveSet", + [geometric_curve_set], + ) + + def create_box_representation(self) -> ifcopenshell.entity_instance: + obj = self.blender_object + bounding_box = self.file.createIfcBoundingBox( + self.create_cartesian_point(obj.bound_box[0][0], obj.bound_box[0][1], obj.bound_box[0][2]), + self.convert_si_to_unit(obj.dimensions[0]), + self.convert_si_to_unit(obj.dimensions[1]), + self.convert_si_to_unit(obj.dimensions[2]), + ) + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "BoundingBox", + [bounding_box], + ) + + def create_cog_representation(self) -> Union[ifcopenshell.entity_instance, None]: + mesh = self.settings["geometry"] + if not isinstance(mesh, bpy.types.Mesh) or len(verts := mesh.vertices) == 0: + return + vert = verts[0].co + cog = self.create_cartesian_point(vert.x, vert.y, vert.z) + return self.file.create_entity( + "IfcShapeRepresentation", + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Point", + (cog,), + ) + + def create_structural_reference_representation(self) -> ifcopenshell.entity_instance: + if isinstance(self.geometry, bpy.types.Mesh) and len(self.geometry.vertices) == 1: + return self.file.createIfcTopologyRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Vertex", + [self.create_vertex_point(self.geometry.vertices[0].co)], + ) + return self.file.createIfcTopologyRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Edge", + [self.create_edge()], + ) + + def create_vertex_point(self, point: Vector) -> ifcopenshell.entity_instance: + return self.file.createIfcVertexPoint(self.create_cartesian_point(point.x, point.y, point.z)) + + def get_spline_points( + self, spline: bpy.types.Spline + ) -> list[Union[bpy.types.SplinePoint, bpy.types.BezierSplinePoint]]: + points = spline.bezier_points[:] + spline.points[:] + if spline.use_cyclic_u: + points.append(points[0]) + return points + + def create_edge(self) -> Union[ifcopenshell.entity_instance, None]: + geometry = self.geometry + if isinstance(geometry, bpy.types.Curve): + points = self.get_spline_points(geometry.splines[0]) + elif isinstance(geometry, bpy.types.Mesh): + points = geometry.vertices + else: + assert False, type(geometry) + if not points: + return + return self.file.createIfcEdge(self.create_vertex_point(points[0].co), self.create_vertex_point(points[1].co)) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_shape_aspect.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_shape_aspect.py new file mode 100644 index 0000000000000000000000000000000000000000..2f4ee941fe1ecf9ebe2dc80d70134f9c036de2ad --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_shape_aspect.py @@ -0,0 +1,88 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +from typing import Optional + + +def add_shape_aspect( + file: ifcopenshell.file, + name: str, + items: list[ifcopenshell.entity_instance], + representation: ifcopenshell.entity_instance, + part_of_product: ifcopenshell.entity_instance, + description: Optional[str] = None, +) -> ifcopenshell.entity_instance: + """Adds a shape aspect to items that are part of a representation and product + + Existing shape aspects will be reused where possible. If the items already + belong to another shape aspect with a different name, this relationship + will be purged. + + Warning: it is not possible to add a shape aspect to types (i.e. + IfcRepresentationMap) in IFC2X3. + + :param name: The name of the shape aspect. This is case sensitive. + :param items: IfcRepresentationItems that will be assigned to this aspect. + :param representation: The IfcShapeRepresentation that the items are in. + :param part_of_product: The IfcRepresentationMap or + IfcProductDefinitionShape that the representation is in. + :param description: A description to set for the shape aspect. It's usually + not necessary. + :return: The IfcShapeAspect + """ + result = None + items_set = set(items) + for aspect in part_of_product.HasShapeAspects or []: + if aspect.Name == name: + for aspect_rep in aspect.ShapeRepresentations: + if aspect_rep.ContextOfItems == representation.ContextOfItems: + aspect.Description = description + aspect_rep.Items = tuple(set(aspect_rep.Items) | items_set) + result = aspect + if not result: + aspect_rep = file.createIfcShapeRepresentation( + ContextOfItems=representation.ContextOfItems, + RepresentationIdentifier=representation.RepresentationIdentifier, + RepresentationType=representation.RepresentationType, + Items=items, + ) + aspect.ShapeRepresentations += (aspect_rep,) + result = aspect + else: + for aspect_rep in aspect.ShapeRepresentations: + if aspect_rep.ContextOfItems != representation.ContextOfItems: + continue + if set(aspect_rep.Items) & items_set: + if new_items := set(aspect_rep.Items) - items_set: + aspect_rep.Items = tuple(new_items) + else: + file.remove(aspect_rep) + if not aspect.ShapeRepresentations: + file.remove(aspect) + + if result: + return result + + aspect_rep = file.createIfcShapeRepresentation( + ContextOfItems=representation.ContextOfItems, + RepresentationIdentifier=representation.RepresentationIdentifier, + RepresentationType=representation.RepresentationType, + Items=items, + ) + return file.createIfcShapeAspect((aspect_rep,), name, description, True, part_of_product) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_slab_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_slab_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..f6a6f85d1af3ede7451f7a07ac9745f9e0a7a87a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_slab_representation.py @@ -0,0 +1,161 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element +import ifcopenshell.util.unit +from ifcopenshell.util.data import Clipping +from math import sin, cos +from typing import Any, Optional, Union + + +def add_slab_representation( + file: ifcopenshell.file, + context: ifcopenshell.entity_instance, + depth: float = 0.2, + # TODO: document remaining args. + direction_sense: str = "POSITIVE", + offset: float = 0.0, + x_angle: float = 0.0, + clippings: Optional[list[Union[Clipping, ifcopenshell.entity_instance]]] = None, + polyline: Optional[list[tuple[float, float]]] = None, +) -> ifcopenshell.entity_instance: + """ + Add a geometric representation for a slab. + + :param context: The IfcGeometricRepresentationContext for the representation, + only Model/Body/MODEL_VIEW type of representations are currently supported. + :param depth: The slab depth, in meters. + :param x_angle: The slope angle along the slab's X-axis, in radians. + :param clippings: List of planes that define clipping half space solids. + Clippings can be `Clipping` objects or dictionaries of arguments for `Clipping.parse`. + :return: IfcShapeRepresentation. + + Example: + + .. code:: python + + context = ifcopenshell.util.representation.get_context(ifc_file, "Model", "Body", "MODEL_VIEW") + clippings = [ifcopenshell.util.data.Clipping(location=(0.0, 0.0, 0.1), normal=(0.0, 0.0, 1.0),)] + representation = ifcopenshell.api.geometry.add_slab_representation(ifc_file, context, depth=0.2, clippings=clippings) + ifcopenshell.api.geometry.assign_representation(ifc_file, product=element, representation=representation) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute( + context, + depth, + direction_sense, + offset, + x_angle, + clippings if clippings is not None else [], + polyline, + ) + + +class Usecase: + file: ifcopenshell.file + + def execute( + self, + context: ifcopenshell.entity_instance, + depth: float, + direction_sense: str, + offset: float, + x_angle: float, + clippings: list[Union[Clipping, ifcopenshell.entity_instance]], + polyline: Optional[list[tuple[float, float]]], + ) -> ifcopenshell.entity_instance: + self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file) + self.clippings = clippings + self.depth = depth + self.direction_sense = direction_sense + self.offset = offset + self.x_angle = x_angle + self.polyline = polyline + return self.file.create_entity( + "IfcShapeRepresentation", + context, + context.ContextIdentifier, + "Clipping" if self.clippings else "SweptSolid", + [self.create_item()], + ) + + def create_item(self) -> ifcopenshell.entity_instance: + size = self.convert_si_to_unit(1) + points = ((0.0, 0.0), (size, 0.0), (size, size), (0.0, size), (0.0, 0.0)) + if self.polyline: + points = [ + (self.convert_si_to_unit(p[0]), self.convert_si_to_unit(p[1] * abs(1 / cos(self.x_angle)))) + for p in self.polyline + ] + if self.file.schema == "IFC2X3": + curve = self.file.createIfcPolyline([self.file.createIfcCartesianPoint(p) for p in points]) + else: + curve = self.file.createIfcIndexedPolyCurve(self.file.createIfcCartesianPointList2D(points)) + + if self.x_angle: + direction_ratios = (0.0, sin(self.x_angle), cos(self.x_angle)) + else: + direction_ratios = (0.0, 0.0, 1.0) + + offset_direction = direction_ratios # offset direction doesn't change if direction_sense is negative + extrusion_direction = self.file.createIfcDirection(direction_ratios) + if self.direction_sense == "NEGATIVE": + direction_ratios = tuple(-n for n in direction_ratios) + extrusion_direction = self.file.createIfcDirection(direction_ratios) + + perpendicular_offset = self.convert_si_to_unit(self.offset) * abs(1 / cos(self.x_angle)) + perpendicular_depth = self.convert_si_to_unit(self.depth) * abs(1 / cos(self.x_angle)) + position = None + # default position for IFC2X3 where .Position is not optional + if self.file.schema == "IFC2X3" or self.offset != 0: + position_vector = ( + offset_direction[0] * perpendicular_offset, + offset_direction[1] * perpendicular_offset, + offset_direction[2] * perpendicular_offset, + ) + position = self.file.createIfcAxis2Placement3D( + self.file.createIfcCartesianPoint(position_vector), + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.file.createIfcDirection((1.0, 0.0, 0.0)), + ) + + extrusion = self.file.create_entity( + "IfcExtrudedAreaSolid", + self.file.createIfcArbitraryClosedProfileDef("AREA", None, curve), + position, + extrusion_direction, + perpendicular_depth, + ) + if self.clippings: + return self.apply_clippings(extrusion) + return extrusion + + def apply_clippings(self, first_operand: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + while self.clippings: + clipping = self.clippings.pop() + if isinstance(clipping, ifcopenshell.entity_instance): + new = ifcopenshell.util.element.copy(self.file, clipping) + new.FirstOperand = first_operand + first_operand = new + else: # Clipping + first_operand = clipping.apply(self.file, first_operand, self.unit_scale) + return first_operand + + def convert_si_to_unit(self, co: float) -> float: + return co / self.unit_scale diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_wall_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_wall_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..53e2f58660546fc94a7e8c1367135bc7379f44f9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_wall_representation.py @@ -0,0 +1,142 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element +import ifcopenshell.util.unit +from math import sin, cos, pi +from typing import Optional, Union, Any +from ifcopenshell.util.data import Clipping + + +def add_wall_representation( + file: ifcopenshell.file, + context: ifcopenshell.entity_instance, + length: float = 1.0, + height: float = 3.0, + direction_sense: str = "POSITIVE", + offset: float = 0.0, + thickness: float = 0.2, + x_angle: float = 0.0, + clippings: Optional[list[Union[Clipping, dict[str, Any]]]] = None, + booleans: Optional[list[ifcopenshell.entity_instance]] = None, +) -> ifcopenshell.entity_instance: + """ + Add a geometric representation for a wall. + + :param context: The IfcGeometricRepresentationContext for the representation, + only Model/Body/MODEL_VIEW type of representations are currently supported. + :param length: The length of the wall in meters. + :param height: The height of the wall in meters. + :param offset: The base offset distance of the wall from the origin. + :param thickness: The thickness of the wall in meters. + :param x_angle: The slope angle along the wall's X-axis, in radians. + :param clippings: List of clipping definitions. Clippings can be `Clipping` objects + or dictionaries of arguments for `Clipping.parse`. + :param booleans: List of any existing IfcBooleanResults. + :return: IfcShapeRepresentation. + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "context": context, + "length": length, + "height": height, + "direction_sense": direction_sense, + "offset": offset, + "thickness": thickness, + "x_angle": x_angle, + "clippings": clippings if clippings is not None else [], + "booleans": booleans if booleans is not None else [], + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + clippings: list[Clipping] + + def execute(self) -> ifcopenshell.entity_instance: + self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file) + self.clippings = [Clipping.parse(c) for c in self.settings["clippings"]] + return self.file.createIfcShapeRepresentation( + self.settings["context"], + self.settings["context"].ContextIdentifier, + "Clipping" if self.clippings or self.settings["booleans"] else "SweptSolid", + [self.create_item()], + ) + + def create_item(self) -> ifcopenshell.entity_instance: + length = self.convert_si_to_unit(self.settings["length"]) + thickness = self.convert_si_to_unit(self.settings["thickness"]) + thickness *= 1 / cos(self.settings["x_angle"]) + if self.settings["direction_sense"] == "NEGATIVE": + thickness *= -1 + points = ( + (0.0, 0.0), + (0.0, thickness), + (length, thickness), + (length, 0.0), + (0.0, 0.0), + ) + if self.file.schema == "IFC2X3": + curve = self.file.createIfcPolyline([self.file.createIfcCartesianPoint(p) for p in points]) + else: + curve = self.file.createIfcIndexedPolyCurve(self.file.createIfcCartesianPointList2D(points), None, False) + if self.settings["x_angle"]: + extrusion_direction = self.file.createIfcDirection( + (0.0, sin(self.settings["x_angle"]), cos(self.settings["x_angle"])) + ) + else: + extrusion_direction = self.file.createIfcDirection((0.0, 0.0, 1.0)) + extrusion = self.file.createIfcExtrudedAreaSolid( + self.file.createIfcArbitraryClosedProfileDef("AREA", None, curve), + self.file.createIfcAxis2Placement3D( + self.file.createIfcCartesianPoint((0.0, self.convert_si_to_unit(self.settings["offset"]), 0.0)), + self.file.createIfcDirection((0.0, 0.0, 1.0)), + self.file.createIfcDirection((1.0, 0.0, 0.0)), + ), + extrusion_direction, + self.convert_si_to_unit(self.settings["height"]) * abs(1 / cos(self.settings["x_angle"])), + ) + if self.settings["booleans"]: + extrusion = self.apply_booleans(extrusion) + if self.clippings: + extrusion = self.apply_clippings(extrusion) + return extrusion + + def apply_booleans(self, first_operand: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + while self.settings["booleans"]: + boolean = self.settings["booleans"].pop() + boolean.FirstOperand = first_operand + first_operand = boolean + return first_operand + + def apply_clippings(self, first_operand: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + while self.clippings: + clipping = self.clippings.pop() + if isinstance(clipping, ifcopenshell.entity_instance): + new = ifcopenshell.util.element.copy(self.file, clipping) + new.FirstOperand = first_operand + first_operand = new + else: # Clipping + first_operand = clipping.apply(self.file, first_operand, self.unit_scale) + return first_operand + + def convert_si_to_unit(self, co: Any) -> Any: + return co / self.unit_scale diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_window_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_window_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..298ec18f70cb3fd652c743a14ae77015658f10ad --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/add_window_representation.py @@ -0,0 +1,784 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import sys +import numpy as np +import dataclasses +import ifcopenshell.api.geometry +import ifcopenshell.util.unit +from itertools import chain +from ifcopenshell.util.shape_builder import ShapeBuilder, V +from typing import Any, Optional, Literal, Union, overload + +DATACLASS_SLOTS = {} if sys.version_info < (3, 10) else {"slots": True} +ZIP_STRICT = {} if sys.version_info < (3, 10) else {"strict": True} + +# SCHEMAS describe panels setup +# where: +# - schema rows represent window X axis +# - schema columns represent window Y axis +# - order of rows is from top of the window to bottom + +WINDOW_TYPE = Literal[ + "SINGLE_PANEL", + "DOUBLE_PANEL_HORIZONTAL", + "DOUBLE_PANEL_VERTICAL", + "TRIPLE_PANEL_BOTTOM", + "TRIPLE_PANEL_HORIZONTAL", + "TRIPLE_PANEL_LEFT", + "TRIPLE_PANEL_RIGHT", + "TRIPLE_PANEL_TOP", + "TRIPLE_PANEL_VERTICAL", +] + +DEFAULT_PANEL_SCHEMAS = { + "SINGLE_PANEL": [[0]], + "DOUBLE_PANEL_HORIZONTAL": [[0], [1]], + "DOUBLE_PANEL_VERTICAL": [[0, 1]], + "TRIPLE_PANEL_BOTTOM": [[0, 1], [2, 2]], + "TRIPLE_PANEL_TOP": [[0, 0], [1, 2]], + "TRIPLE_PANEL_LEFT": [[0, 1], [0, 2]], + "TRIPLE_PANEL_RIGHT": [[0, 1], [2, 1]], + "TRIPLE_PANEL_HORIZONTAL": [[0], [1], [2]], + "TRIPLE_PANEL_VERTICAL": [[0, 1, 2]], +} + + +def mm(x: float) -> float: + """mm to meters shortcut for readability""" + return x / 1000 + + +def create_ifc_window_frame_simple( + builder: ShapeBuilder, size: np.ndarray, thickness: Union[list[float], float], position: Optional[np.ndarray] = None +) -> list[ifcopenshell.entity_instance]: + """`thickness` of the profile is defined as list in the following order: + `(LEFT, TOP, RIGHT, BOTTOM)` + + `thickness` can be also defined just as 1 float value. + """ + + if not isinstance(thickness, list): + thickness = [thickness] * 4 + if position is None: + position = np.zeros(3) + np_X, np_Y, np_Z = 0, 1, 2 + np_XZ = [0, 2] + th_left, th_up, th_right, th_bottom = thickness + + def get_extruded_profile(profile: ifcopenshell.entity_instance): + return builder.extrude(profile, size[np_Y], position=position, **builder.extrude_kwargs("Y")) + + # if all lining sides are present then we can just use two rectangles + # as inner and outer curves of the profile + if thickness.count(0) == 0: + panel_rect = builder.rectangle(size=size[np_XZ]) + + inner_rect_size = size - (th_left + th_right, 0, th_bottom + th_up) + inner_rect = builder.rectangle(size=inner_rect_size[np_XZ], position=(th_left, th_bottom)) + + panel_profile = builder.profile(panel_rect, inner_curves=inner_rect) + return [get_extruded_profile(panel_profile)] + + # if some side has zero thickness it means we cannot use inner curves + # and need to generate L/U shape or just separate rectangles + else: + + def get_segments_from_thickness() -> list[tuple[float, ...]]: + nonlocal thickness + segments = [] + cur_segment = [] + for i, thickness_ in enumerate(thickness): + if thickness_ == 0: + if cur_segment: + segments.append(tuple(cur_segment)) + cur_segment = [] + else: + cur_segment.append(i) + + if cur_segment: + if len(segments) > 0 and segments[0][0] == 0: + segments[0] = tuple(cur_segment) + segments[0] + else: + segments.append(tuple(cur_segment)) + return segments + + # prepare coords to build a lining + # fmt: off + outer_coords = [ + ((0, 0), (0, size[np_Z])), + ((0, size[np_Z]), (size[np_X], size[np_Z])), + ((size[np_X], size[np_Z]), (size[np_X], 0)), + ((size[np_X], 0), (0, 0)), + ] + inner_coords = [ + ((th_left, th_bottom), (th_left, size[np_Z] - th_up)), + ((th_left, size[np_Z] - th_up), (size[np_X] - th_right, size[np_Z] - th_up)), + ((size[np_X] - th_right, size[np_Z] - th_up), (size[np_X] - th_right, th_bottom)), + ((size[np_X] - th_right, th_bottom), (th_left, th_bottom)), + ] + # fmt: on + + def get_points(segment: tuple[float, ...]) -> list[tuple[float, float]]: + points = [] + for side in segment: + outer = outer_coords[side] + if side == segment[0]: # first segment + points.append(outer[0]) + points.append(outer[1]) + + for side in reversed(segment): + inner = inner_coords[side] + if side == segment[-1]: # last non zero segment + points.append(inner[1]) + points.append(inner[0]) + return points + + segments = get_segments_from_thickness() + segments_items: list[ifcopenshell.entity_instance] = [] + for seg in segments: + polyline = builder.polyline(points=get_points(seg), closed=True) + panel_profile = builder.profile(polyline) + segments_items.append(get_extruded_profile(panel_profile)) + + return segments_items + + +def window_l_shape_check( + lining_to_panel_offset_y_full: float, + lining_depth: float, + lining_to_panel_offset_x: list[float], + lining_thickness: list[float], +) -> bool: + """`lining_thickness` and `lining_to_panel_offset_x` expected to be defined as a list, + similarly to `create_ifc_window_frame_simple` `thickness` argument""" + l_shape_check = lining_to_panel_offset_y_full < lining_depth and any( + x_offset < th for th, x_offset in zip(lining_thickness, lining_to_panel_offset_x, **ZIP_STRICT) + ) + return l_shape_check + + +def create_ifc_window( + builder: ShapeBuilder, + lining_size: np.ndarray, + lining_thickness: list[float], + lining_to_panel_offset_x: float, + lining_to_panel_offset_y_full: float, + frame_size: np.ndarray, + frame_thickness: float, + glass_thickness: float, + position: np.ndarray, + x_offsets: Optional[list[float]] = None, +) -> dict[str, list[ifcopenshell.entity_instance]]: + """`lining_thickness` and `x_offsets` are expected to be defined as a list, + similarly to `create_ifc_window_frame_simple` `thickness` argument""" + lining_items: list[ifcopenshell.entity_instance] = [] + main_lining_size = lining_size + + np_Y = 1 + + if x_offsets is None: + x_offsets = [lining_to_panel_offset_x] * 4 + # need to check offsets to decide whether lining should be rectangle + # or L shaped + l_shape_check = window_l_shape_check( + lining_to_panel_offset_y_full, + lining_size[np_Y], + x_offsets, + lining_thickness, + ) + + if l_shape_check: + main_lining_size = lining_size.copy() + main_lining_size[np_Y] = lining_to_panel_offset_y_full + + second_lining_size = lining_size.copy() + second_lining_size[np_Y] = lining_size[np_Y] - lining_to_panel_offset_y_full + second_lining_position = V(0, lining_to_panel_offset_y_full, 0) + second_lining_thickness = [min(th, x_offset) for th, x_offset in zip(lining_thickness, x_offsets, **ZIP_STRICT)] + + second_lining_items = create_ifc_window_frame_simple( + builder, second_lining_size, second_lining_thickness, second_lining_position + ) + lining_items.extend(second_lining_items) + + main_lining_items = create_ifc_window_frame_simple(builder, main_lining_size, lining_thickness) + lining_items.extend(main_lining_items) + + frame_position = V( + x_offsets[0], + lining_to_panel_offset_y_full, + x_offsets[3], + ) + + frame_extruded_items = create_ifc_window_frame_simple(builder, frame_size, frame_thickness, frame_position) + + glass_position = frame_position + V(0, frame_size[np_Y] / 2 - glass_thickness / 2, 0) + glass_rect = builder.deep_copy(frame_extruded_items[0].SweptArea.InnerCurves[0]) + glass = builder.extrude(glass_rect, glass_thickness, position=glass_position, **builder.extrude_kwargs("Y")) + + output_items = (lining_items, frame_extruded_items, [glass]) + builder.translate(chain(*output_items), position) + + return {"Lining": lining_items, "Framing": frame_extruded_items, "Glazing": [glass]} + + +# we use dataclass as we need default values for arguments +# it's okay to use slots since we don't need dynamic attributes +@dataclasses.dataclass(**DATACLASS_SLOTS) +class WindowLiningProperties: + LiningDepth: Optional[float] = None + """Optional, defaults to 50mm.""" + + LiningThickness: Optional[float] = None + """Optional, defaults to 50mm.""" + + LiningOffset: Optional[float] = None + """Offset to the wall. Optional, defaults to 50mm.""" + + LiningToPanelOffsetX: Optional[float] = None + """Offset from the wall. Optional, defaults to 25mm.""" + + # that way it allows you to define overall_depth constant between all panels + # and still have panels with different size: + # overall_depth = lining_depth + offset_y + # full offset from X axis = overall_depth - frame_depth. + LiningToPanelOffsetY: Optional[float] = None + """Offset from the lining. Optional, defaults to 25mm.""" + + MullionThickness: Optional[float] = None + """Mullion thickness (horizontal distance between panels). + + Applies to windows of types: DoublePanelVertical, TriplePanelBottom, TriplePanelTop, + TriplePanelLeft, TriplePanelRight. + + Optional, defaults to 50mm.""" + + FirstMullionOffset: Optional[float] = None + """Distance from the first lining to the mullion center. Optional, defaults to 300mm.""" + + SecondMullionOffset: Optional[float] = None + """Distance from the first lining to the second mullion center. + + Applies to windows of type: TriplePanelVertical. + + Optional, defaults to 450mm.""" + + TransomThickness: Optional[float] = None + """Transom thickness (vertical distance between panels), works similar way to mullions. + + Applies to windows of types:DoublePanelHorizontal, TriplePanelBottom, TriplePanelTop, + TriplePanelLeft, TriplePanelRight. + + Optional, defaults to 50mm.""" + + FirstTransomOffset: Optional[float] = None + """Optional, defaults to 300mm.""" + + SecondTransomOffset: Optional[float] = None + """ + Applies to windows of type: TriplePanelHorizontal. + Optional, defaults to 600mm.""" + + ShapeAspectStyle: None = None + """Optional. Deprecated argument.""" + + def initialize_properties(self, unit_scale: float) -> None: + # in meters + # fmt: off + default_values: dict[str, float] = dict( + LiningDepth = mm(50), + LiningThickness = mm(50), + LiningOffset = mm(50), + LiningToPanelOffsetX = mm(25), + LiningToPanelOffsetY = mm(25), + MullionThickness = mm(50), + FirstMullionOffset = mm(300), + SecondMullionOffset = mm(450), + TransomThickness = mm(50), + FirstTransomOffset = mm(300), + SecondTransomOffset = mm(600), + ) + # fmt: on + + si_conversion = 1 / unit_scale + for attr, default_value in default_values.items(): + if getattr(self, attr) is not None: + continue + setattr(self, attr, default_value * si_conversion) + + +@dataclasses.dataclass(**DATACLASS_SLOTS) +class WindowPanelProperties: + FrameDepth: Optional[float] = None + """Frame thickness by Y axis. Optional, defaults to 35 mm.""" + + FrameThickness: Optional[float] = None + """Frame thickness by X axis. Optional, defaults to 35 mm.""" + + PanelPosition: None = None + """Optional, value is never used""" + + PanelOperation: None = None + """Optional, value is never used. + Defines the basic ways to describe how window panels operate.""" + + ShapeAspectStyle: None = None + """Optional. Deprecated argument.""" + + def initialize_properties(self, unit_scale: float) -> None: + # in meters + # fmt: off + default_values: dict[str, float] = dict( + FrameDepth = mm(35), + FrameThickness = mm(35), + ) + # fmt: on + + si_conversion = 1 / unit_scale + for attr, default_value in default_values.items(): + if getattr(self, attr) is not None: + continue + setattr(self, attr, default_value * si_conversion) + + +def add_window_representation( + file: ifcopenshell.file, + *, # keywords only as this API implementation is probably not final + context: ifcopenshell.entity_instance, + overall_height: Optional[float] = None, + overall_width: Optional[float] = None, + partition_type: WINDOW_TYPE = "SINGLE_PANEL", + lining_properties: Optional[Union[WindowLiningProperties, dict[str, Any]]] = None, + panel_properties: Optional[list[Union[WindowPanelProperties, dict[str, Any]]]] = None, + part_of_product: Optional[ifcopenshell.entity_instance] = None, + unit_scale: Optional[float] = None, +) -> ifcopenshell.entity_instance: + """units in usecase_settings expected to be in ifc project units + + :param context: IfcGeometricRepresentationContext for the representation. + :param overall_height: Overall window height. Defaults to 0.9m. + :param overall_width: Overall window width. Defaults to 0.6m. + :param partition_type: Type of the window. Defaults to SINGLE_PANEL. + :param lining_properties: WindowLiningProperties or a dictionary to create one. + See WindowLiningProperties description for details. + :param panel_properties: A list of WindowPanelProperties or dictionaries to create one. + See WindowPanelProperties description for details. + :param unit_scale: The unit scale as calculated by + ifcopenshell.util.unit.calculate_unit_scale. If not provided, it + will be automatically calculated for you. + :return: IfcShapeRepresentation for a window. + """ + usecase = Usecase() + usecase.file = file + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcWindow.htm + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcWindowTypePartitioningEnum.htm + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcWindowLiningProperties.htm + # http://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcWindowPanelProperties.htm + # define unit_scale first as it's going to be used setting default arguments + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) if unit_scale is None else unit_scale + settings: dict[str, Any] = {"unit_scale": unit_scale} + + if lining_properties is None: + lining_properties = WindowLiningProperties() + elif not isinstance(lining_properties, WindowLiningProperties): + lining_properties = WindowLiningProperties(**lining_properties) + lining_properties.initialize_properties(unit_scale) + lining_properties = dataclasses.asdict(lining_properties) + + if panel_properties is None: + panel_properties = [WindowPanelProperties()] + + for i in range(len(panel_properties)): + properties = panel_properties[i] + if not isinstance(properties, WindowPanelProperties): + properties = WindowPanelProperties(**properties) + properties.initialize_properties(unit_scale) + panel_properties[i] = dataclasses.asdict(properties) + + settings.update( + { + "context": context, + "overall_height": overall_height if overall_height is not None else usecase.convert_si_to_unit(0.9), + "overall_width": overall_width if overall_width is not None else usecase.convert_si_to_unit(0.6), + "partition_type": partition_type, + "lining_properties": lining_properties, + "panel_properties": panel_properties, + "part_of_product": part_of_product, + } + ) + + usecase.settings = settings + usecase.settings["panel_schema"] = DEFAULT_PANEL_SCHEMAS[usecase.settings["partition_type"]] + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + builder = ShapeBuilder(self.file) + np_X, np_Y, np_Z = 0, 1, 2 + overall_height: float = self.settings["overall_height"] + overall_width: float = self.settings["overall_width"] + + if self.settings["context"].TargetView == "ELEVATION_VIEW": + rect = builder.rectangle(V(overall_width, 0, overall_height)) + representation_evelevation = builder.get_representation(self.settings["context"], rect) + return representation_evelevation + + panel_schema: list[list[int]] = self.settings["panel_schema"] + panels: list[dict[str, Any]] = self.settings["panel_properties"] + accumulated_height: list[float] = [0] * len(panel_schema[0]) + built_panels: list[int] = [] + window_items: list[ifcopenshell.entity_instance] = [] + lining_items: list[ifcopenshell.entity_instance] = [] + framing_items: list[ifcopenshell.entity_instance] = [] + glazing_items: list[ifcopenshell.entity_instance] = [] + + lining_props: dict[str, Any] = self.settings["lining_properties"] + lining_thickness: float = lining_props["LiningThickness"] + lining_depth: float = lining_props["LiningDepth"] + lining_offset: float = lining_props["LiningOffset"] + lining_to_panel_offset_x: float = lining_props["LiningToPanelOffsetX"] + lining_to_panel_offset_y: float = lining_props["LiningToPanelOffsetY"] + overall_depth: float = lining_depth + lining_to_panel_offset_y + + mullion_thickness: float = lining_props["MullionThickness"] / 2 + first_mullion_offset: float = lining_props["FirstMullionOffset"] + second_mullion_offset: float = lining_props["SecondMullionOffset"] + transom_thickness: float = lining_props["TransomThickness"] / 2 + first_transom_offset: float = lining_props["FirstTransomOffset"] + second_transom_offset: float = lining_props["SecondTransomOffset"] + glass_thickness: float = self.convert_si_to_unit(0.01) + + panel_schema = list(reversed(panel_schema)) + + # create 2d representation + def create_ifc_window_2d_representation() -> ifcopenshell.entity_instance: + items_2d: list[ifcopenshell.entity_instance] = [] + + top_row = panel_schema[-1] + unique_cols = len(set(top_row)) + built_panels: list[int] = [] + accumulated_width: float = 0 + + for column_i, panel_i in enumerate(top_row): + cur_panel_items: list[ifcopenshell.entity_instance] = [] + + # lists represent left and right linings + window_lining_thickness = [lining_thickness] * 2 + closed_lining = [True] * 2 + + if panel_i in built_panels: + continue + + # detect mullion + has_mullion = unique_cols > 1 + first_column = column_i == 0 + last_column = column_i == unique_cols - 1 + left_to_mullion = has_mullion and not last_column + right_to_mullion = has_mullion and not first_column + + if has_mullion: + if first_column: + panel_width = first_mullion_offset + elif last_column: + panel_width = overall_width - accumulated_width + else: + panel_width = second_mullion_offset - accumulated_width + + # mullion thickness + if not first_column: + window_lining_thickness[0] = mullion_thickness # left column + closed_lining[0] = False + if not last_column: + window_lining_thickness[1] = mullion_thickness # right column + closed_lining[1] = False + else: + panel_width = overall_width + + frame_depth: float = panels[panel_i]["FrameDepth"] + frame_thickness: float = panels[panel_i]["FrameThickness"] + lining_to_panel_offset_y_full = (lining_depth - frame_depth) + lining_to_panel_offset_y + base_frame_clear = lining_to_panel_offset_x + frame_thickness - lining_thickness + current_offset_x = base_frame_clear - frame_thickness + mullion_thickness + + # add lining + cur_panel_items.append( + builder.polyline( + [ + (window_lining_thickness[0], 0), + (panel_width - window_lining_thickness[1], 0), + ] + ) + ) + + def get_lining_shape( + lining_thickness: float, closed: bool = True, mirror: bool = False, x_offset: Optional[float] = None + ) -> ifcopenshell.entity_instance: + if x_offset is None: + x_offset = lining_to_panel_offset_x + l_shape_check = window_l_shape_check( + lining_to_panel_offset_y_full, + lining_depth, + [x_offset], + [lining_thickness], + ) + if l_shape_check: + lining_shape = builder.polyline( + [ + (0, lining_depth), + (x_offset, lining_depth), + (x_offset, lining_to_panel_offset_y_full), + (lining_thickness, lining_to_panel_offset_y_full), + (lining_thickness, 0), + (0, 0), + ], + closed=closed, + ) + else: + lining_shape = builder.polyline( + [ + (0, lining_depth), + (lining_thickness, lining_depth), + (lining_thickness, 0), + (0, 0), + ], + closed=closed, + ) + + if mirror: + builder.mirror( + lining_shape, + mirror_axes=(1, 0), + mirror_point=(panel_width / 2, 0), + ) + + return lining_shape + + cur_panel_items.extend( + [ + get_lining_shape( + window_lining_thickness[0], + closed=closed_lining[0], + x_offset=current_offset_x if right_to_mullion else None, + ), + get_lining_shape( + window_lining_thickness[1], + closed=closed_lining[1], + x_offset=current_offset_x if left_to_mullion else None, + mirror=True, + ), + ] + ) + + # add frame + frame_items: list[ifcopenshell.entity_instance] = [] + + frame_position = ( + current_offset_x if right_to_mullion else lining_to_panel_offset_x, + lining_to_panel_offset_y_full, + ) + + frame_width = panel_width + frame_width -= current_offset_x if left_to_mullion else lining_to_panel_offset_x + frame_width -= current_offset_x if right_to_mullion else lining_to_panel_offset_x + + frame_vertical = builder.rectangle(size=(frame_thickness, frame_depth)) + frame_items.extend( + [ + frame_vertical, + builder.mirror( + frame_vertical, + mirror_axes=(1, 0), + mirror_point=(frame_width / 2, 0), + create_copy=True, + ), + ] + ) + + frame_horizontal = builder.polyline([(frame_thickness, 0), (frame_width - frame_thickness, 0)]) + frame_items.extend( + [ + frame_horizontal, + builder.translate(frame_horizontal, (0, frame_depth), create_copy=True), + ] + ) + # glass + frame_items.append(builder.translate(frame_horizontal, (0, frame_depth / 2), create_copy=True)) + + builder.translate(frame_items, frame_position) + cur_panel_items.extend(frame_items) + + builder.translate(cur_panel_items, (accumulated_width, 0)) + + accumulated_width += panel_width + built_panels.append(panel_i) + items_2d.extend(cur_panel_items) + + builder.translate(items_2d, (0, lining_offset)) + representation_2d = builder.get_representation(self.settings["context"], items_2d) + return representation_2d + + if self.settings["context"].TargetView == "PLAN_VIEW": + return create_ifc_window_2d_representation() + + # TODO: need more readable way to define panel width and height + unique_rows_in_col = [ + len(set(row[column_i] for row in panel_schema)) for column_i in range(len(panel_schema[0])) + ] + + for row_i, panel_row in enumerate(panel_schema): + accumulated_width = 0 + unique_cols = len(set(panel_row)) + + for column_i, panel_i in enumerate(panel_row): + # detect mullion + has_mullion = unique_cols > 1 + first_column = column_i == 0 + last_column = column_i == unique_cols - 1 + left_to_mullion = has_mullion and not last_column + right_to_mullion = has_mullion and not first_column + + # detect transom + has_transom = unique_rows_in_col[column_i] > 1 + first_row = row_i == 0 + last_row = row_i == unique_rows_in_col[column_i] - 1 + top_to_transom = has_transom and not first_row + bottom_to_transom = has_transom and not last_row + + # calculate current panel dimensions + if has_mullion: + # panel_width + if first_column: + panel_width = first_mullion_offset + elif last_column: + panel_width = overall_width - accumulated_width + else: + panel_width = second_mullion_offset - accumulated_width + else: + panel_width = overall_width + + if has_transom: + if first_row: + panel_height = first_transom_offset + elif last_row: + panel_height = overall_height - accumulated_height[column_i] + else: + panel_height = second_transom_offset - accumulated_height[column_i] + else: + panel_height = overall_height + + if panel_i in built_panels: + accumulated_height[column_i] += panel_height + accumulated_width += panel_width + continue + + cur_panel = panels[panel_i] + frame_depth = cur_panel["FrameDepth"] + frame_thickness = cur_panel["FrameThickness"] + lining_to_panel_offset_y_full = (lining_depth - frame_depth) + lining_to_panel_offset_y + + # fmt: off + # calculate lining thickness and frame size / offset + # taking into account mullions and transoms + window_lining_thickness = [ + mullion_thickness if right_to_mullion else lining_thickness, + transom_thickness if bottom_to_transom else lining_thickness, + mullion_thickness if left_to_mullion else lining_thickness, + transom_thickness if top_to_transom else lining_thickness, + ] + + # x offsets can differ if there are mullions or transoms because we're trying to maintain symmetry + base_frame_clear = lining_to_panel_offset_x + frame_thickness - lining_thickness + current_offset_x = base_frame_clear - frame_thickness + mullion_thickness + current_offset_z = base_frame_clear - frame_thickness + transom_thickness + x_offsets = [ + current_offset_x if right_to_mullion else lining_to_panel_offset_x, # LEFT + current_offset_z if bottom_to_transom else lining_to_panel_offset_x, # TOP + current_offset_x if left_to_mullion else lining_to_panel_offset_x, # RIGHT + current_offset_z if top_to_transom else lining_to_panel_offset_x, # BOTTOM + ] + # fmt: on + + window_lining_size = V(panel_width, lining_depth, panel_height) + frame_size = window_lining_size.copy() + frame_size[np_Y] = frame_depth + frame_size[np_X] -= x_offsets[0] + x_offsets[2] + frame_size[np_Z] -= x_offsets[1] + x_offsets[3] + + window_panel_position = V(accumulated_width, 0, accumulated_height[column_i]) + # create window panel + current_window_items = create_ifc_window( + builder, + window_lining_size, + window_lining_thickness, + lining_to_panel_offset_x, + lining_to_panel_offset_y_full, + frame_size, + frame_thickness, + glass_thickness, + window_panel_position, + x_offsets, + ) + built_panels.append(panel_i) + window_items.extend(chain(*current_window_items.values())) + lining_items.extend(current_window_items["Lining"]) + framing_items.extend(current_window_items["Framing"]) + glazing_items.extend(current_window_items["Glazing"]) + + accumulated_height[column_i] += panel_height + accumulated_width += panel_width + + builder.translate(window_items, (0, lining_offset, 0)) # wall offset + representation = builder.get_representation(self.settings["context"], window_items) + if self.settings["part_of_product"]: + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Lining", + items=lining_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Framing", + items=framing_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + ifcopenshell.api.geometry.add_shape_aspect( + self.file, + "Glazing", + items=glazing_items, + representation=representation, + part_of_product=self.settings["part_of_product"], + ) + + return representation + + @overload + def convert_si_to_unit(self, value: float) -> float: ... + @overload + def convert_si_to_unit(self, value: np.ndarray) -> np.ndarray: ... + def convert_si_to_unit(self, value: Union[float, np.ndarray]) -> Union[float, np.ndarray]: + si_conversion = 1 / self.settings["unit_scale"] + return value * si_conversion diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/assign_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/assign_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..5b62fd463924875a62637fda6d8342f9c253a018 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/assign_representation.py @@ -0,0 +1,95 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.owner +import ifcopenshell.api.geometry +import ifcopenshell.util.element +from typing import Any + + +def assign_representation( + file: ifcopenshell.file, product: ifcopenshell.entity_instance, representation: ifcopenshell.entity_instance +) -> None: + usecase = Usecase() + usecase.file = file + return usecase.execute(product, representation) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, product: ifcopenshell.entity_instance, representation: ifcopenshell.entity_instance) -> None: + if product.is_a("IfcProduct"): + product_type = ifcopenshell.util.element.get_type(product) + if ( + product_type + and product_type.RepresentationMaps + and representation.RepresentationType != "MappedRepresentation" + # Revit is adding a non-mapped representation to the exported profile-based types, + # so assigning representation to occurrence by accident was assigning it to the type. + # We guard from this by skipping profile and layer-based types. + # See 6934 for example. + and not ( + (material := ifcopenshell.util.element.get_material(product_type)) + and material.is_a() in ("IfcMaterialProfileSet", "IfcMaterialLayerSet") + ) + ): + product = product_type + + if product.is_a("IfcProduct"): + self.assign_product_representation(product, representation) + elif product.is_a("IfcTypeProduct"): + if product.RepresentationMaps: + maps = list(product.RepresentationMaps) + else: + maps = [] + self.zero = self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + self.x_axis = self.file.createIfcDirection((1.0, 0.0, 0.0)) + self.z_axis = self.file.createIfcDirection((0.0, 0.0, 1.0)) + maps.append( + self.file.create_entity( + "IfcRepresentationMap", + **{ + "MappingOrigin": self.file.createIfcAxis2Placement3D(self.zero, self.z_axis, self.x_axis), + "MappedRepresentation": representation, + }, + ) + ) + product.RepresentationMaps = maps + if self.file.schema == "IFC2X3": + types = product.ObjectTypeOf + else: + types = product.Types + if types: + for element in types[0].RelatedObjects: + mapped_representation = ifcopenshell.api.geometry.map_representation( + self.file, representation=representation + ) + self.assign_product_representation(element, mapped_representation) + ifcopenshell.api.owner.update_owner_history(self.file, element=product) + + def assign_product_representation( + self, product: ifcopenshell.entity_instance, representation: ifcopenshell.entity_instance + ) -> None: + definition = product.Representation + if not definition: + definition = self.file.createIfcProductDefinitionShape() + product.Representation = definition + representations = list(definition.Representations) if definition.Representations else [] + representations.append(representation) + definition.Representations = representations diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_element.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_element.py new file mode 100644 index 0000000000000000000000000000000000000000..f737b54c77bb7f140f7c0af4d0452a151b4e441a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_element.py @@ -0,0 +1,60 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Optional + + +def connect_element( + file: ifcopenshell.file, + relating_element: ifcopenshell.entity_instance, + related_element: ifcopenshell.entity_instance, + description: Optional[str] = None, +) -> ifcopenshell.entity_instance: + incompatible_connections = [] + + for rel in relating_element.ConnectedFrom: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatingElement == related_element: + incompatible_connections.append(rel) + + for rel in related_element.ConnectedTo: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatedElement == relating_element: + incompatible_connections.append(rel) + + if incompatible_connections: + for connection in set(incompatible_connections): + history = connection.OwnerHistory + file.remove(connection) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + for rel in relating_element.ConnectedTo: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatedElement == related_element: + rel.Description = description + return rel + + return file.createIfcRelConnectsElements( + ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(file), + Description=description, + RelatingElement=relating_element, + RelatedElement=related_element, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_path.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_path.py new file mode 100644 index 0000000000000000000000000000000000000000..81fa276a2cbb3fba9d8387a1962b60aac68acf41 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_path.py @@ -0,0 +1,81 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Optional + + +def connect_path( + file: ifcopenshell.file, + relating_element: ifcopenshell.entity_instance, + related_element: ifcopenshell.entity_instance, + relating_connection: str = "NOTDEFINED", + related_connection: str = "NOTDEFINED", + description: Optional[str] = None, +) -> ifcopenshell.entity_instance: + incompatible_connections: list[ifcopenshell.entity_instance] = [] + for rel in relating_element.ConnectedTo: + if not rel.is_a("IfcRelConnectsPathElements"): + continue + if rel.RelatedElement == related_element: + incompatible_connections.append(rel) + elif rel.RelatingConnectionType in ["ATSTART", "ATEND"] and rel.RelatingConnectionType == relating_connection: + incompatible_connections.append(rel) + + for rel in relating_element.ConnectedFrom: + if not rel.is_a("IfcRelConnectsPathElements"): + continue + if rel.RelatedConnectionType in ["ATSTART", "ATEND"] and rel.RelatedConnectionType == relating_connection: + incompatible_connections.append(rel) + + for rel in related_element.ConnectedFrom: + if not rel.is_a("IfcRelConnectsPathElements"): + continue + if rel.RelatedConnectionType in ["ATSTART", "ATEND"] and rel.RelatedConnectionType == related_connection: + incompatible_connections.append(rel) + + for rel in related_element.ConnectedTo: + if not rel.is_a("IfcRelConnectsPathElements"): + continue + if rel.RelatedElement == relating_element: + incompatible_connections.append(rel) + elif rel.RelatingConnectionType in ["ATSTART", "ATEND"] and rel.RelatingConnectionType == related_connection: + incompatible_connections.append(rel) + + if incompatible_connections: + for connection in set(incompatible_connections): + history = connection.OwnerHistory + file.remove(connection) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + return file.create_entity( + "IfcRelConnectsPathElements", + ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(file), + Description=description, + RelatingElement=relating_element, + RelatedElement=related_element, + RelatingConnectionType=relating_connection, + RelatedConnectionType=related_connection, + RelatingPriorities=[], + RelatedPriorities=[], + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_wall.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..8666a386930ef4f133344461f67b7ab4fea38ef9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/connect_wall.py @@ -0,0 +1,62 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import ifcopenshell +import ifcopenshell.api.geometry +import ifcopenshell.util.placement +import ifcopenshell.util.representation +import ifcopenshell.util.shape_builder +from typing import Optional + + +def connect_wall( + file: ifcopenshell.file, + wall1: ifcopenshell.entity_instance, + wall2: ifcopenshell.entity_instance, + is_atpath: bool = False, +) -> Optional[ifcopenshell.entity_instance]: + matrix1i = np.linalg.inv(ifcopenshell.util.placement.get_local_placement(wall1.ObjectPlacement)) + matrix2 = ifcopenshell.util.placement.get_local_placement(wall2.ObjectPlacement) + axis1 = ifcopenshell.util.representation.get_reference_line(wall1) + axis2 = ifcopenshell.util.representation.get_reference_line(wall2) + axis2[0] = (matrix1i @ matrix2 @ np.concatenate((axis2[0], (0, 1))))[:2] + axis2[1] = (matrix1i @ matrix2 @ np.concatenate((axis2[1], (0, 1))))[:2] + midx = (axis1[0][0] + axis1[1][0]) / 2 + starty = axis2[0][1] + endy = axis2[1][1] + y = axis1[0][1] + + if (x := ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y)) is None: + return + + wall1_end = "ATEND" if x > midx else "ATSTART" + if is_atpath: + wall2_end = "ATPATH" + elif abs(y - starty) < abs(y - endy): + wall2_end = "ATSTART" + else: + wall2_end = "ATEND" + + return ifcopenshell.api.geometry.connect_path( + file, + relating_element=wall1, + related_element=wall2, + relating_connection=wall1_end, + related_connection=wall2_end, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/create_2pt_wall.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/create_2pt_wall.py new file mode 100644 index 0000000000000000000000000000000000000000..3401b29c7a15970e506516f3861d400c0cb499e7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/create_2pt_wall.py @@ -0,0 +1,90 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import ifcopenshell.api.geometry +import ifcopenshell.util.unit +from typing import Any + + +def create_2pt_wall( + file: ifcopenshell.file, + element: ifcopenshell.entity_instance, + context: ifcopenshell.entity_instance, + p1: tuple[float, float], + p2: tuple[float, float], + elevation: float, + height: float, + thickness: float, + is_si: bool = True, +) -> ifcopenshell.entity_instance: + """ + Create a wall between two points (p1 and p2). + A shortcut for geometry.add_wall_representation. + + :param element: Wall IFC element. + :param context: IfcGeometricRepresentationContext for the representation. + only Model/Body/MODEL_VIEW type of representations are currently supported. + :param p1: The starting point (x, y) of the wall. + :param p2: The ending point (x, y) of the wall. + :param elevation: The base elevation (z-coordinate) for the wall. + :param height: The height of the wall. + :param thickness: The thickness of the wall. + :param is_si: If True, provided arguments units are treated as SI (meters). + If False, values are converted from project units to SI. + :return: IfcShapeRepresentation. + """ + si_conversion = ifcopenshell.util.unit.calculate_unit_scale(file) + + p1_ = np.array(p1).astype(float) + p2_ = np.array(p2).astype(float) + + length = float(np.linalg.norm(p2_ - p1_)) + + if not is_si: + length = convert_unit_to_si(length, si_conversion) + height = convert_unit_to_si(height, si_conversion) + thickness = convert_unit_to_si(thickness, si_conversion) + # No need to convert p2 as length is already calculated. + p1_ = convert_unit_to_si(p1_, si_conversion) + elevation = convert_unit_to_si(elevation, si_conversion) + + representation = ifcopenshell.api.geometry.add_wall_representation( + file, + context=context, + length=length, + height=height, + thickness=thickness, + ) + + v = p2_ - p1_ + v /= float(np.linalg.norm(v)) + matrix = np.array( + [ + [v[0], -v[1], 0, p1_[0]], + [v[1], v[0], 0, p1_[1]], + [0, 0, 1, elevation], + [0, 0, 0, 1], + ] + ) + ifcopenshell.api.geometry.edit_object_placement(file, product=element, matrix=matrix) + return representation + + +def convert_unit_to_si(co: Any, si_conversion: float) -> Any: + return co * si_conversion diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_element.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_element.py new file mode 100644 index 0000000000000000000000000000000000000000..666d3d35b4bc579f3abc717e893b0ce34ad536b0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_element.py @@ -0,0 +1,55 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def disconnect_element( + file: ifcopenshell.file, + relating_element: ifcopenshell.entity_instance, + related_element: ifcopenshell.entity_instance, +) -> None: + # TODO: arguments relating_element, related_element probably + # should be renamed to element1, element2 + # as api call doesn't really treat them as "relating" and "related" + # and just purging all connections between them + incompatible_connections = [] + + for rel in relating_element.ConnectedTo: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatedElement == related_element: + incompatible_connections.append(rel) + + for rel in relating_element.ConnectedFrom: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatingElement == related_element: + incompatible_connections.append(rel) + + for rel in related_element.ConnectedTo: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatedElement == relating_element: + incompatible_connections.append(rel) + + for rel in related_element.ConnectedFrom: + if rel.is_a() == "IfcRelConnectsElements" and rel.RelatingElement == relating_element: + incompatible_connections.append(rel) + + if incompatible_connections: + for connection in set(incompatible_connections): + history = connection.OwnerHistory + file.remove(connection) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_path.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_path.py new file mode 100644 index 0000000000000000000000000000000000000000..787f7a5633eb44c953de277a106f35cd84b9ca52 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/disconnect_path.py @@ -0,0 +1,58 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api +import ifcopenshell.util.element +from typing import Optional + + +def disconnect_path( + file: ifcopenshell.file, + element: Optional[ifcopenshell.entity_instance] = None, + connection_type: Optional[str] = None, + relating_element: Optional[ifcopenshell.entity_instance] = None, + related_element: Optional[ifcopenshell.entity_instance] = None, +) -> None: + """There are two options to use this API method: + - provide `element` (connected from) and `connection_type` that should be disconnected. + - provide connected elements to disconnect explicitly: + `relating_element` (connected from) and `related_element` (connected to) + """ + if connection_type and element: + connections = [ + r + for r in element.ConnectedTo + if r.is_a("IfcRelConnectsPathElements") and r.RelatingConnectionType == connection_type + ] + [ + r + for r in element.ConnectedFrom + if r.is_a("IfcRelConnectsPathElements") and r.RelatedConnectionType == connection_type + ] + elif related_element: + connections = [ + r + for r in relating_element.ConnectedTo + if r.is_a("IfcRelConnectsPathElements") and r.RelatedElement == related_element + ] + + for connection in set(connections): + history = connection.OwnerHistory + file.remove(connection) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/edit_object_placement.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/edit_object_placement.py new file mode 100644 index 0000000000000000000000000000000000000000..2e37e99e26082c1ac6decba15ee5c239013d0c2c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/edit_object_placement.py @@ -0,0 +1,198 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import numpy.typing as npt +import ifcopenshell.api.owner +import ifcopenshell.util.unit +import ifcopenshell.util.element +import ifcopenshell.util.placement +from ifcopenshell.util.shape_builder import ShapeBuilder +from typing import Optional, Union, Any + +NPArrayOfFloats = npt.NDArray[np.float64] + + +def edit_object_placement( + file: ifcopenshell.file, + product: ifcopenshell.entity_instance, + matrix: Optional[NPArrayOfFloats] = None, + is_si: bool = True, + should_transform_children: bool = False, +) -> ifcopenshell.entity_instance: + """Changes the object placement matrix of an element + + The placement matrix is a 4x4 matrix describing the location and + orientation of an element in 3D. See + https://docs.ifcopenshell.org/ifcopenshell-python/geometry_creation.html#object-placements + for more details. + + This only supports local placements. Grid and linear placements are not + supported. + + :param matrix: A 4x4 matrix in numpy. If left blank, it is the identity + matrix (equivalent to ``np.eye(4)``). + :param is_si: If True, the matrix is given in SI units. If false, in + project units. + :param should_transform_children: A child element is a nested element, + opening, filling, etc. If true, child elements will move along with the + parent. If false, child elements will stay where they are. Because most + placements in IFC are relative, this means that if a child moves, we + actually don't change their placement. + :return: The new or updated IfcLocalPlacement entity + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "product": product, + "matrix": matrix if matrix is not None else np.eye(4), + "is_si": is_si, + "should_transform_children": should_transform_children, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + if not hasattr(self.settings["product"], "ObjectPlacement"): + return + self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(self.file) + self.builder = ShapeBuilder(self.file) + + if not self.settings["is_si"]: + self.convert_matrix_to_si(self.settings["matrix"]) + + children_settings = [] + if not self.settings["should_transform_children"]: + children_settings = self.get_children_settings(self.settings["product"].ObjectPlacement) + + placement_rel_to = self.get_placement_rel_to() + relative_placement = self.get_relative_placement(placement_rel_to) + new_placement = self.file.createIfcLocalPlacement(RelativePlacement=relative_placement) + + old_placement = self.settings["product"].ObjectPlacement + + if old_placement: + for inverse in self.file.get_inverse(old_placement): + if inverse.is_a("IfcLocalPlacement"): + ifcopenshell.util.element.replace_attribute(inverse, old_placement, new_placement) + + if self.file.get_total_inverses(old_placement) == 1: + self.settings["product"].ObjectPlacement = None + old_placement.PlacementRelTo = None + ifcopenshell.util.element.remove_deep2(self.file, old_placement) + + new_placement.PlacementRelTo = placement_rel_to + self.settings["product"].ObjectPlacement = new_placement + + ifcopenshell.api.owner.update_owner_history(self.file, element=self.settings["product"]) + + for settings in children_settings: + self.settings = settings + self.execute() + + return new_placement + + def convert_matrix_to_si(self, matrix: NPArrayOfFloats): + matrix[0][3] *= self.unit_scale + matrix[1][3] *= self.unit_scale + matrix[2][3] *= self.unit_scale + + def get_placement_rel_to(self) -> Union[ifcopenshell.entity_instance, None]: + product = self.settings["product"] + relating_object = None + + if rels := getattr(product, "Decomposes", None): + relating_object = rels[0].RelatingObject + elif rels := getattr(product, "Nests", None): + relating_object = rels[0].RelatingObject + elif rels := getattr(product, "ContainedIn", None): + relating_object = rels[0].RelatedElement + elif rels := getattr(product, "VoidsElements", None): + relating_object = rels[0].RelatingBuildingElement + elif rels := getattr(product, "FillsVoids", None): + relating_object = rels[0].RelatingOpeningElement + elif rels := getattr(product, "ProjectsElements", None): + relating_object = rels[0].RelatingElement + # TODO: add tests when there will be adherence api + elif rels := getattr(product, "AdheresToElement", None): + relating_object = rels[0].RelatingElement + elif rels := getattr(product, "ContainedInStructure", None): + return rels[0].RelatingStructure.ObjectPlacement + + if relating_object: + return getattr(relating_object, "ObjectPlacement", None) + + def get_children_settings(self, placement: Union[ifcopenshell.entity_instance, None]) -> list[dict]: + if not placement: + return [] + results = [] + # NOTE: we ignore subchildren as we already adjust position for their parent + # therefore they're not present in `results` and `should_transform_children` should be `True` + for referenced_placement in placement.ReferencedByPlacements: + matrix = ifcopenshell.util.placement.get_local_placement(referenced_placement) + for obj in referenced_placement.PlacesObject: + if obj.is_a("IfcDistributionPort"): + # Although a port is technically a nested child, it is generally + # more intuitive that the ports always move with the parent. + continue + elif obj.is_a("IfcFeatureElement"): + # Feature elements affect the geometry of their parent, and + # so logically should always move with the parent. However, + # subchildren (fillings) shouldn't move. + placement2 = obj.ObjectPlacement + for referenced_placement2 in placement2.ReferencedByPlacements: + matrix2 = ifcopenshell.util.placement.get_local_placement(referenced_placement2) + for obj2 in referenced_placement2.PlacesObject: + results.append( + {"product": obj2, "matrix": matrix2, "is_si": False, "should_transform_children": True} + ) + continue + results.append({"product": obj, "matrix": matrix, "is_si": False, "should_transform_children": True}) + return results + + def get_relative_placement( + self, placement_rel_to: Union[ifcopenshell.entity_instance, None] + ) -> ifcopenshell.entity_instance: + if placement_rel_to: + relating_object_matrix = ifcopenshell.util.placement.get_local_placement(placement_rel_to) + relating_object_matrix[0][3] = self.convert_unit_to_si(relating_object_matrix[0][3]) + relating_object_matrix[1][3] = self.convert_unit_to_si(relating_object_matrix[1][3]) + relating_object_matrix[2][3] = self.convert_unit_to_si(relating_object_matrix[2][3]) + else: + relating_object_matrix = np.eye(4) + m = self.settings["matrix"] + x = np.array((m[0][0], m[1][0], m[2][0])) + z = np.array((m[0][2], m[1][2], m[2][2])) + o = np.array((m[0][3], m[1][3], m[2][3])) + object_matrix = ifcopenshell.util.placement.a2p(o, z, x) + relative_placement_matrix = np.linalg.inv(relating_object_matrix) @ object_matrix + return self.builder.create_axis2_placement_3d( + self.convert_si_to_unit(relative_placement_matrix[:, 3][0:3]), + relative_placement_matrix[:, 2][0:3], + relative_placement_matrix[:, 0][0:3], + ) + + def convert_si_to_unit(self, co: NPArrayOfFloats) -> NPArrayOfFloats: + return co / self.unit_scale + + def convert_unit_to_si(self, co: NPArrayOfFloats) -> NPArrayOfFloats: + return co * self.unit_scale diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/map_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/map_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..e868beea6661beaa1167899f3287e203bded4679 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/map_representation.py @@ -0,0 +1,64 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def map_representation( + file: ifcopenshell.file, representation: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + usecase = Usecase() + usecase.file = file + return usecase.execute(representation) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, representation: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + self.representation = representation + mapping_source = self.get_mapping_source() + + zero = self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + x_axis = self.file.createIfcDirection((1.0, 0.0, 0.0)) + y_axis = self.file.createIfcDirection((0.0, 1.0, 0.0)) + z_axis = self.file.createIfcDirection((0.0, 0.0, 1.0)) + + mapping_target = self.file.createIfcCartesianTransformationOperator3D(x_axis, y_axis, zero, 1, z_axis) + mapped_item = self.file.createIfcMappedItem(mapping_source, mapping_target) + return self.file.create_entity( + "IfcShapeRepresentation", + **{ + "ContextOfItems": representation.ContextOfItems, + "RepresentationIdentifier": representation.RepresentationIdentifier, + "RepresentationType": "MappedRepresentation", + "Items": [mapped_item], + } + ) + + def get_mapping_source(self) -> ifcopenshell.entity_instance: + for inverse in self.file.get_inverse(self.representation): + if inverse.is_a("IfcRepresentationMap"): + return inverse + zero = self.file.createIfcCartesianPoint((0.0, 0.0, 0.0)) + x_axis = self.file.createIfcDirection((1.0, 0.0, 0.0)) + z_axis = self.file.createIfcDirection((0.0, 0.0, 1.0)) + mapping_origin = self.file.createIfcAxis2Placement3D(zero, z_axis, x_axis) + return self.file.createIfcRepresentationMap( + MappingOrigin=mapping_origin, MappedRepresentation=self.representation + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/regenerate_wall_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/regenerate_wall_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..0cce951810157959291f3c2875ec407d64079560 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/regenerate_wall_representation.py @@ -0,0 +1,635 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import json +import numpy as np +import ifcopenshell +import ifcopenshell.api.context +import ifcopenshell.api.geometry +import ifcopenshell.util.element +import ifcopenshell.util.placement +import ifcopenshell.util.representation +import ifcopenshell.util.shape_builder +import ifcopenshell.util.unit +from collections import namedtuple +from math import sin, cos +from typing import Optional + +# https://stackoverflow.com/a/9184560/9627415 +# Possible optimisation to linalg.norm? + +PrioritisedLayer = namedtuple("PrioritisedLayer", "priority thickness") + + +def regenerate_wall_representation( + file: ifcopenshell.file, + wall: ifcopenshell.entity_instance, + length: float = 1.0, + height: float = 1.0, + angle: Optional[float] = None, +) -> ifcopenshell.entity_instance: + """ + Regenerate the body representation of a wall taking into account connections. + + IFC defines how a standard (case) wall should behave that has a material + layer set and connections to other walls using IfcRelConnectsPathElements. + This function will regenerate the body geometry of a wall taking into + account the notches, butts, mitres, etc in the wall due to connections with + other walls. + + A standard wall has a 2D axis line as well as parameters defined in terms + of layer thicknesses and priorities. The body geometry is defined as a 2D + XY profile which is extruded in the +Z direction. For this function to + work, a wall must have these defined and the project must have an axis and + body representation context. + + For non-sloped walls, a 2D profile is generated and extruded in the +Z + direction. The profile may be a composite profile, if the wall is split due + to wall joins along the path of the wall that protrude all the way through + the wall. + + For sloped walls, a basic rectangular 2D profile is extruded, and then + additional extrusions are generated for each connection that boolean + difference the base extrusion. + + This will also update the axis line representation (e.g. trim the axis line + to any connections). + + The wall's object placement will also be updated such that the placement is + equivalent to the axis line's start point (which therefore becomes (0.0, + 0.0)). This is a logical, consistent, and useful placement coordinate + (especially for apps that can pivot using this point). + + All this functionality relies on the Plan/Axis/GRAPH_VIEW representation + context. It will be created if it does not exist. + + :param wall: The IfcWall for the representation, + only Model/Body/MODEL_VIEW type of representations are currently supported. + :param length: If the wall doesn't have an axis length, this is the default + length in SI units. + :param height: If the wall doesn't already have a height, this is the + default height in SI units. + :param angle: If the wall doesn't already have a slope, this is the default + angle in radians. Left as none or 0 defines no slope. + :return: The newly generated body IfcShapeRepresentation + """ + return Regenerator(file).regenerate(wall, length=length, height=height, angle=angle) + + +class Regenerator: + def __init__(self, file): + self.file = file + self.body = ifcopenshell.util.representation.get_context(file, "Model", "Body", "MODEL_VIEW") + self.axis = ifcopenshell.util.representation.get_context(file, "Plan", "Axis", "GRAPH_VIEW") + self.unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) + self.is_angled = False + + if not self.axis: + if not (plan := ifcopenshell.util.representation.get_context(file, "Plan")): + plan = ifcopenshell.api.context.add_context(file, context_type="Plan") + self.axis = ifcopenshell.api.context.add_context( + file, context_type="Plan", context_identifier="Axis", target_view="GRAPH_VIEW", parent=plan + ) + + def regenerate(self, wall, length=1.0, height=1.0, angle=None): + self.fallback_length = length / self.unit_scale + self.fallback_height = height / self.unit_scale + self.fallback_angle = angle + layers = self.get_layers(wall) + if not layers: + return + reference = ifcopenshell.util.representation.get_reference_line(wall, self.fallback_length) + self.reference_p1, self.reference_p2 = reference + self.wall_vectors = self.get_wall_vectors(wall) + axes = self.get_axes(wall, reference, layers, self.wall_vectors["a"]) + self.miny = axes[0][0][1] + self.maxy = axes[-1][0][1] + self.end_point = None + self.start_points = [] + self.start_vector = np.array((0.0, 0.0, 1.0)) + self.start_offset = 0.0 + self.atpath_points = [] + self.split_points = [] + self.maxpath_points = [] + self.minpath_points = [] + self.end_points = [] + self.end_vector = np.array((0.0, 0.0, 1.0)) + self.end_offset = 0.0 + manual_booleans = self.get_manual_booleans(wall) + + for rel in wall.ConnectedTo: + if rel.is_a("IfcRelConnectsPathElements"): + wall2 = rel.RelatedElement + layers1 = self.combine_layers(layers.copy(), rel.RelatingPriorities) + layers2 = self.combine_layers(self.get_layers(wall2), rel.RelatedPriorities) + if not layers1 or not layers2: + continue + self.join(wall, wall2, layers1, layers2, rel.RelatingConnectionType, rel.RelatedConnectionType) + + for rel in wall.ConnectedFrom: + if rel.is_a("IfcRelConnectsPathElements"): + wall2 = rel.RelatingElement + layers1 = self.combine_layers(layers.copy(), rel.RelatedPriorities) + layers2 = self.combine_layers(self.get_layers(wall2), rel.RelatingPriorities) + if not layers1 or not layers2: + continue + self.join(wall, wall2, layers1, layers2, rel.RelatedConnectionType, rel.RelatingConnectionType) + + miny = axes[-2][0][1] + maxy = axes[-1][0][1] + if not self.start_points: + minx = axes[0][0][0] + self.start_points = [ + np.array((minx, axes[0][0][1])), + np.array((minx, axes[-1][0][1])), + ] + if not self.end_points: + maxx = axes[0][1][0] + self.end_points = [ + np.array((maxx, axes[0][0][1])), + np.array((maxx, axes[-1][0][1])), + ] + + if self.start_points[0][1] > self.start_points[-1][1]: # Canonicalise to the +Y direction + self.start_points.reverse() + if self.end_points[0][1] > self.end_points[-1][1]: # Canonicalise to the +Y direction + self.end_points.reverse() + + builder = ifcopenshell.util.shape_builder.ShapeBuilder(self.file) + + # Don't offset wall if there are manual booleans, because that'll also shift operands + offset = None if manual_booleans else self.reference_p1 * -1 + + if self.is_angled: + start_points = [p.copy() for p in self.start_points] + end_points = [p.copy() for p in self.end_points] + if self.end_offset > 0: + for point in end_points: + point[0] += self.end_offset + if self.start_offset < 0: + for point in start_points: + point[0] += self.start_offset + points = [] + points.extend(start_points) + end_points.reverse() + points.extend(end_points) + item = builder.extrude( + builder.polyline(points, closed=True, position_offset=offset), + magnitude=self.wall_vectors["d"], + extrusion_vector=self.wall_vectors["z"], + ) + + operands = [] + if not np.allclose(self.start_vector, np.array((0.0, 0.0, 1.0))): + points = self.start_points.copy() + while ifcopenshell.util.shape_builder.is_x(points[0][1], points[1][1]): + points.pop(0) + while ifcopenshell.util.shape_builder.is_x(points[-1][1], points[-2][1]): + points.pop() + newx = min([p[0] for p in points]) - abs(self.start_offset) + p1 = points[-1].copy() + p1[0] = newx + p2 = p1.copy() + p2[1] = points[0][1] + points.extend((p1, p2)) + magnitude = np.linalg.norm(self.start_vector * (self.wall_vectors["h"] / self.start_vector[2])) + operands.append( + builder.extrude( + builder.polyline(points, closed=True, position_offset=offset), + magnitude=magnitude, + extrusion_vector=self.start_vector, + ) + ) + + if not np.allclose(self.end_vector, np.array((0.0, 0.0, 1.0))): + points = self.end_points.copy() + while ifcopenshell.util.shape_builder.is_x(points[0][1], points[1][1]): + points.pop(0) + while ifcopenshell.util.shape_builder.is_x(points[-1][1], points[-2][1]): + points.pop() + + newx = max([p[0] for p in points]) + abs(self.end_offset) + p1 = points[-1].copy() + p1[0] = newx + p2 = p1.copy() + p2[1] = points[0][1] + points.extend((p1, p2)) + magnitude = np.linalg.norm(self.end_vector * (self.wall_vectors["h"] / self.end_vector[2])) + operands.append( + builder.extrude( + builder.polyline(points, closed=True, position_offset=offset), + magnitude=magnitude, + extrusion_vector=self.end_vector, + ) + ) + + for atpath_vector, points in self.atpath_points: + if len(points) <= 2: + continue + magnitude = np.linalg.norm(atpath_vector * (self.wall_vectors["h"] / atpath_vector[2])) + operands.append( + builder.extrude( + builder.polyline(points, closed=True, position_offset=offset), + magnitude=magnitude, + extrusion_vector=atpath_vector, + ) + ) + + if operands: + item = ifcopenshell.api.geometry.add_boolean(self.file, first_item=item, second_items=operands)[-1] + else: + # A wall footprint may be multiple profiles if the wall is split into two due to an ATPATH connection + profiles = [] + minx = max([p[0] for p in self.start_points]) + maxx = min([p[0] for p in self.end_points]) + split_points = [] + for points in sorted(self.split_points, key=lambda x: x[0][0]): # Sort islands in the +X direction + if any([p[0] > maxx or p[0] < minx for p in points]): # Can't have anything outside our start/end + continue + split_points.append(points) + start_points = [p.copy() for p in self.start_points] + end_points = [p.copy() for p in self.end_points] + split_points.insert(0, start_points) + split_points.append(end_points) + split_points = iter(split_points) + + if maxy < miny: + self.maxpath_points, self.minpath_points = self.minpath_points, self.maxpath_points + if self.maxpath_points: + self.maxpath_points[0] = list(reversed(self.maxpath_points[0])) + if self.minpath_points: + self.minpath_points[0] = list(reversed(self.minpath_points[0])) + + while True: + # Draw each profile as clockwise starting from (minx, miny) + start_split = next(split_points, None) + if not start_split: + break + end_split = next(split_points, None) + if not end_split: + break + maxy_minx = start_split[-1][0] + maxy_maxx = end_split[-1][0] + miny_minx = start_split[0][0] + miny_maxx = end_split[0][0] + # Do more defensive checks here? + points = start_split + + remaining_path_points = [] + for maxpath_points in self.maxpath_points: + if maxpath_points[0][0] > maxy_minx and maxpath_points[-1][0] < maxy_maxx: + points.extend(maxpath_points) + else: + remaining_path_points.append(maxpath_points) + self.maxpath_points = remaining_path_points + + points.extend(end_split[::-1]) + + remaining_path_points = [] + for minpath_points in self.minpath_points: + if minpath_points[0][0] < miny_maxx and minpath_points[-1][0] > miny_minx: + points.extend(minpath_points) + else: + remaining_path_points.append(minpath_points) + self.minpath_points = remaining_path_points + + profiles.append(builder.profile(builder.polyline(points, closed=True, position_offset=offset))) + + for points in self.maxpath_points + self.minpath_points: + profiles.append(builder.profile(builder.polyline(points, closed=True, position_offset=offset))) + + if len(profiles) > 1: + profile = self.file.createIfcCompositeProfileDef("AREA", Profiles=profiles) + else: + profile = profiles[0] + + item = builder.extrude(profile, magnitude=self.wall_vectors["d"], extrusion_vector=self.wall_vectors["z"]) + for boolean in self.get_manual_booleans(wall): + boolean.FirstOperand = item + item = boolean + + body_rep = builder.get_representation(self.body, items=[item]) + if old_rep := ifcopenshell.util.representation.get_representation(wall, self.body): + ifcopenshell.util.element.replace_element(old_rep, body_rep) + ifcopenshell.util.element.remove_deep2(self.file, old_rep) + else: + ifcopenshell.api.geometry.assign_representation(self.file, product=wall, representation=body_rep) + + item = builder.polyline([self.reference_p1, self.reference_p2], position_offset=offset) + axis_rep = builder.get_representation(self.axis, items=[item]) + if old_rep := ifcopenshell.util.representation.get_representation(wall, self.axis): + ifcopenshell.util.element.replace_element(old_rep, axis_rep) + ifcopenshell.util.element.remove_deep2(self.file, old_rep) + else: + ifcopenshell.api.geometry.assign_representation(self.file, product=wall, representation=axis_rep) + + if not np.allclose(self.reference_p1, np.array((0.0, 0.0))) and not manual_booleans: + children = [] + for referenced_placement in wall.ObjectPlacement.ReferencedByPlacements: + matrix = ifcopenshell.util.placement.get_local_placement(referenced_placement) + children.append((matrix, referenced_placement.PlacesObject)) + + matrix = ifcopenshell.util.placement.get_local_placement(wall.ObjectPlacement) + matrix[:, 3] = matrix @ np.concatenate((self.reference_p1, (0, 1))) + ifcopenshell.api.geometry.edit_object_placement( + self.file, product=wall, matrix=matrix, is_si=False, should_transform_children=True + ) + + # Restore children to their previous location + for matrix, elements in children: + for element in elements: + ifcopenshell.api.geometry.edit_object_placement( + self.file, product=element, matrix=matrix, is_si=False, should_transform_children=True + ) + + return body_rep + + def join(self, wall1, wall2, layers1, layers2, connection1, connection2): + if connection1 == "NOTDEFINED" or connection2 == "NOTDEFINED": + return + if connection1 == "ATPATH" and connection2 == "ATPATH": + return + + reference1 = ifcopenshell.util.representation.get_reference_line(wall1, self.fallback_length) + reference2 = ifcopenshell.util.representation.get_reference_line(wall2, self.fallback_length) + wall_vectors2 = self.get_wall_vectors(wall2) + axes1 = self.get_axes(wall1, reference1, layers1, self.wall_vectors["a"]) + axes2 = self.get_axes(wall2, reference2, layers2, wall_vectors2["a"]) + matrix1i = np.linalg.inv(ifcopenshell.util.placement.get_local_placement(wall1.ObjectPlacement)) + matrix2 = ifcopenshell.util.placement.get_local_placement(wall2.ObjectPlacement) + + # Convert wall2 data to wall1 local coordinates + for axis in axes2: + axis[0] = (matrix1i @ matrix2 @ np.concatenate((axis[0], (0, 1))))[:2] + axis[1] = (matrix1i @ matrix2 @ np.concatenate((axis[1], (0, 1))))[:2] + reference2[0] = (matrix1i @ matrix2 @ np.concatenate((reference2[0], (0, 1))))[:2] + reference2[1] = (matrix1i @ matrix2 @ np.concatenate((reference2[1], (0, 1))))[:2] + wall_vectors2["z"] = (matrix1i @ matrix2 @ np.append(wall_vectors2["z"], 0.0))[:3] + wall_vectors2["y"] = (matrix1i @ matrix2 @ np.append(wall_vectors2["y"], 0.0))[:3] + + axis2 = axes2[0] # Take an arbitrary axis of wall2 + if ifcopenshell.util.shape_builder.is_x(axis2[0][1], axis2[1][1]): + return # Parallel + + # Sort axes from interior to exterior + if connection1 == "ATEND": + if axes2[0][0][0] > axes2[-1][0][0]: # We process layers in a +X direction + axes2 = list(reversed(axes2)) + layers2 = list(reversed(layers2)) + elif connection1 == "ATSTART": + if axes2[-1][0][0] > axes2[0][0][0]: # We process layers in a -X direction + axes2 = list(reversed(axes2)) + layers2 = list(reversed(layers2)) + + axis2 = axes2[0] # Take an arbitrary axis of wall2 + if connection2 == "ATSTART": + axis2 = [axis2[1], axis2[0]] # Flip direction so the axis "points" in the direction of join + if axis2[0][1] < axis2[1][1]: # Pointing +Y + if axes1[-1][0][1] < axes1[0][0][1]: # We process layers1 in a +Y direction + axes1 = list(reversed(axes1)) + layers1 = list(reversed(layers1)) + else: # Pointing -Y + if axes1[0][0][1] < axes1[-1][0][1]: # We process layers1 in a -Y direction + axes1 = list(reversed(axes1)) + layers1 = list(reversed(layers1)) + + if connection1 == "ATPATH": + first_axis2 = axes2[0] + last_axis2 = axes2[-1] + first_y = axes1[0][0][1] + last_y = axes1[-1][0][1] + p0 = np.array((ifcopenshell.util.shape_builder.intersect_x_axis_2d(*first_axis2, y=first_y), first_y)) + pN = np.array((ifcopenshell.util.shape_builder.intersect_x_axis_2d(*last_axis2, y=first_y), first_y)) + + # Generate CurveOnRelating/RelatedElement + points = [p0] + axes2 = iter(axes2) + axis2 = next(axes2) + for layer2 in layers2: + ys = iter([a[0][1] for a in axes1]) + y = next(ys) + for layer1 in layers1: + if layer2.priority <= layer1.priority: + break + y = next(ys) + p1 = np.array((ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y), y)) + axis2 = next(axes2) + p2 = np.array((ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y), y)) + if points and np.allclose(points[-1], p1): + points[-1] = p2 # Just slide along previous point + else: + points.extend((p1, p2)) + + # The curve must end at pN + if not np.allclose(points[-1], pN): + points.append(pN) + + # Categorise our points into a segment that either splits or cuts the wall + split_ys = {first_y, last_y} + segment = [] + atpath_vector = self.get_join_vector(self.wall_vectors["y"], wall_vectors2["y"]) + self.atpath_points.append((atpath_vector, points)) + for point in points: + segment.append(point) + if len(segment) == 1: # Not enough points to categorise the segment + continue + elif {segment[0][1], segment[-1][1]} == split_ys: # This segment splits the wall + if segment[0][1] > segment[-1][1]: # Go in the +Y direction + segment.reverse() + self.split_points.append(segment) + segment = [] + elif segment[0][1] == segment[-1][1]: # This segment cuts some of the wall + if segment[0][1] == self.maxy: # Go in the +X direction + if segment[0][0] > segment[-1][0]: + segment.reverse() + self.maxpath_points.append(segment) + elif segment[0][1] == self.miny: # Go in the -X direction + if segment[-1][0] > segment[0][0]: + segment.reverse() + self.minpath_points.append(segment) + segment = [] + elif connection2 == "ATPATH": + points = [] + ys = iter([a[0][1] for a in axes1]) + y = next(ys) + for layer1 in layers1: + axes2_iter = iter(axes2) + axis2 = next(axes2_iter) + for layer2 in layers2: + if layer1.priority <= layer2.priority: + break + axis2 = next(axes2_iter) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y) + p1 = np.array((x, y)) + y = next(ys) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y) + p2 = np.array((x, y)) + if points and np.allclose(points[-1], p1): + points.append(p2) + else: + points.extend((p1, p2)) + + if connection1 == "ATSTART": + self.start_points = points + self.start_vector = self.get_join_vector(self.wall_vectors["y"], wall_vectors2["y"]) + self.start_offset = (self.start_vector * (self.wall_vectors["h"] / self.start_vector[2]))[0] + self.reference_p1[0] = ifcopenshell.util.shape_builder.intersect_x_axis_2d( + *reference2, y=reference1[0][1] + ) + elif connection1 == "ATEND": + self.end_points = points + self.end_vector = self.get_join_vector(self.wall_vectors["y"], wall_vectors2["y"]) + self.end_offset = (self.end_vector * (self.wall_vectors["h"] / self.end_vector[2]))[0] + self.reference_p2[0] = ifcopenshell.util.shape_builder.intersect_x_axis_2d( + *reference2, y=reference1[0][1] + ) + else: # A connection at either end of both walls + last_y = axes1[-1][0][1] + ys = iter([a[0][1] for a in axes1]) + + last_axis2 = axes2[-1] + axes2 = iter(axes2) + axis2 = next(axes2) + y = next(ys) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y) + points = [np.array((x, y))] + + layers1 = iter(layers1) + layers2 = iter(layers2) + layer1 = next(layers1, None) + layer2 = next(layers2, None) + + # This creates "mitering" behaviour which is an ambiguity by bSI. + while layer1 and layer2: + if layer1.priority > layer2.priority: + axis2 = next(axes2) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y) + layer2 = next(layers2, None) + elif layer2.priority > layer1.priority: + y = next(ys) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*axis2, y=y) + layer1 = next(layers1, None) + else: + y = next(ys) + x = ifcopenshell.util.shape_builder.intersect_x_axis_2d(*next(axes2), y=y) + layer1 = next(layers1, None) + layer2 = next(layers2, None) + points.append(np.array((x, y))) + + if points[-1][1] != last_y: + points.append( + np.array((ifcopenshell.util.shape_builder.intersect_x_axis_2d(*last_axis2, y=last_y), last_y)) + ) + + if connection1 == "ATSTART": + self.start_points = points + self.start_vector = self.get_join_vector(self.wall_vectors["y"], wall_vectors2["y"]) + self.start_offset = (self.start_vector * (self.wall_vectors["h"] / self.start_vector[2]))[0] + self.reference_p1[0] = ifcopenshell.util.shape_builder.intersect_x_axis_2d( + *reference2, y=reference1[0][1] + ) + elif connection1 == "ATEND": + self.end_points = points + self.end_vector = self.get_join_vector(self.wall_vectors["y"], wall_vectors2["y"]) + self.end_offset = (self.end_vector * (self.wall_vectors["h"] / self.end_vector[2]))[0] + self.reference_p2[0] = ifcopenshell.util.shape_builder.intersect_x_axis_2d( + *reference2, y=reference1[0][1] + ) + + def get_layers(self, wall) -> list: + material = ifcopenshell.util.element.get_material(wall, should_skip_usage=True) + if not material or not material.is_a("IfcMaterialLayerSet"): + return [] + return [PrioritisedLayer(getattr(l, "Priority", 0) or 0, l.LayerThickness) for l in material.MaterialLayers] + + def combine_layers(self, layers, override_priorities): + results = [] + if override_priorities: + for i, priority in enumerate(override_priorities[: len(layers)]): + layers[i][0] = priority + if not layers: + return [] + results = [layers.pop(0)] + for layer in layers: + if not layer.thickness: + continue + if layer.priority == results[-1].priority: + results[-1] = PrioritisedLayer(layer.priority, results[-1].thickness + layer.thickness) + else: + results.append(layer) + return results + + def get_wall_vectors(self, wall): + if body := ifcopenshell.util.representation.get_representation(wall, "Model", "Body", "MODEL_VIEW"): + for item in ifcopenshell.util.representation.resolve_representation(body).Items: + while item.is_a("IfcBooleanResult"): + item = item.FirstOperand + if item.is_a("IfcExtrudedAreaSolid"): + z = np.array(item.ExtrudedDirection.DirectionRatios) + z /= np.linalg.norm(z) + y = np.cross(z, np.array((1.0, 0.0, 0.0))) + d = item.Depth + h = (z * d)[2] + a = ifcopenshell.util.shape_builder.np_angle_signed(np.array((0.0, 1.0)), z[1:]) + if not ifcopenshell.util.shape_builder.is_x(a, 0): + self.is_angled = True + return {"z": z, "y": y, "a": a, "d": d, "h": h} + elif self.fallback_angle: + a = self.fallback_angle + z = np.array([0.0, sin(a), cos(a)]) + y = np.cross(z, np.array((1.0, 0.0, 0.0))) + h = self.fallback_height + d = np.linalg.norm(z * (h / z[2])) + if not ifcopenshell.util.shape_builder.is_x(a, 0): + self.is_angled = True + return {"z": z, "y": y, "a": a, "d": d, "h": h} + return { + "z": np.array((0.0, 0.0, 1.0)), + "y": np.array((0.0, 1.0, 0.0)), + "a": 0.0, + "d": self.fallback_height, + "h": self.fallback_height, + } + + def get_join_vector(self, y1, y2): + result = np.cross(y1, y2) + if result[2] < 0: + return result * -1 + return result + + def get_axes(self, wall: ifcopenshell.entity_instance, reference, layers: list[PrioritisedLayer], angle: float): + axes = [[p.copy() for p in reference]] + # Apply usage to convert the Reference line into MlsBase + sense_factor = 1 + if (usage := ifcopenshell.util.element.get_material(wall)) and usage.is_a("IfcMaterialLayerSetUsage"): + for point in axes[0]: + point[1] += usage.OffsetFromReferenceLine + sense_factor = 1 if usage.DirectionSense == "POSITIVE" else -1 + + for layer in layers: + y_offset = (layer.thickness * sense_factor) / cos(angle) + axes.append([p.copy() + np.array((0.0, y_offset)) for p in axes[-1]]) + return axes + + def get_manual_booleans(self, element: ifcopenshell.entity_instance): + if pset := ifcopenshell.util.element.get_pset(element, "BBIM_Boolean"): + try: + return [self.file.by_id(boolean_id) for boolean_id in json.loads(pset["Data"])] + except: + return [] + return [] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_boolean.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_boolean.py new file mode 100644 index 0000000000000000000000000000000000000000..bf844838c348dcafa7921906cf43df0b5ce1f974 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_boolean.py @@ -0,0 +1,61 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element + + +def remove_boolean(file: ifcopenshell.file, item: ifcopenshell.entity_instance) -> None: + """Removes a boolean operation without deleting the operands + + The first operand will replace the boolean result itself, and the second + operand will be reset as a top level representation item. + + This may affect the Items of IfcShapeRepresentation, so it is recommended + to run :func:`ifcopenshell.api.geometry.validate_type` after all boolean + modifications are complete. + + :param item: This may either be an IfcBooleanResult or an + IfcRepresentationItem that is participating in one or more boolean + results (in which case all are removed). + """ + if not item.is_a("IfcBooleanResult"): + for inverse in file.get_inverse(item): + if inverse.is_a("IfcBooleanResult"): + remove_boolean(file, inverse) + return + + representations = [] + queue = list(file.get_inverse(item)) + while queue: + inverse = queue.pop() + if inverse.is_a("IfcShapeRepresentation"): + representations.append(inverse) + elif inverse.is_a("IfcBooleanResult"): + queue.extend(file.get_inverse(inverse)) + elif inverse.is_a("IfcCsgSolid"): + queue.extend(file.get_inverse(inverse)) + + first = item.FirstOperand + second = item.SecondOperand + for inverse in file.get_inverse(item): + ifcopenshell.util.element.replace_attribute(inverse, item, first) + + for representation in set(representations): + representation.Items = list(representation.Items) + [second] + + file.remove(item) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..6262060fa7169ca8877622a25218a42860a91d11 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/remove_representation.py @@ -0,0 +1,92 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element + + +def remove_representation( + file: ifcopenshell.file, representation: ifcopenshell.entity_instance, should_keep_named_profiles: bool = True +) -> None: + """Remove a representation. + + Also purges representation items and their related elements + like IfcStyledItem, tessellated facesets colours and UV map. + + By default, named profiles are assumed to be significant (i.e. curated as + part of a profile library) and will not be removed. + + :param representation: IfcRepresentation to remove. + Note that it's expected that IfcRepresentation won't be in use + before calling this method (in such elements as IfcProductRepresentation, IfcShapeAspect) + otherwise representation won't be removed. + :param should_keep_named_profiles: If true, named profile defs will not be + removed as they are assumed to be significant. + """ + is_ifc2x3 = file.schema == "IFC2X3" + styled_items = set() + presentation_layer_assignments_items: set[ifcopenshell.entity_instance] = set() + presentation_layer_assignments_reps: set[ifcopenshell.entity_instance] = set() + textures: set[ifcopenshell.entity_instance] = set() + colours: set[ifcopenshell.entity_instance] = set() + named_profiles: set[ifcopenshell.entity_instance] = set() + for subelement in file.traverse(representation): + if subelement.is_a("IfcRepresentationItem"): + [styled_items.add(s) for s in subelement.StyledByItem or []] + # IFC2X3 is using LayerAssignments + for s in subelement.LayerAssignment if not is_ifc2x3 else subelement.LayerAssignments: + presentation_layer_assignments_items.add(s) + # IfcTessellatedFaceSet inverses + if subelement.is_a("IfcTessellatedFaceSet"): + textures.update(subelement.HasTextures) + colours.update(subelement.HasColours) + elif subelement.is_a("IfcRepresentation"): + for layer in subelement.LayerAssignments: + presentation_layer_assignments_reps.add(layer) + elif subelement.is_a("IfcProfileDef") and subelement.ProfileName: + named_profiles.add(subelement) + + do_not_delete = file.by_type("IfcGeometricRepresentationContext") + if should_keep_named_profiles: + do_not_delete += named_profiles + + # Order matters - layer assignments may reference representation directly. + also_consider = list(presentation_layer_assignments_reps) + also_consider.extend(presentation_layer_assignments_items - presentation_layer_assignments_reps) + also_consider.extend(styled_items) + also_consider.extend(textures) + ifcopenshell.util.element.remove_deep2( + file, + representation, + also_consider=also_consider, + do_not_delete=set(do_not_delete), + ) + + for texture in textures: + ifcopenshell.util.element.remove_deep2(file, texture) + for colour in colours: + ifcopenshell.util.element.remove_deep2(file, colour) + + to_delete = file.to_delete or set() + for element in styled_items: + item = element.Item + if not item or item in to_delete: + file.remove(element) + presentation_layer_assignments = presentation_layer_assignments_reps | presentation_layer_assignments_items + for element in presentation_layer_assignments: + if all(item in to_delete for item in element.AssignedItems): + file.remove(element) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/unassign_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/unassign_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..5dc3bf3aebb5ce19cffa697312815f8acacdc37a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/unassign_representation.py @@ -0,0 +1,112 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.geometry +import ifcopenshell.util.element +from typing import Any + + +def unassign_representation( + file: ifcopenshell.file, product: ifcopenshell.entity_instance, representation: ifcopenshell.entity_instance +) -> None: + usecase = Usecase() + usecase.file = file + usecase.settings = {"product": product, "representation": representation} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self) -> None: + product: ifcopenshell.entity_instance = self.settings["product"] + representation: ifcopenshell.entity_instance = self.settings["representation"] + if product.is_a("IfcProduct"): + self.unassign_product_representation(product, representation) + elif product.is_a("IfcTypeProduct"): + self.unassign_type_representation() + + def unassign_product_representation( + self, product: ifcopenshell.entity_instance, representation: ifcopenshell.entity_instance + ) -> None: + representations = list(product.Representation.Representations or []) + if representation not in representations: + return + representations.remove(representation) + if not representations: + product_def = product.Representation + # TODO: should somehow find matching shape aspect and remove it + # even before the last representation is removed. + self.process_shape_aspects(product_def) + self.file.remove(product_def) + else: + product.Representation.Representations = representations + + def unassign_type_representation(self) -> None: + matching_representation_map = None + + for representation_map in self.settings["product"].RepresentationMaps or []: + if representation_map.MappedRepresentation == self.settings["representation"]: + matching_representation_map = representation_map + break + + if matching_representation_map: + self.unassign_products_using_mapped_representation(matching_representation_map) + self.settings["product"].RepresentationMaps = [ + rm for rm in self.settings["product"].RepresentationMaps if rm != matching_representation_map + ] or None + self.process_shape_aspects(matching_representation_map) + self.remove_representation_map_only(matching_representation_map) + + def process_shape_aspects(self, product_representation: ifcopenshell.entity_instance) -> None: + # Technically IfcShapeAspect doesn't become invalid when product representation is removed, + # but shape aspect makes sense only in context of some other representation. + if self.file.schema == "IFC2X3" and product_representation.is_a("IfcRepresentationMap"): + shape_aspects = [ + a + for a in self.file.by_type("IfcShapeAspect") + if a.PartOfProductDefinitionShape == product_representation + ] + else: + shape_aspects = product_representation.HasShapeAspects + for shape_aspect in shape_aspects: + representations = shape_aspect.ShapeRepresentations + self.file.remove(shape_aspect) + for rep in representations: + ifcopenshell.api.geometry.remove_representation(self.file, rep) + + def remove_representation_map_only(self, representation_map: ifcopenshell.entity_instance) -> None: + representation_map.MappedRepresentation = self.file.createIfcShapeRepresentation() + ifcopenshell.util.element.remove_deep2(self.file, representation_map) + + def unassign_products_using_mapped_representation(self, representation_map: ifcopenshell.entity_instance) -> None: + mapped_representations: list[dict[str, ifcopenshell.entity_instance]] = [] + just_representations: list[ifcopenshell.entity_instance] = [] + for map_usage in representation_map.MapUsage or []: + for inverse in self.file.get_inverse(map_usage): + if not inverse.is_a("IfcShapeRepresentation"): + continue + for definition in inverse.OfProductRepresentation or []: + for product in definition.ShapeOfProduct or []: + mapped_representations.append({"product": product, "representation": inverse}) + just_representations.append(inverse) + for item in mapped_representations: + self.unassign_product_representation(item["product"], item["representation"]) + for representation in just_representations: + ifcopenshell.api.geometry.remove_representation(self.file, representation=representation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/validate_type.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/validate_type.py new file mode 100644 index 0000000000000000000000000000000000000000..b5970e4d44a5b20903ada6e8faf3da8565386f53 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/geometry/validate_type.py @@ -0,0 +1,89 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2025 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.geometry +import ifcopenshell.util.representation +from typing import Union + + +def validate_type( + file: ifcopenshell.file, + representation: ifcopenshell.entity_instance, + preferred_item: Union[ifcopenshell.entity_instance, None] = None, +) -> bool: + """Validates the RepresentationType of an IfcShapeRepresentation + + A shape representation has to identify its geometry using the + RepresentationType attribute. For example, if it holds tessellated + geometry, it should store "Tessellation" as its RepresentationType. + + This function checks whether or not the RepresentationType is valid. This + is a wrapper around :func:`ifcopenshell.util.representation.guess_type`. It + will then set RepresentationType to the most appropriate value, or return + False otherwise. In addition, it also attempts to reconcile otherwise + invalid CSG geometry by unioning all remaining top level items to existing + boolean results. + + :param representation: The IfcShapeRepresentation with Items + :param preferred_item: If the type is expected to be a CSG, this will be + the preferred item to union all remaining items to. If no preferred + item is provided, the first boolean result will be chosen. + :return: True if the representation type was set and it is a valid + combination, or False otherwise. + """ + + def is_operand(item: ifcopenshell.entity_instance) -> bool: + return ( + item.is_a("IfcBooleanResult") + or item.is_a("IfcCsgPrimitive3D") + or item.is_a("IfcHalfSpaceSolid") + or item.is_a("IfcSolidModel") + or item.is_a("IfcTessellatedFaceSet") + ) + + has_boolean = False + remaining_items = [] + for item in representation.Items: + if item.is_a("IfcBooleanResult"): + has_boolean = True + if item != preferred_item and is_operand(item): + remaining_items.append(item) + + if not has_boolean: + result = ifcopenshell.util.representation.guess_type(representation.Items) + if result: + representation.RepresentationType = result + return True + return False + + if not preferred_item: + # Prioritise an existing boolean result + for i in remaining_items: + if i.is_a("IfcBooleanResult"): + preferred_item = i + break + if not preferred_item and remaining_items: + preferred_item = remaining_items[0] + + if remaining_items: + ifcopenshell.api.geometry.add_boolean(file, preferred_item, remaining_items, "UNION") + + representation.RepresentationType = ifcopenshell.util.representation.guess_type(representation.Items) + if representation.RepresentationType == "CSG": + return True + return False diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ffe0306db1c54efc57168a6c89e2428886d1ba83 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/__init__.py @@ -0,0 +1,41 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Manage georeferencing metadata + +IFC model geometry may have a coordinate reference system (CRS) assigned to it. +It may also optionally have a map conversion defined to transform to and from +map coordinates and project local engineering coordinates. +""" + +from .. import wrap_usecases +from .add_georeferencing import add_georeferencing +from .edit_georeferencing import edit_georeferencing +from .edit_true_north import edit_true_north +from .edit_wcs import edit_wcs +from .remove_georeferencing import remove_georeferencing + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_georeferencing", + "edit_georeferencing", + "edit_true_north", + "edit_wcs", + "remove_georeferencing", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/add_georeferencing.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/add_georeferencing.py new file mode 100644 index 0000000000000000000000000000000000000000..43ccaea2bca793653e5ce2a670266a94a5f2854f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/add_georeferencing.py @@ -0,0 +1,99 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.pset +import ifcopenshell.util.element + + +def add_georeferencing(file: ifcopenshell.file, ifc_class: str = "IfcMapConversion", name: str = "EPSG:3857") -> None: + """Add empty georeferencing entities to a model + + By default, models are not georeferenced. Georeferencing requires two + entities: a definition of the projected coordinated reference system + (CRS) used, and the transformation parameters between any local coordinate + system and that projected CRS if any. + + This function will create the entities to store the projected CRS and + map conversion transformation, but will leave all the parameters blank. + It is this the users responsibility to specify the correct + georeferencing parameters. See + ifcopenshell.api.georeference.edit_georeferencing. + + :param ifc_class: A type of IfcCoordinateOperation. For IFC2X3, this has no + impact and only uses ePSet_MapConversion. + + Example: + + .. code:: python + + ifcopenshell.api.georeference.add_georeferencing(model) + """ + if file.schema == "IFC2X3": + if not (project := file.by_type("IfcProject")): + return + project = project[0] + if ifcopenshell.util.element.get_pset(project, "ePSet_ProjectedCRS"): + return + conversion = ifcopenshell.api.pset.add_pset(file, project, "ePSet_MapConversion") + crs = ifcopenshell.api.pset.add_pset(file, project, "ePSet_ProjectedCRS") + ifcopenshell.api.pset.edit_pset(file, crs, properties={"Name": name}) + ifcopenshell.api.pset.edit_pset( + file, + conversion, + properties={ + "Eastings": file.createIfcLengthMeasure(0), + "Northings": file.createIfcLengthMeasure(0), + "OrthogonalHeight": file.createIfcLengthMeasure(0), + }, + ) + return + if file.by_type("IfcProjectedCRS"): + return + source_crs = None + for context in file.by_type("IfcGeometricRepresentationContext", include_subtypes=False): + if context.ContextType == "Model": + source_crs = context + break + if not source_crs: + return + projected_crs = file.create_entity("IfcProjectedCRS", Name=name) + if ifc_class == "IfcMapConversion": + file.create_entity( + ifc_class, SourceCRS=source_crs, TargetCRS=projected_crs, Eastings=0, Northings=0, OrthogonalHeight=0 + ) + elif ifc_class == "IfcMapConversionScaled": + file.create_entity( + ifc_class, + SourceCRS=source_crs, + TargetCRS=projected_crs, + Eastings=0, + Northings=0, + OrthogonalHeight=0, + FactorX=1, + FactorY=1, + FactorZ=1, + ) + elif ifc_class == "IfcRigidOperation": + file.create_entity( + ifc_class, + SourceCRS=source_crs, + TargetCRS=projected_crs, + FirstCoordinate=file.createIfcLengthMeasure(0), + SecondCoordinate=file.createIfcLengthMeasure(0), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_georeferencing.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_georeferencing.py new file mode 100644 index 0000000000000000000000000000000000000000..0d4da93bcb683d71c311a782511b931d25bc5283 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_georeferencing.py @@ -0,0 +1,116 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.pset +import ifcopenshell.util.element +from typing import Optional, Any + + +def edit_georeferencing( + file: ifcopenshell.file, + coordinate_operation: Optional[dict[str, Any]] = None, + projected_crs: Optional[dict[str, Any]] = None, +) -> None: + """Edits the attributes of a map conversion, projected CRS, and true north + + Setting the correct georeferencing parameters is a complex topic and + should ideally be done with three parties present: the lead architect, + surveyor, and a third-party digital engineer with expertise in IFC to + moderate. For more information, read the Bonsai documentation + for Georeferencing: + https://docs.bonsaibim.org/guides/authoring/georeferencing.html + + For more information about the attributes and data types of an + IfcCoordinateOperation, consult the IFC documentation. + + For more information about the attributes and data types of an + IfcProjectedCRS, consult the IFC documentation. + + See ifcopenshell.util.geolocation for more utilities to convert to and + from local and map coordinates to check your results. + + :param coordinate_operation: The dictionary of attribute names and values + you want to edit. + 'MapUnit' attribute in IFC2X3 should be presented as a full unit name (string), + in other IFC versions it's presented an IfcNamedUnit. + :param projected_crs: The IfcProjectedCRS dictionary of attribute + names and values you want to edit. + + Example: + + .. code:: python + + ifcopenshell.api.georeference.add_georeferencing(model) + # This is the simplest scenario, a defined CRS (GDA2020 / MGA Zone + # 56, typically used in Sydney, Australia) but with no local + # coordinates. This is only recommended for horizontal construction + # projects, not for vertical construction (such as buildings). + ifcopenshell.api.georeference.edit_georeferencing(model, + projected_crs={"Name": "EPSG:7856"}) + + # For buildings, it is almost always recommended to specify map + # conversion parameters to a false origin and orientation to project + # north. See the diagram in the Bonsai Georeferencing + # documentation for correct calculation of the X Axis Abcissa and + # Ordinate. + ifcopenshell.api.georeference.edit_georeferencing(model, + projected_crs={"Name": "EPSG:7856"}, + coordinate_operation={ + "Eastings": 335087.17, # The architect nominates a false origin + "Northings": 6251635.41, # The architect nominates a false origin + # Note: this is the angle difference between Project North + # and Grid North. Remember: True North should never be used! + "XAxisAbscissa": cos(radians(-30)), # The architect nominates a project north + "XAxisOrdinate": sin(radians(-30)), # The architect nominates a project north + "Scale": 0.99956, # Ask your surveyor for your site's average combined scale factor! + }) + """ + if file.schema == "IFC2X3": + if not (project := file.by_type("IfcProject")): + return + project = project[0] + if projected_crs: + if crs := ifcopenshell.util.element.get_pset(project, "ePSet_ProjectedCRS"): + crs = file.by_id(crs["id"]) + for k, v in projected_crs.items(): + if k == "Description": + v = file.createIfcText(v) + elif k == "Name": + v = file.createIfcLabel(v) + elif v is not None: + v = file.createIfcIdentifier(v) + ifcopenshell.api.pset.edit_pset(file, crs, properties=projected_crs) + if coordinate_operation: + if conversion := ifcopenshell.util.element.get_pset(project, "ePSet_MapConversion"): + conversion = file.by_id(conversion["id"]) + for k, v in coordinate_operation.items(): + if k in ("XAxisAbscissa", "XAxisOrdinate", "Scale"): + v = file.createIfcReal(v) + else: + v = file.createIfcLengthMeasure(v) + ifcopenshell.api.pset.edit_pset(file, conversion, properties=coordinate_operation) + return + if projected_crs: + crs = file.by_type("IfcProjectedCRS")[0] + for name, value in projected_crs.items(): + setattr(crs, name, value) + if coordinate_operation: + conversion = file.by_type("IfcCoordinateOperation")[0] + for name, value in coordinate_operation.items(): + setattr(conversion, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_true_north.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_true_north.py new file mode 100644 index 0000000000000000000000000000000000000000..0a7e967fbd4219cc1fd5a859b061b3263636f91d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_true_north.py @@ -0,0 +1,72 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element +import ifcopenshell.util.geolocation +from typing import Union, Optional + + +def edit_true_north(file: ifcopenshell.file, true_north: Optional[Union[tuple[float, float], float]] = 0.0) -> None: + """Edits the true north + + Given project north being up (i.e. a vector of 0, 1), true north is defined + as a unitised 2D vector pointing to true north. Alternatively, true north + may be defined as a rotation from project north to true north. + Anticlockwise is positive. + + Note that true north is not part of georeferencing, and is only optionally + provided as a reference value, typically for solar analysis. Remember: grid + north (what your surveyor will typically use) is not the same as true + north! + + :param true_north: A unitised 2D vector, where each ordinate is a float, or + an angle in decimal degrees where anticlockwise is positive. + + Example: + + .. code:: python + + # Both of these are identical, and indicate that: + # - If project north is up the page, true north is in the top left + # - The building is therefore facing north east + ifcopenshell.api.georeference.edit_true_north(model, true_north=30) + ifcopenshell.api.georeference.edit_true_north(model, true_north=(-0.5, 0.8660254)) + + # This unsets true north + ifcopenshell.api.georeference.edit_true_north(model, true_north=None) + """ + if isinstance(true_north, (float, int)): + x, y = ifcopenshell.util.geolocation.angle2yaxis(true_north) + elif true_north is not None: + x, y = true_north + + for context in file.by_type("IfcGeometricRepresentationContext", include_subtypes=False): + if context.TrueNorth and true_north is None: + old_true_north = context.TrueNorth + context.TrueNorth = None + if not file.get_total_inverses(old_true_north): + ifcopenshell.util.element.remove_deep2(file, old_true_north) + continue + + if context.TrueNorth: + if file.get_total_inverses(context.TrueNorth) != 1: + context.TrueNorth = file.create_entity("IfcDirection") + else: + context.TrueNorth = file.create_entity("IfcDirection") + context.TrueNorth.DirectionRatios = (x, y) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_wcs.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_wcs.py new file mode 100644 index 0000000000000000000000000000000000000000..25fb4f3b6ea2b01ed7178e48c133bcd8e1b4e97e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/edit_wcs.py @@ -0,0 +1,93 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element +import ifcopenshell.util.unit +import numpy as np +from ifcopenshell.util.shape_builder import ShapeBuilder +from math import sin, cos, radians + + +def edit_wcs( + file: ifcopenshell.file, + x: float = 0.0, + y: float = 0.0, + z: float = 0.0, + rotation: float = 0.0, + is_si: bool = True, +) -> None: + """Edits the WCS for all geometric contexts to a translation and rotation + + Typically, a project's local engineering origin (0, 0, 0) has a coordinate + operation (e.g. map conversion) to a projected CRS. If a WCS is provided, + the coordinate operation is relative to the WCS, not the local engineering + origin. + + For example, if I have an IfcSite with a placement at (10, 0, 0) and a map + conversion of (50, 0, 0), my IfcSite's local XYZ is at (10, 0, 0) with an + ENH (Easting, Northing, Height) of (60, 0, 0). + + If I then define by WCS at (15, 0, 0), my IfcSite's local XYZ is still at + (10, 0, 0) but its ENH is now at (45, 0, 0). + + It's recommended to leave the WCS at 0,0,0. Please :) + + :param x: The X translation of the WCS + :param y: The Y translation of the WCS + :param z: The Z translation of the WCS + :param rotation: The rotation around the Z axis (i.e. top down plan view) + in decimal degrees of the WCS. Anticlockwise is positive. + + Example: + + .. code:: python + + # This is the simplest scenario, resetting the WCS to 0,0,0 with no rotation (recommended) + ifcopenshell.api.georeference.edit_wcs(model) + """ + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) + builder = ShapeBuilder(file) + if np.isclose(rotation, 0): + xaxis_x = 1.0 + xaxis_y = 0.0 + else: + xaxis_x = cos(radians(rotation)) + xaxis_y = sin(radians(rotation)) + if np.allclose((x, y, z), (0, 0, 0)): + x = y = z = 0.0 + for context in file.by_type("IfcGeometricRepresentationContext", include_subtypes=False): + old_wcs = context.WorldCoordinateSystem + if context.CoordinateSpaceDimension == 3: + if is_si: + xyz = (x / unit_scale, y / unit_scale, z / unit_scale) + else: + xyz = (x, y, z) + placement = builder.create_axis2_placement_3d(xyz, (0.0, 0.0, 1.0), (xaxis_x, xaxis_y, 0.0)) + elif context.CoordinateSpaceDimension == 2: + if is_si: + point = file.createIfcCartesianPoint((x / unit_scale, y / unit_scale)) + else: + point = file.createIfcCartesianPoint((x, y)) + placement = file.createIfcAxis2Placement2D( + point, + file.createIfcDirection((xaxis_x, xaxis_y)), + ) + context.WorldCoordinateSystem = placement + if file.get_total_inverses(old_wcs) == 0: + ifcopenshell.util.element.remove_deep2(file, old_wcs) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/remove_georeferencing.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/remove_georeferencing.py new file mode 100644 index 0000000000000000000000000000000000000000..3cbcae5d60a1c1492b0b3d2fb9b33619c7ea1bf5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/georeference/remove_georeferencing.py @@ -0,0 +1,51 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.pset +import ifcopenshell.util.element + + +def remove_georeferencing(file: ifcopenshell.file) -> None: + """Remove georeferencing data + + All georeferencing parameters such as projected CRS and map conversion + data will be lost. + + In IFC2X3, the psets will be removed from the IfcProject. + + Example: + + ifcopenshell.api.georeference.add_georeferencing(model) + # Let's change our mind + ifcopenshell.api.georeference.remove_georeferencing(model) + """ + if file.schema == "IFC2X3": + project = file.by_type("IfcProject")[0] + if pset := ifcopenshell.util.element.get_pset(project, "ePSet_ProjectedCRS"): + ifcopenshell.api.pset.remove_pset(file, project, file.by_id(pset["id"])) + if pset := ifcopenshell.util.element.get_pset(project, "ePSet_MapConversion"): + ifcopenshell.api.pset.remove_pset(file, project, file.by_id(pset["id"])) + return + for projected_crs in file.by_type("IfcProjectedCRS"): + if (unit := projected_crs.MapUnit) and file.get_total_inverses(unit) == 1: + projected_crs.MapUnit = None + ifcopenshell.util.element.remove_deep2(file, unit) + file.remove(projected_crs) + for coordinate_operation in file.by_type("IfcCoordinateOperation"): + file.remove(coordinate_operation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..cc759ce7e09cc0515c4086daea2625b9f74ad0a1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/__init__.py @@ -0,0 +1,36 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Manages grid and grid axes + +A grid in IFC may contain two or more axes running in two or more directions. +""" + +from .. import wrap_usecases + +from .create_axis_curve import create_axis_curve +from .create_grid_axis import create_grid_axis +from .remove_grid_axis import remove_grid_axis + +wrap_usecases(__path__, __name__) + +__all__ = [ + "create_axis_curve", + "create_grid_axis", + "remove_grid_axis", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_axis_curve.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_axis_curve.py new file mode 100644 index 0000000000000000000000000000000000000000..b87eea94d094545d3c252005b3294f9fa6b828fd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_axis_curve.py @@ -0,0 +1,85 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import ifcopenshell +import ifcopenshell.util.element +import ifcopenshell.util.unit +import ifcopenshell.util.placement +import numpy as np +from ifcopenshell.util.shape_builder import VectorType, V, ifc_safe_vector_type, np_apply_matrix + + +def create_axis_curve( + file: ifcopenshell.file, + *, + p1: VectorType, + p2: VectorType, + grid_axis: ifcopenshell.entity_instance, + is_si: bool = True, +) -> None: + """Adds curve geometry to a grid axis to represent the axis extents + + An IFC grid will have a minimum of two axes (typically perpendicular). Each + axis will then have a line which represents the extents of the axis. + + Points are provided as 3D coordinates in world space. + During axis creation, the coordinates will be localized relative to IfcGrid + and saved as 2D. + + :param p1: The first point of the grid axis + :param p2: The second point of the grid axis + :param grid_axis: The IfcGridAxis element to add geometry to. + :param is_si: If true, the points are in meters, not project units + + Example: + + .. code:: python + + # A pretty standard rectangular grid, with only two axes. + grid = ifcopenshell.api.root.create_entity(model, ifc_class="IfcGrid") + axis_a = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="A", uvw_axes="UAxes", grid=grid) + axis_1 = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="1", uvw_axes="VAxes", grid=grid) + + # By convention, alphabetic grids are horizontal, and numeric are vertical + ifcopenshell.api.grid.create_axis_curve( + model, p1=np.array((0., 0., 0.)), p2=np.array((10., 0., 0.)), grid_axis=axis_a) + ifcopenshell.api.grid.create_axis_curve( + model, p1=np.array((0., 0., 0.)), p2=np.array((0., 10., 0.)), grid_axis=axis_1) + """ + existing_curve = grid_axis.AxisCurve + points = V([p1, p2]) + if is_si: + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) + points /= unit_scale + + grid = next(i for i in file.get_inverse(grid_axis) if i.is_a("IfcGrid")) + grid_matrix_i = np.linalg.inv(ifcopenshell.util.placement.get_local_placement(grid.ObjectPlacement)) + p1, p2 = ifc_safe_vector_type(np_apply_matrix(points, grid_matrix_i)) + grid_axis.AxisCurve = file.create_entity( + "IfcPolyline", + ( + file.create_entity("IfcCartesianPoint", p1[:2]), + file.create_entity("IfcCartesianPoint", p2[:2]), + ), + ) + + if existing_curve: + ifcopenshell.util.element.remove_deep2(file, existing_curve) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_grid_axis.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_grid_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..77228434b087e95a558f9091150b9d9b9d43e987 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/create_grid_axis.py @@ -0,0 +1,77 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Optional, Literal + + +def create_grid_axis( + file: ifcopenshell.file, + grid: ifcopenshell.entity_instance, + axis_tag: str = "A", + same_sense: bool = True, + uvw_axes: Literal["UAxes", "VAxes", "WAxes"] = "UAxes", +) -> ifcopenshell.entity_instance: + """Adds a new grid axis to a grid + + An IFC grid will typically have a minimum of two axes which will be + perpendicular to one another. Grids may be rectangular (typically + perpendicular lines), radial (where one set of axes is a circle and the + other is a line), or triangular (three sets of axes, each at a different + angle to one another). + + For a simple rectangular grid, the "UAxes" are a set of one or more + horizontal axes, which are typically labeled with the convention of A, + B, C, etc. The "VAxes" is another set of one or more vertical axes, + typically labeled with the convention of 1, 2, 3, etc. These axes are + horizontal or vertical relative to project north. + + For a radial grid, the "UAxes" are straight lines, typically radiating + from a central point. The "VAxes" are circular perimeters, with the + center of these circles being the same central point. + + For a triangular grid, the UAxes, VAxes, and WAxes are all sets of one + or more straight lines. + + :param axis_tag: The name of the axis, that would typically be labeled + on drawings or described on site during coordination, such as A, B, + C, 1, 2, 3, etc. Defaults to "A". + :param same_sense: Determines whether the direction of the axis's line + is reversed. True means the direction the geometry is defined in + represents the direction of the axis. False means the direction is + reversed. Leave as True if unsure. Defaults to "True". + :param uvw_axes: Choose from "UAxes", "VAxes" or "WAxes" depending on + which set of axes the new axis you are adding should belong to. + Defaults to "UAxes". + :param grid: The IfcGrid you are adding the axis to. + :return: The newly created IfcGridAxis + + Example: + + # A pretty standard rectangular grid, with only two axes. + grid = ifcopenshell.api.root.create_entity(model, ifc_class="IfcGrid") + axis_a = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="A", uvw_axes="UAxes", grid=grid) + axis_1 = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="1", uvw_axes="VAxes", grid=grid) + """ + + element = file.create_entity("IfcGridAxis", **{"AxisTag": axis_tag, "SameSense": same_sense}) + axes = list(getattr(grid, uvw_axes) or []) + axes.append(element) + setattr(grid, uvw_axes, axes) + return element diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/remove_grid_axis.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/remove_grid_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..652fc89f56e14135acd5535ce661d6401935a2df --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/grid/remove_grid_axis.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element + + +def remove_grid_axis(file: ifcopenshell.file, axis: ifcopenshell.entity_instance) -> None: + """Removes a grid axis from a grid + + :param axis: The IfcGridAxis you want to remove. + :return: None + + Example: + + # A pretty standard rectangular grid, with only two axes. + grid = ifcopenshell.api.root.create_entity(model, ifc_class="IfcGrid") + axis_a = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="A", uvw_axes="UAxes", grid=grid) + axis_1 = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="1", uvw_axes="VAxes", grid=grid) + + # Let's create a third so we can remove it later + axis_2 = ifcopenshell.api.grid.create_grid_axis(model, + axis_tag="2", uvw_axes="VAxes", grid=grid) + + # Let's remove it! + ifcopenshell.api.grid.remove_grid_axis(model, axis=axis_2) + """ + axis_curve = axis.AxisCurve + if file.get_total_inverses(axis_curve) == 1: + ifcopenshell.util.element.remove_deep(file, axis_curve) + file.remove(axis_curve) + file.remove(axis) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e89610017e785d5f12ef379524150838eeed0b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/__init__.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Elements may be arbitrarily assigned to groups for organisation + +Groups are useful for filtering elements or non-hierarchical organisation of a +model. Note that this only targets arbitrary groups. If you want to group +elements into a distribution system, see :mod:`ifcopenshell.api.system`. +""" + +from .. import wrap_usecases +from .add_group import add_group +from .assign_group import assign_group +from .edit_group import edit_group +from .remove_group import remove_group +from .unassign_group import unassign_group +from .update_group_products import update_group_products + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_group", + "assign_group", + "edit_group", + "remove_group", + "unassign_group", + "update_group_products", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/add_group.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/add_group.py new file mode 100644 index 0000000000000000000000000000000000000000..a2a877ef6ebaba90a297c156d56637263c1beba7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/add_group.py @@ -0,0 +1,55 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +from typing import Optional + + +def add_group( + file: ifcopenshell.file, name: str = "Unnamed", description: Optional[str] = None +) -> ifcopenshell.entity_instance: + """Adds a new group + + An IFC group is an arbitrary collection of products, which are typically + physical. It may be used when there is no other more specific group + which may be used. Other types of groups include distribution systems, + which group together products that are connected and circulate a medium + (such as fluid or electricity), or zones, which group together spaces, + or structural load groups, which group together loads for structural + analysis, or inventories, which are groups of assets. + + :param name: The name of the group. Defaults to "Unnamed" + :param description: The description of the purpose of the group. + :return: The newly created IfcGroup + + Example: + + .. code:: python + + ifcopenshell.api.group.add_group(model, name="Unit 1A") + """ + + return file.create_entity( + "IfcGroup", + GlobalId=ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(file), + Name=name, + Description=description, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/assign_group.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/assign_group.py new file mode 100644 index 0000000000000000000000000000000000000000..cb9cd95fea426e7e25eb42d0257012f887aa6921 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/assign_group.py @@ -0,0 +1,67 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +from typing import Union + + +def assign_group( + file: ifcopenshell.file, products: list[ifcopenshell.entity_instance], group: ifcopenshell.entity_instance +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns products to a group + + If a product is already assigned to the group, it will not be assigned + twice. + + :param products: A list of IfcProduct elements to assign to the group + :param group: The IfcGroup to assign the products to + :return: The IfcRelAssignsToGroup relationship + or `None` if `products` was empty list. + + Example: + + .. code:: python + + group = ifcopenshell.api.group.add_group(model, name="Furniture") + ifcopenshell.api.group.assign_group(model, + products=model.by_type("IfcFurniture"), group=group) + """ + if not products: + return + + is_grouped_by: tuple[ifcopenshell.entity_instance, ...] + if not (is_grouped_by := group.IsGroupedBy): + return file.create_entity( + "IfcRelAssignsToGroup", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": products, + "RelatingGroup": group, + }, + ) + rel = is_grouped_by[0] + related_objects = set(rel.RelatedObjects) or set() + products_set = set(products) + if products_set.issubset(related_objects): + return rel + rel.RelatedObjects = list(related_objects | products_set) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + return rel diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/edit_group.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/edit_group.py new file mode 100644 index 0000000000000000000000000000000000000000..5a7a2b20181998b51fa2d1d571876a2d5a2b758d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/edit_group.py @@ -0,0 +1,41 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_group(file: ifcopenshell.file, group: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcGroup + + For more information about the attributes and data types of an + IfcGroup, consult the IFC documentation. + + :param group: The IfcGroup entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + group = ifcopenshell.api.group.add_group(model, name="Unit 1A") + ifcopenshell.api.group.edit_group(model, + group=group, attributes={"Description": "All furniture and joinery included in the unit"}) + """ + for name, value in attributes.items(): + setattr(group, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/remove_group.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/remove_group.py new file mode 100644 index 0000000000000000000000000000000000000000..2916a7cb32f43735e905e0005d5903216086f4e2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/remove_group.py @@ -0,0 +1,65 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.pset +import ifcopenshell.util.element + + +def remove_group(file: ifcopenshell.file, group: ifcopenshell.entity_instance) -> None: + """Removes a group + + All products assigned to the group will remain, but the relationship to + the group will be removed. + + :param group: The IfcGroup entity you want to remove + :return: None + + Example: + + .. code:: python + + group = ifcopenshell.api.group.add_group(model, name="Unit 1A") + ifcopenshell.api.group.remove_group(model, group=group) + """ + for inverse_id in [i.id() for i in file.get_inverse(group)]: + try: + inverse = file.by_id(inverse_id) + except: + continue + if inverse.is_a("IfcRelDefinesByProperties"): + ifcopenshell.api.pset.remove_pset( + file, + product=group, + pset=inverse.RelatingPropertyDefinition, + ) + elif inverse.is_a("IfcRelAssignsToGroup"): + if inverse.RelatingGroup == group: + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + elif len(inverse.RelatedObjects) == 1: + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + history = group.OwnerHistory + file.remove(group) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/unassign_group.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/unassign_group.py new file mode 100644 index 0000000000000000000000000000000000000000..198361e78d3f65e112820b3e7ecf762d1f5a7b75 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/unassign_group.py @@ -0,0 +1,59 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_group( + file: ifcopenshell.file, products: list[ifcopenshell.entity_instance], group: ifcopenshell.entity_instance +) -> None: + """Unassigns products from a group + + If the product isn't assigned to the group, nothing will happen. + + :param products: A list of IfcProduct elements to unassign from the group + :param group: The IfcGroup to unassign from + :return: None + + Example: + + .. code:: python + + group = ifcopenshell.api.group.add_group(model, name="Furniture") + furniture = model.by_type("IfcFurniture") + ifcopenshell.api.group.assign_group(model, products=furniture, group=group) + + bad_furniture = furniture[0] + ifcopenshell.api.group.unassign_group(model, products=[bad_furniture], group=group) + """ + if not group.IsGroupedBy: + return + rel = group.IsGroupedBy[0] + related_objects = set(rel.RelatedObjects) or set() + products_set = set(products) + related_objects -= products_set + if related_objects: + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/update_group_products.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/update_group_products.py new file mode 100644 index 0000000000000000000000000000000000000000..e033ebe8faaf84b0d3055fbc2d7c4b6a0287f7dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/group/update_group_products.py @@ -0,0 +1,69 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element + + +def update_group_products( + file: ifcopenshell.file, group: ifcopenshell.entity_instance, products: list[ifcopenshell.entity_instance] +) -> ifcopenshell.entity_instance: + """Sets a group products to be an explicit list of products + + Any previous products assigned to that group will have their assignment + removed. + + :param products: A list of IfcProduct elements to assign to the group + :param group: The IfcGroup to assign the products to + :return: The IfcRelAssignsToGroup relationship + + Example: + + .. code:: python + + group = ifcopenshell.api.group.add_group(model, name="Furniture") + ifcopenshell.api.group.update_group_products(model, + products=model.by_type("IfcFurniture"), group=group) + """ + if not group.IsGroupedBy: + return file.create_entity( + "IfcRelAssignsToGroup", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": products, + "RelatingGroup": group, + } + ) + else: + rels = group.IsGroupedBy + objects = set(products) + for rel in rels: + objects.update([g for g in rel.RelatedObjects if g.is_a("IfcGroup")]) + to_purge = rels[1:] + + for rel in to_purge: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + rels[0].RelatedObjects = list(objects) + return rels[0] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_layer.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..5fae2ed275dd46b88d687ef25bc8d1f5e1489b56 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_layer.py @@ -0,0 +1,94 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +import ifcopenshell.util.unit +from typing import Optional + + +def add_layer( + file: ifcopenshell.file, + layer_set: ifcopenshell.entity_instance, + material: ifcopenshell.entity_instance, + name: Optional[str] = None, +) -> ifcopenshell.entity_instance: + """Adds a new layer to a layer set + + A layer represents a portion of material within a layered build up, + defined by a thickness. Typical layered construction includes walls and + slabs, where a wall might include a layer of finish, a layer of + structure, a layer of insulation, and so on. It is recommended to define + layered construction this way where it is unnecessary to define the + exact geometry of how the wall or slab will be built, and it will + instead be determined on site by a trade. + + Layers are defined in a particular order and thickness, so that it is + clear which layer comes next. + + :param layer_set: The IfcMaterialLayerSet that the layer is part of. The + layer set represents a group of layers. See + ifcopenshell.api.material.add_material_set for more information on + how to add a layer set. + :param material: The IfcMaterial that the layer is made out of. + :param name: An optional name of the layer. + :return: The newly created IfcMaterialLayer + + Example: + + .. code:: python + + # Let's imagine we have a wall type that has two layers of + # gypsum with steel studs inside. Notice we are assigning to + # the type only, as all occurrences of that type will automatically + # inherit the material. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType", name="WAL01") + + # First, let's create a material set. This will later be assigned + # to our wall type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="GYP-ST-GYP", set_type="IfcMaterialLayerSet") + + # Let's create a few materials, it's important to also give them + # categories. This makes it easy for model recipients to do things + # like "show me everything made out of aluminium / concrete / steel + # / glass / etc". The IFC specification states a list of categories + # you can use. + gypsum = ifcopenshell.api.material.add_material(model, name="PB01", category="gypsum") + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Now let's use those materials as three layers in our set, such + # that the steel studs are sandwiched by the gypsum. Let's imagine + # we're setting the layer thickness in millimeters. + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 13}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 92}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 13}) + + # Great! Let's assign our material set to our wall type. + ifcopenshell.api.material.assign_material(model, products=[wall_type], material=material_set) + """ + unit_scale = ifcopenshell.util.unit.calculate_unit_scale(file) + layers = list(layer_set.MaterialLayers or []) + if file.schema == "IFC2X3": + layer = file.create_entity("IfcMaterialLayer", Material=material, LayerThickness=0.1 / unit_scale) + else: + layer = file.create_entity("IfcMaterialLayer", Material=material, LayerThickness=0.1 / unit_scale, Name=name) + layers.append(layer) + layer_set.MaterialLayers = layers + return layer diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_list_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_list_item.py new file mode 100644 index 0000000000000000000000000000000000000000..994d4665ef26b293990e9015ebfc3cb9f095ea77 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_list_item.py @@ -0,0 +1,82 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def add_list_item( + file: ifcopenshell.file, material_list: ifcopenshell.entity_instance, material: ifcopenshell.entity_instance +) -> None: + """Adds a new material in a list of materials + + In IFC2X3, if you wanted an object to have multiple materials (i.e. a + composite material) you would assign the object to a material list, + which would contain a list of materials. For example, a window might + have a list of 2 materials, one being aluminium for the frame, and + another being glass for the panel. + + In IFC4 and above, this is deprecated and should not be used. Instead, + you should use constituent sets instead, which achieve the same thing + but are more powerful as they allow you to define the properties of the + constituents too. + + However if you're stuck on IFC2X3, you have my condolences as well as + this function. + + :param material_list: The IfcMaterialList the material should be added + to. + :param material: The IfcMaterial to add to the list + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a window type that has an aluminium frame + # and a glass glazing panel. Notice we are assigning to the type + # only, as all occurrences of that type will automatically inherit + # the material. + window_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWindowType") + + # First, let's create a list. This will later be assigned to our + # window element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="Window", set_type="IfcMaterialList") + + # Let's create a few materials, it's important to also give them + # categories. This makes it easy for model recipients to do things + # like "show me everything made out of aluminium / concrete / steel + # / glass / etc". The IFC specification states a list of categories + # you can use. + aluminium = ifcopenshell.api.material.add_material(model, name="AL01", category="aluminium") + glass = ifcopenshell.api.material.add_material(model, name="GLZ01", category="glass") + + # Now let's use those materials as two items in our list. + ifcopenshell.api.material.add_list_item(model, material_list=material_set, material=aluminium) + ifcopenshell.api.material.add_list_item(model, material_list=material_set, material=glass) + + # Great! Let's assign our material set to our window type. + # We're technically not done here, we might want to add geometry to + # our window too, but to keep this example simple, geometry is + # optional and it is enough to say that this window is made out of + # aluminium and glass. + ifcopenshell.api.material.assign_material(model, products=[window_type], material=material_set) + """ + materials = list(material_list.Materials or []) + materials.append(material) + material_list.Materials = materials diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_material_set.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_material_set.py new file mode 100644 index 0000000000000000000000000000000000000000..bd23688ac877c54849c163ae5facdee15bffbad2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_material_set.py @@ -0,0 +1,117 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Literal + + +MATERIAL_SET_TYPE = Literal[ + "IfcMaterialLayerSet", + "IfcMaterialProfileSet", + "IfcMaterialConstituentSet", + "IfcMaterialList", +] + + +def add_material_set( + file: ifcopenshell.file, name: str = "Unnamed", set_type: MATERIAL_SET_TYPE = "IfcMaterialConstituentSet" +) -> ifcopenshell.entity_instance: + """Adds a new material set + + IFC allows you to state that objects are made out of multiple materials. + These are known generically as material sets, but may also be called + layered materials, composite materials, or other names in software. + + There are three types of material sets: + + - A layer set, used for layered construction such as walls, where the + element is parametrically made out of extruded layers, each layer + having a thickness defined. Even though this is known as a layer + "set" it is still recommended to use it for all standared layered + construction as it describes the intent of the element to be layered + construction and thus can be used for parametric editing. + - A profile set, used for profiled construction such as beams or + columns, where the element is parametrically made out of one or more + extruded profiles, where each profile may be parametric from a + standard section (e.g. standardised steel profile) or an arbitrary + shape (e.g. cold rolled sections, or skirtings, moldings, etc). Note + that even though this is called a profile "set", it should still be + used even if there is only a single profile. This is not available in + IFC2X3. + - A constituent set, used for arbitrary composite construction where + the object is made out of multiple materials. The constituents may be + explicitly defined via a shape, such as a window where the frame + geometry is made from one material and the panel geometry is made + from another material. Alternatively, the constituents may be + represented in terms of percentages, such as in mixtures like + concrete where there might be a percentage constituent of cement and + another percentage constituent of binder. This is not available in + IFC2X3. + + There is also a fourth material set known as a material list, which is a + legacy type of set used by IFC2X3. It should not be used on IFC4 and + above, and constituent sets should be used instead. + + :param name: The name of the material set, which may be purely + descriptive or annotated in drawings. Defaults to "Unnamed". + :param set_type: What type of set you want to create, chosen from + IfcMaterialLayerSet, IfcMaterialProfileSet, + IfcMaterialConstituentSet, or IfcMaterialList. Defaults to + IfcMaterialConstituentSet. + :return: The newly created material set element + + Example: + + .. code:: python + + # Let's imagine we have a wall type that has two layers of + # gypsum with steel studs inside. Notice we are assigning to + # the type only, as all occurrences of that type will automatically + # inherit the material. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType", name="WAL01") + + # First, let's create a material set. This will later be assigned + # to our wall type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="GYP-ST-GYP", set_type="IfcMaterialLayerSet") + + # Let's create a few materials, it's important to also give them + # categories. This makes it easy for model recipients to do things + # like "show me everything made out of aluminium / concrete / steel + # / glass / etc". The IFC specification states a list of categories + # you can use. + gypsum = ifcopenshell.api.material.add_material(model, name="PB01", category="gypsum") + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Now let's use those materials as three layers in our set, such + # that the steel studs are sandwiched by the gypsum. Let's imagine + # we're setting the layer thickness in millimeters. + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 13}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 92}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 13}) + + # Great! Let's assign our material set to our wall type. + ifcopenshell.api.material.assign_material(model, products=[wall_type], material=material_set) + """ + if set_type == "IfcMaterialLayerSet": + return file.create_entity("IfcMaterialLayerSet", LayerSetName=name or "Unnamed") + elif set_type == "IfcMaterialList": + return file.create_entity("IfcMaterialList") + return file.create_entity(set_type, Name=name or "Unnamed") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_profile.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..160f79e45333ef28eb043bc7b43262981228d9e4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/add_profile.py @@ -0,0 +1,100 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Optional + + +def add_profile( + file: ifcopenshell.file, + profile_set: ifcopenshell.entity_instance, + material: Optional[ifcopenshell.entity_instance] = None, + profile: Optional[ifcopenshell.entity_instance] = None, + name: Optional[str] = None, +) -> ifcopenshell.entity_instance: + """Add a new profile item to a profile set + + A profile item in a profile set represents an extruded 2D profile curve + that is extruded along the axis of the element. Most commonly there will + only be a single profile item in a profile set. For example, a beam will + have a material profile set containing a single profile item, which may + have a steel material and a I-beam shaped profile curve. + + Note that the "profile item" represents a single extrusion in the + profile set, whereas the "profile curve" represents a 2D curve used by a + "profile item". + + Profile is not optional for IfcMaterialProfile but it is optional for this API + call and can be assigned later with material.assign_profile. + + In some cases, a profiled element (i.e. beam, column) may be a composite + beam or column and include multiple extrusions. This is rare. The order + of the profiles does not matter. + + :param profile_set: The IfcMaterialProfileSet that the profile is part of. The + profile set represents a group of profile items. See + ifcopenshell.api.material.add_material_set for more information on + how to add a profile set. + :param material: The IfcMaterial that the profile item is made out of. + :param profile: The IfcProfileDef that represents the 2D cross section + of the the profile item. + :param name: An optional name of the material profile (not the geometric + profile). + :return: The newly created IfcMaterialProfile + + Example: + + .. code:: python + + # Let's imagine we have a steel I-beam. Notice we are assigning to + # the type only, as all occurrences of that type will automatically + # inherit the material. + beam_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBeamType", name="B1") + + # First, let's create a material set. This will later be assigned + # to our beam type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="B1", set_type="IfcMaterialProfileSet") + + # Create a steel material. + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Create an I-beam profile curve. Notice how we name our profiles + # based on standardised steel profile names. + hea100 = file.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA100", ProfileType="AREA", + OverallWidth=100, OverallDepth=96, WebThickness=5, FlangeThickness=8, FilletRadius=12, + ) + + # Define that steel material and cross section as a single profile + # item. If this were a composite beam, we might add multiple profile + # items instead, but this is rarely the case in most construction. + ifcopenshell.api.material.add_profile(model, + profile_set=material_set, material=steel, profile=hea100) + + # Great! Let's assign our material set to our beam type. + ifcopenshell.api.material.assign_material(model, products=[beam_type], material=material_set) + """ + profiles = list(profile_set.MaterialProfiles or []) + mat_profile = file.create_entity("IfcMaterialProfile", Name=name) + if material: + mat_profile.Material = material + if profile: + mat_profile.Profile = profile + profiles.append(mat_profile) + profile_set.MaterialProfiles = profiles + return mat_profile diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_material.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_material.py new file mode 100644 index 0000000000000000000000000000000000000000..0e37eef148140b042bef8a64171a88857bd08c66 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_material.py @@ -0,0 +1,363 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.api.material +import ifcopenshell.guid +import ifcopenshell.util.element +import ifcopenshell.util.representation +from collections import defaultdict +from typing import Optional, Union, Any + + +def assign_material( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + type: ifcopenshell.util.element.MATERIAL_TYPE = "IfcMaterial", + material: Optional[ifcopenshell.entity_instance] = None, +) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance], None]: + """Assigns a material to the list of products + + Will unassign previously assigned material. + + When a material is assigned to a product, it means that the product is + made out of that material. In its simplest form, a single material may + be assigned to a product, meaning that the entire product is made out of + that one material. Alternatively, a material set may be assigned to a + product, meaning that the product is made out of a set of materials. + There are three types of sets, including layered construction, profiled + materials, and arbitrary material constituents. See + ifcopenshell.api.material.add_material_set for details. + + Materials are typically assigned to the element types rather than + individual occurrences of elements. Individual occurrences would then + inherit the material from the type. + + If the type has a material set, then the geometry of the occurrences + must comply with the material set. For example, if the type has a + constituent set, then it is expected that all occurrences also inherit + the geometry of the type, which is made out of those constituents. + Alternatively, if the type has a layer set, then all occurrences must + have geometry that has a thickness equal to the sum of all layers. If a + type has a profile set, then all occurrences must has the same profile + extruded along its axis. + + For layers and profiles assigned to types, the occurrences must be + assigned an IfcMaterialLayerSetUsage or an IfcMaterialProfileSetUsage. + This allows individual occurrences to override the layered or profiled + construction offset from a reference line. + + :param products: The list of IfcProducts to assign the material or material set + to. + :param type: Choose from "IfcMaterial", "IfcMaterialConstituentSet", + "IfcMaterialLayerSet", "IfcMaterialLayerSetUsage", + "IfcMaterialProfileSet", "IfcMaterialProfileSetUsage", or + "IfcMaterialList". Note that "Set Usages" may only be assigned to + occurrences, not types. Defaults to "IfcMaterial". + :param material: The IfcMaterial or material set you are assigning here. + If type is Usage then no need to provide `material`, it will be deduced + from the element type automatically. + If IfcMaterial is provided as material and type is not IfcMaterial, + provided material will be ignored except for IfcMaterialList + where it will be used as part of the list. + :return: IfcRelAssociatesMaterial entity + or a list of IfcRelAssociatesMaterial entities + (possible if `type` is Usage + and `products` require different Usages) + or `None` if `products` was empty list. + + Example: + + .. code:: python + + # Let's start with a simple concrete material + concrete = ifcopenshell.api.material.add_material(model, name="CON01", category="concrete") + + # Let's imagine a concrete bench made out of a single concrete + # material. Let's assign it to the type. + bench_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurnitureType") + ifcopenshell.api.material.assign_material(model, + products=[bench_type], type="IfcMaterial", material=concrete) + + # Let's imagine there are a two occurrences of this bench. It's not + # necessary to assign any material to these benches as they + # automatically inherit the material from the type. + bench1 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + bench2 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + ifcopenshell.api.type.assign_type(model, related_objects=[bench1], relating_type=bench_type) + ifcopenshell.api.type.assign_type(model, related_objects=[bench2], relating_type=bench_type) + + # If we have a concrete wall, we should use a layer set. Again, + # let's start with a wall type, not occurrences. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType", name="WAL01") + + # Even though there is only one layer in our layer set, we still use + # a layer set because it makes it clear that this is a layered + # construction. Let's say it's a 200mm thick concrete layer. + material_set = ifcopenshell.api.material.add_material_set(model, + name="CON200", set_type="IfcMaterialLayerSet") + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": 200}) + + # Our wall type now has the layer set assigned to it + ifcopenshell.api.material.assign_material(model, + products=[wall_type], type="IfcMaterialLayerSet", material=material_set) + + # Let's imagine an occurrence of this wall type. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + ifcopenshell.api.type.assign_type(model, related_objects=[wall], relating_type=wall_type) + + # Our wall occurrence needs to have a "set usage" which describes + # how the layers relate to a reference line (typically a 2D line + # representing the extents of the wall). Usages are special since + # they automatically detect the inherited material set from the + # type. You'd write similar code for a profile set. + ifcopenshell.api.material.assign_material(model, + products=[wall], type="IfcMaterialLayerSetUsage") + + # To be complete, let's create the wall's axis and body + # representation. Notice how the axis guides the walls "reference + # line" which determines where layers are extruded from, and the + # body has a thickness of 200mm, same as our total layer set + # thickness. + axis = ifcopenshell.api.geometry.add_axis_representation(model, + context=axis_context, axis=[(0.0, 0.0), (5000.0, 0.0)]) + body = ifcopenshell.api.geometry.add_wall_representation(model, + context=body_context, length=5000, height=3000, thickness=200) + ifcopenshell.api.geometry.assign_representation(model, product=wall, representation=axis) + ifcopenshell.api.geometry.assign_representation(model, product=wall, representation=body) + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = {"products": products, "type": type, "material": material} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + self.products: set[ifcopenshell.entity_instance] = set(self.settings["products"]) + if not self.products: + return + + # NOTE: we always reassign material, even if it might be assigned before + products_to_unassign_material = [p for p in self.products if ifcopenshell.util.element.get_material(p)] + if products_to_unassign_material: + ifcopenshell.api.material.unassign_material(self.file, products=products_to_unassign_material) + + if self.settings["type"] == "IfcMaterial" or ( + self.settings["material"] + and not self.settings["material"].is_a("IfcMaterial") + and not self.settings["type"].endswith("Usage") + ): + return self.assign_ifc_material() + + elif self.settings["type"] == "IfcMaterialConstituentSet": + material_set = self.file.create_entity(self.settings["type"]) + return self.create_material_association(material_set) + + elif self.settings["type"] == "IfcMaterialLayerSet": + material_set = self.file.create_entity(self.settings["type"]) + return self.create_material_association(material_set) + + elif self.settings["type"] == "IfcMaterialLayerSetUsage": + AXIS3_CLASSES = [ + "IfcSlab", + "IfcSlabStandardCase", + "IfcSlabElementedCase", + "IfcRoof", + "IfcRamp", + "IfcPlate", + "IfcPlateStandardCase", + "IfcCovering", + "IfcFurniture", + ] + + provided_material_set = None + if self.settings["material"]: + provided_material_set = self.settings["material"] + material_set_class = provided_material_set.is_a() + assert ( + material_set_class == "IfcMaterialLayerSet" + ), f"{material_set_class} cannot be assiged as a IfcMaterialLayerSetUsage." + + layer_types_to_products: defaultdict[ + tuple[ifcopenshell.entity_instance, str], list[ifcopenshell.entity_instance] + ] + layer_types_to_products = defaultdict(list) + types_to_material_sets: dict[Union[ifcopenshell.entity_instance, None], ifcopenshell.entity_instance] + types_to_material_sets = {} + + for product in self.products: + # Figure what material set to assign. + if provided_material_set is not None: + material_set = provided_material_set + else: + # If material set is not provided, derive it from the type. + element_type = ifcopenshell.util.element.get_type(product) + if element_type in types_to_material_sets: + material_set = types_to_material_sets[element_type] + else: + element_type_material = None + if element_type is not None: + element_type_material = ifcopenshell.util.element.get_material(element_type) + if element_type_material and element_type_material.is_a("IfcMaterialLayerSet"): + material_set = element_type_material + else: + material_set = self.file.create_entity("IfcMaterialLayerSet") + + layer_set_direction = "AXIS3" if product.is_a() in AXIS3_CLASSES else "AXIS2" + material_layer_type = (material_set, layer_set_direction) + layer_types_to_products[material_layer_type].append(product) + + rels = [ + self.create_layer_set_usage(material_set, layer_set_direction, products) + for (material_set, layer_set_direction), products in layer_types_to_products.items() + ] + return rels[0] if len(rels) == 1 else rels + + elif self.settings["type"] == "IfcMaterialProfileSet": + material_set = self.file.create_entity(self.settings["type"]) + return self.create_material_association(material_set) + + elif self.settings["type"] == "IfcMaterialProfileSetUsage": + provided_material_set = None + if self.settings["material"]: + provided_material_set = self.settings["material"] + material_set_class = provided_material_set.is_a() + assert ( + material_set_class == "IfcMaterialProfileSet" + ), f"{material_set_class} cannot be assiged as a IfcMaterialProfileSetUsage." + + material_sets_to_products: dict[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]] + material_sets_to_products = defaultdict(list) + types_to_material_sets: dict[Union[ifcopenshell.entity_instance, None], ifcopenshell.entity_instance] + types_to_material_sets = {} + + for product in self.products: + # Figure what material set to assign. + if provided_material_set is not None: + material_set = provided_material_set + else: + # If material set is not provided, derive it from the type. + element_type = ifcopenshell.util.element.get_type(product) + if element_type in types_to_material_sets: + material_set = types_to_material_sets[element_type] + else: + element_type_material = None + if element_type is not None: + element_type_material = ifcopenshell.util.element.get_material(element_type) + if element_type_material and element_type_material.is_a("IfcMaterialProfileSet"): + material_set = element_type_material + else: + material_set = self.file.create_entity("IfcMaterialProfileSet") + + material_sets_to_products[material_set].append(product) + + rels: list[ifcopenshell.entity_instance] = [] + for material_set, products in material_sets_to_products.items(): + self.update_representation_profile(material_set, products) + material_set_usage = self.create_profile_set_usage(material_set) + rels.append(self.create_material_association(material_set_usage, products)) + return rels[0] if len(rels) == 1 else rels + + elif self.settings["type"] == "IfcMaterialList": + material_set = self.file.create_entity(self.settings["type"]) + material_set.Materials = [self.settings["material"]] + return self.create_material_association(material_set) + + def update_representation_profile( + self, material_set: ifcopenshell.entity_instance, products: list[ifcopenshell.entity_instance] + ) -> None: + profile = material_set.CompositeProfile + if not profile and material_set.MaterialProfiles: + profile = material_set.MaterialProfiles[0].Profile + if not profile: + return + for product in products: + representation = ifcopenshell.util.representation.get_representation(product, "Model", "Body", "MODEL_VIEW") + if not representation: + return + for subelement in self.file.traverse(representation): + if subelement.is_a("IfcSweptAreaSolid"): + subelement.SweptArea = profile + + def create_layer_set_usage( + self, + material_set: ifcopenshell.entity_instance, + layer_set_direction: str, + products: list[ifcopenshell.entity_instance], + ) -> ifcopenshell.entity_instance: + usage = self.file.create_entity( + "IfcMaterialLayerSetUsage", + **{ + "ForLayerSet": material_set, + "LayerSetDirection": layer_set_direction, + "DirectionSense": "POSITIVE", + "OffsetFromReferenceLine": 0, + }, + ) + return self.create_material_association(usage, products) + + def create_profile_set_usage(self, material_set: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + return self.file.create_entity("IfcMaterialProfileSetUsage", **{"ForProfileSet": material_set}) + + def assign_ifc_material(self) -> ifcopenshell.entity_instance: + material = self.settings["material"] or self.file.create_entity("IfcMaterial") + rel = self.get_rel_associates_material(material) + if not rel: + return self.create_material_association(material) + previous_related_objects = set(rel.RelatedObjects) + rel.RelatedObjects = list(previous_related_objects | self.products) + ifcopenshell.api.owner.update_owner_history(self.file, element=rel) + return rel + + def create_material_association( + self, + relating_material: ifcopenshell.entity_instance, + products: Optional[list[ifcopenshell.entity_instance]] = None, + ) -> ifcopenshell.entity_instance: + if products is None: + products = list(self.products) + return self.file.create_entity( + "IfcRelAssociatesMaterial", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(self.file), + "RelatedObjects": products, + "RelatingMaterial": relating_material, + }, + ) + + def get_rel_associates_material( + self, material: ifcopenshell.entity_instance + ) -> Union[ifcopenshell.entity_instance, None]: + if self.file.schema == "IFC2X3" or material.is_a("IfcMaterialList"): + return next( + ( + r + for r in self.file.by_type("IfcRelAssociatesMaterial") + if r.RelatingMaterial == self.settings["material"] + ), + None, + ) + return next(iter(material.AssociatedTo), None) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_profile.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..ce269dbc8659084925c3093353cf08fcf9d99de4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/assign_profile.py @@ -0,0 +1,127 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.representation +from typing import Any + + +def assign_profile( + file: ifcopenshell.file, material_profile: ifcopenshell.entity_instance, profile: ifcopenshell.entity_instance +) -> None: + """Changes the profile curve of a material profile item in a profile set + + In addition to changing the profile curve, it will also change the + profile curve used in any body representation extrusions. + + :param material_profile: The IfcMaterialProfile to change the profile + curve of. See ifcopenshell.api.material.add_profile to see how to + create profiles. + :param profile: The IfcProfileDef to set the profile item's curve to. + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a steel I-beam. Notice we are assigning to + # the type only, as all occurrences of that type will automatically + # inherit the material. + beam_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBeamType", name="B1") + + # First, let's create a material set. This will later be assigned + # to our beam type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="B1", set_type="IfcMaterialProfileSet") + + # Create a steel material. + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Create an I-beam profile curve. Notice how we name our profiles + # based on standardised steel profile names. + hea100 = model.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA100", ProfileType="AREA", + OverallWidth=100, OverallDepth=96, WebThickness=5, FlangeThickness=8, FilletRadius=12, + ) + + # Define that steel material and cross section as a single profile + # item. If this were a composite beam, we might add multiple profile + # items instead, but this is rarely the case in most construction. + profile_item = ifcopenshell.api.material.add_profile(model, + profile_set=material_set, material=steel, profile=hea100) + + # Great! Let's assign our material set to our beam type. + ifcopenshell.api.material.assign_material(model, products=[beam_type], material=material_set) + + # Let's create an occurrence of this beam. + beam = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBeam", name="B1.01") + ifcopenshell.api.material.assign_material(model, + products=[beam], type="IfcMaterialProfileSetUsage") + + # Let's give a 1000mm long beam body representation. + body = ifcopenshell.api.geometry.add_profile_representation( + context=body_context, profile=hea100, depth=1000) + ifcopenshell.api.geometry.assign_representation(model, product=beam, representation=body) + ifcopenshell.api.geometry.edit_object_placement(model, product=beam) + + # Now let's change the profile to a HEA200 standard profile instead. + # This will automatically change the body representation that we + # just added as well to a HEA200 profile. + hea200 = model.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA200", ProfileType="AREA", + OverallWidth=200, OverallDepth=190, WebThickness=6.5, FlangeThickness=10, FilletRadius=18, + ) + ifcopenshell.api.material.assign_profile(model, material_profile=profile_item, profile=hea200) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(material_profile, profile) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, material_profile: ifcopenshell.entity_instance, profile: ifcopenshell.entity_instance) -> None: + # TODO: handle composite profiles + old_profile = material_profile.Profile + material_profile.Profile = profile + for profile_set in material_profile.ToMaterialProfileSet: + for inverse in self.file.get_inverse(profile_set): + if not inverse.is_a("IfcMaterialProfileSetUsage"): + continue + if self.file.schema == "IFC2X3": + for rel in self.file.get_inverse(inverse): + if not rel.is_a("IfcRelAssociatesMaterial"): + continue + for element in rel.RelatedObjects: + self.change_profile(element, profile) + else: + for rel in inverse.AssociatedTo: + for element in rel.RelatedObjects: + self.change_profile(element, profile) + + if old_profile and self.file.get_total_inverses(old_profile) == 0: + # TODO: check remove deep + self.file.remove(old_profile) + + def change_profile(self, element: ifcopenshell.entity_instance, profile: ifcopenshell.entity_instance) -> None: + representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW") + if not representation: + return + for subelement in self.file.traverse(representation): + if subelement.is_a("IfcSweptAreaSolid"): + subelement.SweptArea = profile diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_assigned_material.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_assigned_material.py new file mode 100644 index 0000000000000000000000000000000000000000..9a01322743ad4b8f0c3579d2a95b64872c352eee --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_assigned_material.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_assigned_material( + file: ifcopenshell.file, element: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcMaterial + + For more information about the attributes and data types of an + IfcMaterial, consult the IFC documentation. + + :param element: The IfcMaterial entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + concrete = ifcopenshell.api.material.add_material(model, name="CON01", category="concrete") + ifcopenshell.api.material.edit_assigned_material(model, + element=concrete, attributes={"Description": "40MPA concrete with broom finish"}) + """ + for name, value in attributes.items(): + setattr(element, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_material.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_material.py new file mode 100644 index 0000000000000000000000000000000000000000..ddf541503c6b9669dc6497e794432dabd286d873 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_material.py @@ -0,0 +1,26 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_material(file: ifcopenshell.file, material: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcMaterial""" + + for name, value in attributes.items(): + setattr(material, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile.py new file mode 100644 index 0000000000000000000000000000000000000000..3bc747938834b64d735fe7c2a2d3157df3a772f6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile.py @@ -0,0 +1,83 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021, 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from typing import Any, Optional +import ifcopenshell + + +def edit_profile( + file: ifcopenshell.file, + profile: ifcopenshell.entity_instance, + attributes: Optional[dict[str, Any]] = None, + profile_def: Optional[ifcopenshell.entity_instance] = None, + material: Optional[ifcopenshell.entity_instance] = None, +) -> None: + """Edits the attributes of an IfcMaterialProfile + + For more information about the attributes and data types of an + IfcMaterialProfile, consult the IFC documentation. + + :param profile: The IfcMaterialProfile entity you want to edit + :param attributes: a dictionary of attribute names and values. + :param profile_def: The IfcProfileDef entity the profile curve should be + extruded from. + :param material: The IfcMaterial entity you want to change the profile + to be made from. + :return: None + + Example: + + .. code:: python + + # Let's create a material set to store our profiles. + material_set = ifcopenshell.api.material.add_material_set(model, + name="B1", set_type="IfcMaterialProfileSet") + + # Create a couple steel materials. + steel1 = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + steel2 = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Create some I-shaped profiles. Notice how we name our profiles based + # on standardised steel profile names. + hea100 = file.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA100", ProfileType="AREA", + OverallWidth=100, OverallDepth=96, WebThickness=5, FlangeThickness=8, FilletRadius=12, + ) + hea200 = file.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA200", ProfileType="AREA", + OverallWidth=200, OverallDepth=190, WebThickness=6.5, FlangeThickness=10, FilletRadius=18, + ) + + # Define that steel material and cross section as a single profile + # item. If this were a composite beam, we might add multiple profile + # items instead, but this is rarely the case in most construction. + profile_item = ifcopenshell.api.material.add_profile(model, + profile_set=material_set, material=steel1, profile=hea100) + + # Edit our profile item to use a HEA200 profile instead made out of + # another type of steel. + ifcopenshell.api.material.edit_profile(model, + profile=profile_item, profile_def=hea200, material=steel2) + """ + for name, value in (attributes or {}).items(): + setattr(profile, name, value) + if material: + profile.Material = material + if profile_def: + profile.Profile = profile_def diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile_usage.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..4c004ecfdd96e0bd8740b59d57d9366406078c88 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/edit_profile_usage.py @@ -0,0 +1,222 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell.geom +import ifcopenshell.util.representation +import ifcopenshell.util.shape +from ifcopenshell.geom import ShapeType +from typing import Any + + +def edit_profile_usage( + file: ifcopenshell.file, usage: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcMaterialProfileSetUsage + + This is typically used to change the cardinal point of the profile. + The cardinal point represents whether the profile is extruded along the + center of the axis line, at a corner, at a shear center, at the bottom, + top, etc. + + For more information about the attributes and data types of an + IfcMaterialProfileSetUsage, consult the IFC documentation. + + :param usage: The IfcMaterialProfileSetUsage entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a steel I-beam. Notice we are assigning to + # the type only, as all occurrences of that type will automatically + # inherit the material. + beam_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBeamType", name="B1") + + # First, let's create a material set. This will later be assigned + # to our beam type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="B1", set_type="IfcMaterialProfileSet") + + # Create a steel material. + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Create an I-beam profile curve. Notice how we name our profiles + # based on standardised steel profile names. + hea100 = model.create_entity( + "IfcIShapeProfileDef", ProfileName="HEA100", ProfileType="AREA", + OverallWidth=100, OverallDepth=96, WebThickness=5, FlangeThickness=8, FilletRadius=12, + ) + + # Define that steel material and cross section as a single profile + # item. If this were a composite beam, we might add multiple profile + # items instead, but this is rarely the case in most construction. + profile_item = ifcopenshell.api.material.add_profile(model, + profile_set=material_set, material=steel, profile=hea100) + + # Great! Let's assign our material set to our beam type. + ifcopenshell.api.material.assign_material(model, products=[beam_type], material=material_set) + + # Let's create an occurrence of this beam. + beam = ifcopenshell.api.root.create_entity(model, ifc_class="IfcBeam", name="B1.01") + rel = ifcopenshell.api.material.assign_material(model, material=material_set, + products=[beam], type="IfcMaterialProfileSetUsage") + + # Let's give a 1000mm long beam body representation. + body = ifcopenshell.api.geometry.add_profile_representation( + context=body_context, profile=hea100, depth=1000) + ifcopenshell.api.geometry.assign_representation(model, product=beam, representation=body) + ifcopenshell.api.geometry.edit_object_placement(model, product=beam) + + # Let's change the cardinal point to be the top center of the axis + # line. This is represented by the number "8". Consult the IFC + # documentation for all the numbers you can use. + ifcopenshell.api.material.edit_profile_usage(model, + usage=rel.RelatingMaterial, attributes={"CardinalPoint": 8}) + """ + usecase = Usecase() + + usecase.file = file + return usecase.execute(usage, attributes) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, usage: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + self.usage = usage + self.attributes = attributes + self.cardinal_point = attributes.get("CardinalPoint") + if self.cardinal_point and self.cardinal_point != usage.CardinalPoint: + self.update_cardinal_point() + + for name, value in attributes.items(): + setattr(usage, name, value) + + def update_cardinal_point(self): + material_set = self.usage.ForProfileSet + self.profile = material_set.CompositeProfile + if not self.profile and material_set.MaterialProfiles: + self.profile = material_set.MaterialProfiles[0].Profile + if not self.profile: + return + + self.position = self.calculate_position() + + if self.file.schema == "IFC2X3": + for rel in self.file.get_inverse(self.usage): + if not rel.is_a("IfcRelAssociatesMaterial"): + continue + for element in rel.RelatedObjects: + self.update_representation(element) + else: + for rel in self.usage.AssociatedTo: + for element in rel.RelatedObjects: + self.update_representation(element) + + def calculate_position(self): + self.dummy = ifcopenshell.file(schema=self.file.schema) + dummy_profile = self.dummy.add(self.profile) + # We clear all radiuses so that we can calculate geometric centroid easily + for i, attribute in enumerate(dummy_profile): + name = dummy_profile.attribute_name(i) + if "Radius" in name and name != "RoundingRadius": + dummy_profile[i] = None + dummy_solid = self.dummy.create_entity( + "IfcExtrudedAreaSolid", + **{ + "SweptArea": dummy_profile, + "ExtrudedDirection": self.dummy.createIfcDirection((0.0, 0.0, 1.0)), + "Depth": 1, + } + ) + self.settings_2d = ifcopenshell.geom.settings() + self.settings_2d.set("dimensionality", ifcopenshell.ifcopenshell_wrapper.CURVES_SURFACES_AND_SOLIDS) + shape = ifcopenshell.geom.create_shape(self.settings_2d, dummy_solid) + + # NOTE: points do not need unit conversion + # as dummy file is inherently using project units. + if self.cardinal_point == 1: + return self.get_bottom_left(shape) + elif self.cardinal_point == 2: + return self.get_bottom_centre(shape) + elif self.cardinal_point == 3: + return self.get_bottom_right(shape) + elif self.cardinal_point == 4: + return self.get_mid_depth_left(shape) + elif self.cardinal_point == 5: + return self.get_mid_depth_centre(shape) + elif self.cardinal_point == 6: + return self.get_mid_depth_right(shape) + elif self.cardinal_point == 7: + return self.get_top_left(shape) + elif self.cardinal_point == 8: + return self.get_top_centre(shape) + elif self.cardinal_point == 9: + return self.get_top_right(shape) + + def get_bottom_left(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((-width / 2, height / 2, 0.0))) + + def get_bottom_centre(self, shape: ShapeType) -> ifcopenshell.entity_instance: + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((0.0, height / 2, 0.0))) + + def get_bottom_right(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((width / 2, height / 2, 0.0))) + + def get_mid_depth_left(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((-width / 2, 0.0, 0.0))) + + def get_mid_depth_centre(self, shape: ShapeType) -> ifcopenshell.entity_instance: + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((0.0, 0.0, 0.0))) + + def get_mid_depth_right(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((width / 2, 0.0, 0.0))) + + def get_top_left(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((-width / 2, -height / 2, 0.0))) + + def get_top_centre(self, shape: ShapeType) -> ifcopenshell.entity_instance: + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((0.0, -height / 2, 0.0))) + + def get_top_right(self, shape: ShapeType) -> ifcopenshell.entity_instance: + width = ifcopenshell.util.shape.get_x(shape) + height = ifcopenshell.util.shape.get_y(shape) + return self.file.createIfcAxis2Placement3D(self.file.createIfcCartesianPoint((width / 2, -height / 2, 0.0))) + + def update_representation(self, element: ifcopenshell.entity_instance) -> None: + representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW") + if not representation: + return + + for subelement in self.file.traverse(representation): + if subelement.is_a("IfcSweptAreaSolid") and subelement.SweptArea == self.profile: + self.update_swept_area_solid(subelement) + + def update_swept_area_solid(self, element: ifcopenshell.entity_instance) -> None: + element.Position = self.position diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_constituent.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_constituent.py new file mode 100644 index 0000000000000000000000000000000000000000..8367f24d0efe3c279f0d27e24262dd37980653b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_constituent.py @@ -0,0 +1,58 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +import ifcopenshell.util.element + + +def remove_constituent( + file: ifcopenshell.file, constituent: ifcopenshell.entity_instance, should_remove_material: bool = False +) -> None: + """Removes a constituent from a constituent set + + Note that it is invalid to have zero items in a set, so you should leave + at least one constituent to ensure a valid IFC dataset. + + :param constituent: The IfcMaterialConstituent entity you want to remove + :param should_remove_material: If true, materials with no users will be removed + + Example: + + .. code:: python + + # Create a material set for windows made out of aluminium and glass. + material_set = ifcopenshell.api.material.add_material_set(model, + name="Window", set_type="IfcMaterialConstituentSet") + + aluminium = ifcopenshell.api.material.add_material(model, name="AL01", category="aluminium") + glass = ifcopenshell.api.material.add_material(model, name="GLZ01", category="glass") + + # Now let's use those materials as two constituents in our set. + framing = ifcopenshell.api.material.add_constituent(model, + constituent_set=material_set, material=aluminium) + glazing = ifcopenshell.api.material.add_constituent(model, + constituent_set=material_set, material=glass) + + # Let's remove the glass constituent. Note that we should not remove + # the framing, at this would mean there are no constituents which is + # invalid. + ifcopenshell.api.material.remove_constituent(model, constituent=glazing) + """ + material = constituent.Material + file.remove(constituent) + if material and should_remove_material: + ifcopenshell.util.element.remove_deep2(file, material) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_layer.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..443ad122c0c70f3e068bb33eccd80ba22abcaee2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_layer.py @@ -0,0 +1,60 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell.util.element + + +def remove_layer( + file: ifcopenshell.file, layer: ifcopenshell.entity_instance, should_remove_material: bool = False +) -> None: + """Removes a layer from a layer set + + Note that it is invalid to have zero items in a set, so you should leave + at least one layer to ensure a valid IFC dataset. + + :param layer: The IfcMaterialLayer entity you want to remove + :param should_remove_material: If true, materials with no users will be removed + + Example: + + .. code:: python + + # Create a material set for steel stud partition walls. + material_set = ifcopenshell.api.material.add_material_set(model, + name="Window", set_type="IfcMaterialConstituentSet") + + gypsum = ifcopenshell.api.material.add_material(model, name="PB01", category="gypsum") + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Now let's use those materials as three layers in our set, such + # that the steel studs are sandwiched by the gypsum. Let's imagine + # we're setting the layer thickness in millimeters. + layer1 = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer1, attributes={"LayerThickness": 13}) + layer2 = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + ifcopenshell.api.material.edit_layer(model, layer=layer2, attributes={"LayerThickness": 92}) + layer3 = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer3, attributes={"LayerThickness": 13}) + + # Let's remove the last layer, such that the wall might be clad only + # one one side such as to line a services riser. + ifcopenshell.api.material.remove_layer(model, layer=layer3) + """ + material = layer.Material + file.remove(layer) + if material and should_remove_material: + ifcopenshell.util.element.remove_deep2(file, material) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_list_item.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_list_item.py new file mode 100644 index 0000000000000000000000000000000000000000..3be123d8e982d4a94456a8023f09dc96318244bf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_list_item.py @@ -0,0 +1,56 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell + + +def remove_list_item( + file: ifcopenshell.file, material_list: ifcopenshell.entity_instance, material_index: int = 0 +) -> None: + """Removes an item in an material list + + Note that it is invalid to have zero items in a list, so you should leave + at least one item to ensure a valid IFC dataset. + + :param material_list: The IfcMaterialList entity you want to remove an + item from. + :param material_index: The index of the material you want to remove from + the list. Starts counting at 0. Defaults to 0. + :return: None + + Example: + + .. code:: python + + # Create a material list for aluminium windows. + material_set = ifcopenshell.api.material.add_material_set(model, + name="Window", set_type="IfcMaterialMaterialList") + + aluminium = ifcopenshell.api.material.add_material(model, name="AL01", category="aluminium") + glass = ifcopenshell.api.material.add_material(model, name="GLZ01", category="glass") + + # Now let's use those materials as two items in our list. + ifcopenshell.api.material.add_list_item(model, material_list=material_set, material=aluminium) + ifcopenshell.api.material.add_list_item(model, material_list=material_set, material=glass) + + # Let's remove the glass + ifcopenshell.api.material.remove_list_item(model, material_list=material_set, material_index=1) + """ + materials = list(material_list.Materials) + materials.pop(material_index) + material_list.Materials = materials diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material.py new file mode 100644 index 0000000000000000000000000000000000000000..c919f1f6296b4627c7fd7ddef772c49e2556d1a9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material.py @@ -0,0 +1,75 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_material(file: ifcopenshell.file, material: ifcopenshell.entity_instance) -> None: + """Removes a material + + If the material is used in a material set, the corresponding layer, + profile, or constituent is also removed. Note that this may result in a + material set with zero items in it, which is invalid, so the user must + take care of this situation themselves. + + :param material: The IfcMaterial entity you want to remove + :return: None + + Example: + + .. code:: python + + # Create a material + aluminium = ifcopenshell.api.material.add_material(model, name="AL01", category="aluminium") + + # ... and remove it + ifcopenshell.api.material.remove_material(model, material=aluminium) + """ + inverse_elements = file.get_inverse(material) + file.remove(material) + # TODO: Right now, we we choose only to delete set items (e.g. a layer) but not the material set + # This can lead to invalid material sets, but we assume the user will deal with it + for inverse in inverse_elements: + if inverse.is_a("IfcMaterialConstituent"): + file.remove(inverse) + elif inverse.is_a("IfcMaterialLayer"): + file.remove(inverse) + elif inverse.is_a("IfcMaterialProfile"): + file.remove(inverse) + elif inverse.is_a("IfcRelAssociatesMaterial"): + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + elif inverse.is_a("IfcMaterialProperties"): + if file.schema != "IFC2X3": + props = inverse.Properties + else: + # only IfcExtendedMaterialProperties have properties in IFC2X3 + props = getattr(inverse, "ExtendedProperties", None) + props = props or [] + for prop in props: + file.remove(prop) + file.remove(inverse) + elif inverse.is_a("IfcMaterialDefinitionRepresentation"): + for representation in inverse.Representations: + for item in representation.Items: + file.remove(item) + file.remove(representation) + file.remove(inverse) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material_set.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material_set.py new file mode 100644 index 0000000000000000000000000000000000000000..b11927e3821d774a98e60e23ee1aed6263cfaafe --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/remove_material_set.py @@ -0,0 +1,94 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.material +import ifcopenshell.util.element + + +def remove_material_set(file: ifcopenshell.file, material: ifcopenshell.entity_instance) -> None: + """Removes a material set + + All set items, such as layers, profiles, or constituents will also be + removed. All set usages are also removed. + + However, the materials and profile curves used by the layers, + profiles and constituents will not be removed. + + :param material: The IfcMaterialLayerSet, IfcMaterialConstituentSet, + IfcMaterialProfileSet entity you want to remove. + :return: None + + Example: + + .. code:: python + + # Create a material set + material_set = ifcopenshell.api.material.add_material_set(model, + name="GYP-ST-GYP", set_type="IfcMaterialLayerSet") + + # Create some materials + gypsum = ifcopenshell.api.material.add_material(model, name="PB01", category="gypsum") + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Add some layers + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + + # Completely delete the set and all layers. The gypsum and steel + # material still exist, though. + ifcopenshell.api.material.remove_material_set(model, material=material_set) + """ + + # Remove all usages for sets. + has_usages = material.is_a("IfcMaterialLayerSet") or material.is_a("IfcMaterialProfileSet") + if has_usages: + # Usage is invalid if it is not associated with some element, + # so we can remove usages through unassignment. + elements = ifcopenshell.util.element.get_elements_by_material(file, material) + if elements: + ifcopenshell.api.material.unassign_material(file, products=list(elements)) + + if material.is_a("IfcMaterialLayerSet"): + set_items = material.MaterialLayers or [] + elif material.is_a("IfcMaterialProfileSet"): + set_items = material.MaterialProfiles or [] + elif material.is_a("IfcMaterialConstituentSet"): + set_items = material.MaterialConstituents or [] + elif material.is_a("IfcMaterialList"): + set_items = [] + else: + raise ValueError(f"Unknown material set type: {material.is_a()}") + for set_item in set_items: + file.remove(set_item) + + inverse_elements = file.get_inverse(material) + file.remove(material) + + for inverse in inverse_elements: + if inverse.is_a("IfcRelAssociatesMaterial"): + # NOTE: for has_usages already handled by unassign_material. + history = inverse.OwnerHistory + file.remove(inverse) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + elif inverse.is_a("IfcMaterialProperties"): + for prop in inverse.Properties or []: + file.remove(prop) + file.remove(inverse) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/set_shape_aspect_constituents.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/set_shape_aspect_constituents.py new file mode 100644 index 0000000000000000000000000000000000000000..d95f877fcf760e3d45a5a295dc3c5507712e9c94 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/set_shape_aspect_constituents.py @@ -0,0 +1,114 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.style +import ifcopenshell.api.material +import ifcopenshell.util.element +import ifcopenshell.util.representation + + +def set_shape_aspect_constituents( + file: ifcopenshell.file, + *, + element: ifcopenshell.entity_instance, + context: ifcopenshell.entity_instance, + materials: dict[str, ifcopenshell.entity_instance], +) -> None: + """Assigns a material constituent set and sets styles based on shape aspects + + An IFC element may be assigned to a set of material constituents. For + example, a window may have a framing material and a glazing material. Each + constituent may have a name, such as "Framing" (which may be assigned to an + "Aluminium" material), and "Glazing" (assigned to a "Laminated Low-e Glass" + material). + + An IFC element's geometry may be composed of multiple geometric items. + These geometric items may have names, known as "Shape Aspects". For + example a solid extrusion for the framing named "Framing" and a solid + extrusion for the glass panel named "Glazing". + + A material may be associated with a style (i.e. colour). For example, a + grey style for the "Aluminium" material and a transparent blue style for + the "Laminated Low-e Glass" material. + + These three concepts of material constituents, shape aspects, and + associated styles are correlated. For example, if the name (e.g. "Framing") + of a material constituent and a shape aspect correlate, that means that the + geometric item inherits the style (i.e. grey). + + This function lets you specify named material constituents, and it'll + create a constituent set assigned to the element with those names. It'll + then find any geometric representation items with shape aspects matching + those names, and assign the correlating style. + + If an assigned material constituent set already exists matching those + values, it will be reused. If the values do not match, the existing + material constituent set will be removed if it is not used by anything + else. + + :param element: The IfcProduct or IfcTypeProduct + :param context: The IfcGeometricRepresentationContext, typically the body + context. You can get this via + :func:`ifcopenshell.util.representation.get_context`. + :param materials: The key is the name of the constituent, and the value is + the IfcMaterial. + + Example: + + .. code:: python + + # Create two materials + aluminium = ifcopenshell.api.material.add_material(model, name="AL01", category="aluminium") + glass = ifcopenshell.api.material.add_material(model, name="GLZ01", category="glass") + + # Auto assign material constituents and styles to items based on shape aspects + ifcopenshell.api.material.set_shape_aspect_constituents( + model, element=window, context=body, materials={ + "Framing": aluminium + "Lining": aluminium + "Glazing": glass + }) + """ + should_create_new_material_set = False + if material := ifcopenshell.util.element.get_material(element): + if ( + material.is_a("IfcMaterialConstituent") + and len(names := [c.Name for c in material.MaterialConstituents]) == len(materials) + and set(names) == set(materials.keys()) + ): + should_create_new_material_set = False + else: + should_create_new_material_set = True + ifcopenshell.api.material.unassign_material(file, products=[element]) + if not material.is_a("IfcMaterial") and not file.get_total_inverses(material): + ifcopenshell.api.material.remove_material_set(file, material=material) + else: + should_create_new_material_set = True + if should_create_new_material_set: + material_set = ifcopenshell.api.material.add_material_set(file, set_type="IfcMaterialConstituentSet") + for name, material in materials.items(): + ifcopenshell.api.material.add_constituent(file, constituent_set=material_set, material=material, name=name) + ifcopenshell.api.material.assign_material(file, products=[element], material=material_set) + + styles = {n: ifcopenshell.util.representation.get_material_style(m, context) for n, m in materials.items()} + representation = ifcopenshell.util.representation.get_representation(element, context=context) + representation = ifcopenshell.util.representation.resolve_representation(representation) + for item in representation.Items: + if aspect := ifcopenshell.util.representation.get_item_shape_aspect(representation, item): + if style := styles.get(aspect.Name, None): + ifcopenshell.api.style.assign_item_style(file, item=item, style=style) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/unassign_material.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/unassign_material.py new file mode 100644 index 0000000000000000000000000000000000000000..51d11b32483602ae2b07b1c57809cbfac4711057 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/material/unassign_material.py @@ -0,0 +1,135 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element +from typing import Any + + +def unassign_material(file: ifcopenshell.file, products: list[ifcopenshell.entity_instance]) -> None: + """Removes any material relationship with the list of products + + A product can only have one material assigned to it, which is why it is + not necessary to specify the material to unassign. The material is not + removed, only the relationship is removed. + + If the product does not have a material, nothing happens. + + Unassigning a LayerSet or ProfileSet from the product type will also + remove all Usages of the set. + + :param products: The list IfcProducts that may or may not have a material + :return: None + + Example: + + .. code:: python + + concrete = ifcopenshell.api.material.add_material(model, name="CON01", category="concrete") + + # Let's imagine a concrete bench made out of concrete. + bench_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurnitureType") + ifcopenshell.api.material.assign_material(model, + products=[bench_type], type="IfcMaterial", material=concrete) + + # Let's change our mind and remove the concrete assignment. The + # concrete material still exists, but the bench is no longer made + # out of concrete now. + ifcopenshell.api.material.unassign_material(model, products=[bench_type]) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(products) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, products: list[ifcopenshell.entity_instance]) -> None: + if not products: + return + self.products = set(products) + + self.remove_material_usages_from_types() + self.unassign_materials() + + def remove_material_usages_from_types(self) -> None: + # remove material usages from types + for product in self.products: + if not product.is_a("IfcTypeObject"): + continue + material = ifcopenshell.util.element.get_material(product) + if not material: + continue + if material.is_a() in ["IfcMaterialLayerSet", "IfcMaterialProfileSet"]: + # Remove set usages + # TODO: be more considerate and remove only usages + # associated with the set + product type, not all usages? + for inverse in self.file.get_inverse(material): + if self.file.schema == "IFC2X3": + if not inverse.is_a("IfcMaterialLayerSetUsage"): + continue + # in IFC2X3 there is no .AssociatedTo + for inverse2 in self.file.get_inverse(inverse): + if inverse2.is_a("IfcRelAssociatesMaterial"): + history = inverse2.OwnerHistory + self.file.remove(inverse2) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + else: + if not inverse.is_a("IfcMaterialUsageDefinition"): + continue + for rel in inverse.AssociatedTo: + history = rel.OwnerHistory + self.file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + self.file.remove(inverse) + + def unassign_materials(self) -> None: + associations: set[ifcopenshell.entity_instance] = set() + for product in self.products: + associations.update(product.HasAssociations) + + # we ensure that `associations` won't have removed elements + # to avoid crash during `material_inverses.issubset(associations)` + while associations: + rel = next(iter(associations)) + + if not rel.is_a("IfcRelAssociatesMaterial"): + associations.remove(rel) + else: + material = rel.RelatingMaterial + related_objects = set(rel.RelatedObjects) - self.products + + if material.is_a() in ["IfcMaterialLayerSetUsage", "IfcMaterialProfileSetUsage"]: + # Warning: this may leave the model in a non-compliant state. + material_inverses = set(self.file.get_inverse(material)) + if material_inverses.issubset(associations) and not related_objects: + self.file.remove(material) + associations.remove(rel) + + if not related_objects: + history = rel.OwnerHistory + self.file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + continue + rel.RelatedObjects = list(related_objects) + ifcopenshell.api.owner.update_owner_history(self.file, element=rel) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9b6930732e27de3373b7f72fcad853e076329a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/__init__.py @@ -0,0 +1,80 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""An element may have an owner, indicating who is responsible, liable, or +contactable regarding that element + +Note that in IFC2X3, element ownership is mandatory and must be addressed prior +to the creation of any element at all. See :func:`create_owner_history` for +examples. +""" + +from .. import wrap_usecases +from .add_actor import add_actor +from .add_address import add_address +from .add_application import add_application +from .add_organisation import add_organisation +from .add_person import add_person +from .add_person_and_organisation import add_person_and_organisation +from .add_role import add_role +from .assign_actor import assign_actor +from .create_owner_history import create_owner_history +from .edit_actor import edit_actor +from .edit_address import edit_address +from .edit_application import edit_application +from .edit_organisation import edit_organisation +from .edit_person import edit_person +from .edit_role import edit_role +from .remove_actor import remove_actor +from .remove_address import remove_address +from .remove_application import remove_application +from .remove_organisation import remove_organisation +from .remove_person import remove_person +from .remove_person_and_organisation import remove_person_and_organisation +from .remove_role import remove_role +from .unassign_actor import unassign_actor +from .update_owner_history import update_owner_history + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_actor", + "add_address", + "add_application", + "add_organisation", + "add_person", + "add_person_and_organisation", + "add_role", + "assign_actor", + "create_owner_history", + "edit_actor", + "edit_address", + "edit_application", + "edit_organisation", + "edit_person", + "edit_role", + "remove_actor", + "remove_address", + "remove_application", + "remove_organisation", + "remove_person", + "remove_person_and_organisation", + "remove_role", + "unassign_actor", + "update_owner_history", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_actor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..1456a99d5e5e3f84b7901ba621f1a06cb6a7da87 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_actor.py @@ -0,0 +1,70 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import ifcopenshell +import ifcopenshell.api.root +from typing import Literal + + +ACTOR_TYPE = Literal["IfcActor", "IfcOccupant"] + + +def add_actor( + file: ifcopenshell.file, + actor: ifcopenshell.entity_instance, + ifc_class: ACTOR_TYPE = "IfcActor", +) -> ifcopenshell.entity_instance: + """Adds a new actor + + An actor is a person or an organisation who has a responsibility or role + to play in a project. Actor roles include design consultants, + architects, engineers, cost planners, suppliers, manufacturers, + warrantors, owners, subcontractors, etc. + + Actors may either be project actors, who are responsible for the + delivery of the project, or occupants, who are responsible for the + consumption of the project. + + Identifying and managing actors is critical for asset management, and + identifying liability for legal submissions. + + :param actor: Most commonly, an IfcOrganization (in compliance with GDPR + requirements for non personally identifiable information), or an + IfcPerson if it is a sole individual, or an IfcPersonAndOrganization + if a specific person is liable within an organisation and must be + legally nominated. + :param ifc_class: Either "IfcActor" or "IfcOccupant". + :return: The newly created IfcActor or IfcOccupant + + Example: + + .. code:: python + + # Setup an organisation with a single role + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + role = ifcopenshell.api.owner.add_role(model, assigned_object=organisation, role="ARCHITECT") + + # Assign that organisation to a newly created actor + actor = ifcopenshell.api.owner.add_actor(model, actor=organisation) + """ + ifc_class = ifc_class or "IfcActor" + actor_ = ifcopenshell.api.root.create_entity(file, ifc_class=ifc_class) + actor_.TheActor = actor + return actor_ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_address.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_address.py new file mode 100644 index 0000000000000000000000000000000000000000..791f41c6a261b65c0880d80fa6a3ac320e0e82f8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_address.py @@ -0,0 +1,71 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Literal + + +ADDRESS_TYPE = Literal["IfcPostalAddress", "IfcTelecomAddress"] + + +def add_address( + file: ifcopenshell.file, assigned_object: ifcopenshell.entity_instance, ifc_class: ADDRESS_TYPE = "IfcPostalAddress" +) -> ifcopenshell.entity_instance: + """Add a new telecom or postal address to an organisation or person + + A person or organisation may have associated contact details such as + phone numbers, mailing addresses, websites, email addresses, and instant + messaging handles. This information is critical in recording the contact + information of manufacturers and suppliers for facility management, or + liable actors. + + There are two types of addresses, postal addresses for physical snail + mail, and telecom addresses for telephone or internet contact numbers + and addresses. + + :param assigned_object: The IfcOrganization or IfcPerson the contact + address belongs to. + :param ifc_class: Either IfcPostalAddress or IfcTelecomAddress. Defaults + to IfcPostalAddress. + :return: The new IfcPostalAddress or IfcTelecomAddress + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model) + + # A snail mail address + postal = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcPostalAddress") + ifcopenshell.api.owner.edit_address(model, address=postal, + attributes={"Purpose": "OFFICE", "AddressLines": ["42 Wallaby Way"], + "Town": "Sydney", "Region": "NSW", "PostalCode": "2000"}) + + # A phone or internet address + telecom = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcTelecomAddress") + ifcopenshell.api.owner.edit_address(model, address=telecom, + attributes={"Purpose": "OFFICE", "TelephoneNumbers": ["+61432466949"], + "ElectronicMailAddresses": ["bobthebuilder@example.com"], + "WWWHomePageURL": "https://thinkmoult.com"}) + """ + address = file.create_entity(ifc_class, "OFFICE") + addresses = list(assigned_object.Addresses) if assigned_object.Addresses else [] + addresses.append(address) + assigned_object.Addresses = addresses + return address diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_application.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_application.py new file mode 100644 index 0000000000000000000000000000000000000000..665bebc2922d91124f8642057889a1946ae1c844 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_application.py @@ -0,0 +1,123 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api +import ifcopenshell.api.owner +import ifcopenshell.api.pset +from typing import Optional, Any, Union + + +def add_application( + file: ifcopenshell.file, + application_developer: Optional[ifcopenshell.entity_instance] = None, + version: Optional[str] = None, + application_full_name: str = "IfcOpenShell", + application_identifier: str = "IfcOpenShell", +) -> ifcopenshell.entity_instance: + """Adds a new application + + IFC data may be associated with an authoring application to identify + which application was responsible for editing or authoring the data. An + application is defined by the developing organisation, as well as a full + name and identifier. This is akin to how web browsers have an + identification string. + + :param application_developer: The IfcOrganization responsible for + creating the application. Defaults to generating an IfcOpenShell + organisation if none is provided. + :param version: The version of the application. Defaults to the + ifcopenshell.version data if not specified. + :param application_full_name: The name of the application + :param application_identifier: An identification string for the + application intended for computers to read. + :return: The newly created IfcApplication + + Example: + + .. code:: python + + application = ifcopenshell.api.owner.add_application(model) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute( + application_developer, + version or ifcopenshell.version, + application_full_name, + application_identifier, + ) + + +class Usecase: + file: ifcopenshell.file + + def execute( + self, + application_developer: Union[ifcopenshell.entity_instance, None], + version: str, + application_full_name: str, + application_identifier: str, + ) -> ifcopenshell.entity_instance: + if not application_developer: + application_developer = self.create_application_organisation() + return self.file.create_entity( + "IfcApplication", + ApplicationDeveloper=application_developer, + Version=version, + ApplicationFullName=application_full_name, + ApplicationIdentifier=application_identifier, + ) + + def create_application_organisation(self) -> ifcopenshell.entity_instance: + result = self.file.create_entity( + "IfcOrganization", + **{ + "Name": "IfcOpenShell", + "Description": "IfcOpenShell is an open source software library that helps users and software developers to work with IFC data.", + "Roles": [ + self.file.create_entity("IfcActorRole", **{"Role": "USERDEFINED", "UserDefinedRole": "CONTRIBUTOR"}) + ], + }, + ) + # 0 IfcOrganization.Identification / Id (IFC2X3). + result[0] = "IfcOpenShell" + + # 4 IfcOrganization.Addresses + if self.file.schema == "IFC4X3": + # IfcTelecomAddress is deprecated in IFC4X3. + actor = ifcopenshell.api.owner.add_actor(self.file, result) + pset = ifcopenshell.api.pset.add_pset(self.file, actor, "PEnum_AddressType") + ifcopenshell.api.pset.edit_pset( + self.file, + pset, + properties={ + "Purpose": "OTHER", + "UserDefinedPurpose": "WEBPAGE", + "WWWHomePageURL": "https://ifcopenshell.org", + }, + ) + else: + result[4] = [ + self.file.create_entity( + "IfcTelecomAddress", + Purpose="USERDEFINED", + UserDefinedPurpose="WEBPAGE", + WWWHomePageURL="https://ifcopenshell.org", + ), + ] + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_organisation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_organisation.py new file mode 100644 index 0000000000000000000000000000000000000000..be308536e392f5132e866edbb85c048aec3fd0da --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_organisation.py @@ -0,0 +1,49 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def add_organisation( + file: ifcopenshell.file, identification: str = "APTR", name: str = "Aperture Science" +) -> ifcopenshell.entity_instance: + """Adds a new organisation + + Organisations are the main way to identify manufacturers, suppliers, and + other actors who do not have a single representative or must not have + any personally identifiable information. + + :param identification: The short code identifying the organisation. + Sometimes used in drawing naming schemes. Otherise used as a + canonicalised way of computers to identify the organisation. Like + their stock name. + :param name: The legal name of the organisation + :return: The newly created IfcOrganization + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + """ + data = {"Name": name} + if file.schema == "IFC2X3": + data["Id"] = identification + else: + data["Identification"] = identification + return file.create_entity("IfcOrganization", **data) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person.py new file mode 100644 index 0000000000000000000000000000000000000000..1953d800286b828d1d081607e9ee39b7800a34cd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person.py @@ -0,0 +1,50 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def add_person( + file: ifcopenshell.file, + identification: str = "HSeldon", + family_name: str = "Seldon", + given_name: str = "Hari", +) -> ifcopenshell.entity_instance: + """Adds a new person + + Persons are used to identify a legal or liable representative of an + organisation or point of contact. + + :param identification: The computer readable unique identification of + the person. For example, their username in a CDE or alias. + :param family_name: The family name + :param given_name: The given name + :return: The newly created IfcPerson + + Example: + + .. code:: python + + ifcopenshell.api.owner.add_person(model, + identification="bobthebuilder", family_name="Thebuilder", given_name="Bob") + """ + data = {"FamilyName": family_name, "GivenName": given_name} + if file.schema == "IFC2X3": + data["Id"] = identification + else: + data["Identification"] = identification + return file.create_entity("IfcPerson", **data) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person_and_organisation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person_and_organisation.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbec452c06b4fd0bd4e5eb0f9f4c263919d5eed --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_person_and_organisation.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def add_person_and_organisation( + file: ifcopenshell.file, + person: ifcopenshell.entity_instance, + organisation: ifcopenshell.entity_instance, +) -> ifcopenshell.entity_instance: + """Adds a paired person and organisation + + A person and an organisation may be paired to create a representative + belonging to a company. + + :param person: The IfcPerson being the representative of the + organisation. + :param organisation: The IfcOrganization it + :return: The newly created IfcPersonAndOrganization + + Example: + + .. code:: python + + person = ifcopenshell.api.owner.add_person(model, + identification="lecorbycorbycorb", family_name="Curbosiar", given_name="Le") + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + + ifcopenshell.api.owner.add_person_and_organisation(model, + person=person, organisation=organisation) + """ + return file.create_entity("IfcPersonAndOrganization", person, organisation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_role.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_role.py new file mode 100644 index 0000000000000000000000000000000000000000..6ebe013fc41526e85effdc22e25481364ef24478 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/add_role.py @@ -0,0 +1,58 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def add_role( + file: ifcopenshell.file, assigned_object: ifcopenshell.entity_instance, role: str = "ARCHITECT" +) -> ifcopenshell.entity_instance: + """Adds and assigns a new role + + People and organisations must play one or more roles on a project. Roles + include architects, engineers, subcontractors, clients, manufacturers, + etc. Typically these roles and their corresponding responsibilities will + be outlined in contractual documents. + + This function will both add and assign the role to the person or + organisation. + + :param assigned_object: The IfcPerson or IfcOrganization the role should + be assigned to. + :param role: The type of role, taken from the IFC documentation for + IfcActorRole, or a custom name. Defaults to "ARCHITECT". + :return: The newly created IfcActorRole + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + ifcopenshell.api.owner.add_role(model, assigned_object=organisation, role="ARCHITECT") + """ + element = file.create_entity("IfcActorRole", Role="ARCHITECT") + if role: + try: + element.Role = role + except: + element.Role = "USERDEFINED" + element.UserDefinedRole = role + roles = list(assigned_object.Roles) if assigned_object.Roles else [] + roles.append(element) + assigned_object.Roles = roles + return element diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/assign_actor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/assign_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..3056cf07bc800457e944970c3c3c7f6d86b0fec7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/assign_actor.py @@ -0,0 +1,99 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid + + +def assign_actor( + file: ifcopenshell.file, relating_actor: ifcopenshell.entity_instance, related_object: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + """Assigns an actor to an object + + An actor may be assigned to objects which implies that the actor is + responsible for. This is most commonly used in facility management for + indicating the manufacturers, suppliers, and warrantors for product + types. + + Here are a list of objects you may assign an actor to: + + * IfcControl: Indicates project directives issued by the actor. + * IfcGroup: Indicates groups for which the actor is responsible. + * IfcProduct: Indicates products for which the actor is responsible. + * IfcProcess: Indicates processes for which the actor is responsible. + * IfcResource: Indicates resources for which the actor is responsible to + allocate, manage, or delegate. This is not the actor actually using + the resource or performing the work. For that type of actor, see + ifcopenshell.api.resource.assign_resource. + + :param relating_actor: The IfcActor who is responsible for the object. + :param related_object: The object the actor is responsible for. + :return: The newly created IfcRelAssignsToActor relationship. + + Example: + + .. code:: python + + # We need to procure and install 2 of this particular pump type in our facility. + pump_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcPumpType") + + # Define who the manufacturer is + manufacturer = ifcopenshell.api.owner.add_organisation(model, + identification="PWP", name="Pumps With Power") + ifcopenshell.api.owner.add_role(model, assigned_object=manufacturer, role="MANUFACTURER") + + # To help our facility manager, it's nice to provide contact details + # of the manufacturer so they know how to call when the pump breaks. + telecom = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcTelecomAddress") + ifcopenshell.api.owner.edit_address(model, address=telecom, + attributes={"Purpose": "OFFICE", "TelephoneNumbers": ["+61432466949"], + "ElectronicMailAddresses": ["contact@example.com"], + "WWWHomePageURL": "https://example.com"}) + + # Make the manufacturer responsible for that pump type. + ifcopenshell.api.owner.assign_actor(model, + relating_actor=manufacturer, related_object=pump_type) + """ + if related_object.HasAssignments: + for rel in related_object.HasAssignments: + if rel.is_a("IfcRelAssignsToActor") and rel.RelatingActor == relating_actor: + return rel + + rel = None + + if relating_actor.IsActingUpon: + rel = relating_actor.IsActingUpon[0] + + if rel: + related_objects = list(rel.RelatedObjects) + related_objects.append(related_object) + rel.RelatedObjects = related_objects + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + rel = file.create_entity( + "IfcRelAssignsToActor", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": [related_object], + "RelatingActor": relating_actor, + } + ) + return rel diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/create_owner_history.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/create_owner_history.py new file mode 100644 index 0000000000000000000000000000000000000000..296834062e8e780c636abb93d213e5b48e513c74 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/create_owner_history.py @@ -0,0 +1,116 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import time +import ifcopenshell +import ifcopenshell.api.owner.settings +from typing import Union + + +def create_owner_history(file: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None]: + """Creates a new owner history indicating an element was added + + Any object in IFC with a unique ID and name (such as physical products, + tasks, calendars, etc) may have an owner associated with it. An owner is + a liable person and/or organisation which a bit of metadata indicating + whether they have created the object, edited the object, when the change + was made, and which application they used. + + IFC does not offer a comprehensive specification for version control and + change tracking, as this is completely out of scope. However this + similar ability allows IFC to satisfy legal requirements where object + ownership, responsibilities, and permissions must be specified. + Recording the owner is mandatory in IFC2X3 but optional in IFC4. It is + not recommended to store this ownership data in IFC4 unless a legal + requirement is in place. + + Because owner tracking is mandatory in IFC2X3, be aware that some + configuration may be required to work correctly. Read on. + + To track the owner, at a minimum we have to know the application that + the element was authored from, as well as the user (person and + organisation) that made the change. The IfcOpenShell API is a low level + software library and will not know what application the API is being + called from, and nor does it have the responsibility to manage the + "active user" making edits, which may be as simple as hardcoding it to + "Bob" or even be as complex as integration with a CDE's authentication + system. As a result, the developer responsible to integrate with + IfcOpenShell is expected to overload the + ifcopenshell.api.owner.settings.get_user and + ifcopenshell.api.owner.settings.get_application functions. + + It is not necessary to call this function directly if you are already + using other API calls. It is a low level function only available if you + are writing your own advanced scripts and want to take advantage of the + easier ownership tracking. + + :return: The newly created IfcOwnerHistory element or `None` if it's + not IFC2X3 and user or application is not found in the current project. + + Example: + + .. code:: python + + # Let's imagine we're writing a small script, not large enough to be + # its own fully branded application. In this case, let's use the + # default application which is prepopulated with "IfcOpenShell" as + # the name and version. + application = ifcopenshell.api.owner.add_application(model) + + # Let's imagine we run this as an automated QA process in an + # architectural firm. However, the results must be signed off by the + # registered architect who is liable for the project. + person = ifcopenshell.api.owner.add_person(model, + identification="LPARTEE", family_name="Partee", given_name="Leeable") + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + user = ifcopenshell.api.owner.add_person_and_organisation(model, + person=person, organisation=organisation) + + # Let's configure our owner settings to hardcode always returning + # the application and user. In theory, you could build complex user + # access control lookup functions here, but this is simple enough. + ifcopenshell.api.owner.settings.get_user = lambda x: user + ifcopenshell.api.owner.settings.get_application = lambda x: application + + # We've finished our ownership setup. Now let's start our script and + # create a space. Notice we don't actually call + # create_owner_history at all. This is already automatically handled + # by the API when necessary. Under the hood, the API is actually + # running this code on the IfcSpace element: + # element.OwnerHistory = ifcopenshell.api.owner.create_owner_history(model) + space = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSpace") + """ + + user = ifcopenshell.api.owner.settings.get_user(file) + if file.schema != "IFC2X3" and not user: + return + application = ifcopenshell.api.owner.settings.get_application(file) + if file.schema != "IFC2X3" and not application: + return + return file.create_entity( + "IfcOwnerHistory", + OwningUser=user, + OwningApplication=application, + State="READWRITE", + ChangeAction="ADDED", + LastModifiedDate=int(time.time()), + LastModifyingUser=user, + LastModifyingApplication=application, + CreationDate=int(time.time()), + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_actor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad238f994468859bc70f70481f93919a4ceb260 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_actor.py @@ -0,0 +1,50 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_actor(file: ifcopenshell.file, actor: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcActor + + For more information about the attributes and data types of an + IfcActor, consult the IFC documentation. + + :param actor: The IfcActor entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + # Setup an organisation with a single role + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + role = ifcopenshell.api.owner.add_role(model, assigned_object=organisation) + ifcopenshell.api.owner.edit_role(model, role=role, attributes={"Role": "ARCHITECT"}) + + # Assign that organisation to a newly created actor + actor = ifcopenshell.api.owner.add_actor(model, actor=organisation) + + # Edit the description of the attribute. + ifcopenshell.api.actor.edit_actor(model, + actor=actor, attributes={"Description": "Responsible for buildings A, B, and C."}) + """ + for name, value in attributes.items(): + setattr(actor, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_address.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_address.py new file mode 100644 index 0000000000000000000000000000000000000000..52e80d6ef13916f7fad71a3a3f2673acf4a6d216 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_address.py @@ -0,0 +1,52 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_address(file: ifcopenshell.file, address: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcAddress + + For more information about the attributes and data types of an + IfcAddress, consult the IFC documentation. + + :param address: The IfcAddress entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + # A snail mail address + postal = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcPostalAddress") + ifcopenshell.api.owner.edit_address(model, address=postal, + attributes={"Purpose": "OFFICE", "AddressLines": ["42 Wallaby Way"], + "Town": "Sydney", "Region": "NSW", "PostalCode": "2000"}) + + # A phone or internet address + telecom = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcTelecomAddress") + ifcopenshell.api.owner.edit_address(model, address=telecom, + attributes={"Purpose": "OFFICE", "TelephoneNumbers": ["+61432466949"], + "ElectronicMailAddresses": ["bobthebuilder@example.com"], + "WWWHomePageURL": "https://thinkmoult.com"}) + """ + for name, value in attributes.items(): + setattr(address, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_application.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_application.py new file mode 100644 index 0000000000000000000000000000000000000000..3224169ff28b8fef9d7b72bc4aac93749f0668f1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_application.py @@ -0,0 +1,44 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_application( + file: ifcopenshell.file, application: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcApplication + + For more information about the attributes and data types of an + IfcApplication, consult the IFC documentation. + + :param application: The IfcApplication entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + application = ifcopenshell.api.owner.add_application(model, + application_full_name="My App") + ifcopenshell.api.owner.edit_application(model, application=application, + attributes={"ApplicationFullName": "My App New Name"}) + """ + for name, value in attributes.items(): + setattr(application, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_organisation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_organisation.py new file mode 100644 index 0000000000000000000000000000000000000000..a2bb5e3eb63191508cb4f69f7a46e11a0e0c36ff --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_organisation.py @@ -0,0 +1,44 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_organisation( + file: ifcopenshell.file, organisation: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcOrganization + + For more information about the attributes and data types of an + IfcOrganization, consult the IFC documentation. + + :param organisation: The IfcOrganization entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects With Ballpens") + ifcopenshell.api.owner.edit_organisation(model, organisation=organisation, + attributes={"name": "Architects Without Ballpens"}) + """ + for name, value in attributes.items(): + setattr(organisation, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_person.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_person.py new file mode 100644 index 0000000000000000000000000000000000000000..6b697bd6744cea86b5fb021b7691ac02e562c352 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_person.py @@ -0,0 +1,42 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_person(file: ifcopenshell.file, person: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcPerson + + For more information about the attributes and data types of an + IfcPerson, consult the IFC documentation. + + :param person: The IfcPerson entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + person = ifcopenshell.api.owner.add_person(model, + identification="bobthebuilder", family_name="Thebuilder", given_name="Bob") + ifcopenshell.api.owner.edit_person(model, person=person, + attributes={"MiddleNames": ["The"], "FamilyName": "Builder"}) + """ + for name, value in attributes.items(): + setattr(person, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_role.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_role.py new file mode 100644 index 0000000000000000000000000000000000000000..fca80a16b0fc262df7770bd2cad343fdb3d61681 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/edit_role.py @@ -0,0 +1,46 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_role(file: ifcopenshell.file, role: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + """Edits the attributes of an IfcActorRole + + For more information about the attributes and data types of an + IfcActorRole, consult the IFC documentation. + + :param role: The IfcActorRole entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + person = ifcopenshell.api.owner.add_person(model, + identification="bobthebuilder", family_name="Thebuilder", given_name="Bob") + + # By default, the role is an architect + role = ifcopenshell.api.owner.add_role(model, assigned_object=person) + + # But Bob is not an architect + ifcopenshell.api.owner.edit_role(model, role=role, attributes={"Role": "CONSTRUCTIONMANAGER"}) + """ + for name, value in attributes.items(): + setattr(role, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_actor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..dd86a6f937e7c5fcbadf16c41c0a5e8da89eea21 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_actor.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_actor(file: ifcopenshell.file, actor: ifcopenshell.entity_instance) -> None: + """Removes an actor + + :param actor: The IfcActor to remove. + :return: None + + Example: + + .. code:: python + + # Setup an organisation with a single role + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + role = ifcopenshell.api.owner.add_role(model, assigned_object=organisation) + ifcopenshell.api.owner.edit_role(model, role=role, attributes={"Role": "ARCHITECT"}) + + # Assign that organisation to a newly created actor + actor = ifcopenshell.api.owner.add_actor(model, actor=organisation) + + # Actually we need ballpens on this project + ifcopenshell.api.owner.remove_actor(model, actor=actor) + """ + history = actor.OwnerHistory + file.remove(actor) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_address.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_address.py new file mode 100644 index 0000000000000000000000000000000000000000..28942943a4ea490ed542c6ff0d02de9db023af2e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_address.py @@ -0,0 +1,45 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_address(file: ifcopenshell.file, address: ifcopenshell.entity_instance) -> None: + """Removes an address + + Naturally, any organisations or people using that address will have the + relationship removed. + + :param address: The IfcAddress to remove. + :return: None + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model) + address = ifcopenshell.api.owner.add_address(model, + assigned_object=organisation, ifc_class="IfcPostalAddress") + + # Change our mind and delete it + ifcopenshell.api.owner.remove_address(model, address=address) + """ + for inverse in file.get_inverse(address): + if inverse.is_a() in ("IfcOrganization", "IfcPerson"): + if inverse.Addresses == (address,): + inverse.Addresses = None + file.remove(address) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_application.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_application.py new file mode 100644 index 0000000000000000000000000000000000000000..1a63bc494989de6283fedf14997c769b93afda0f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_application.py @@ -0,0 +1,37 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_application(file: ifcopenshell.file, application: ifcopenshell.entity_instance) -> None: + """Removes an application + + Warning: removing an application may invalidate ownership histories. + Check whether or not the application is used anywhere prior to removal. + + :param address: The IfcApplication to remove. + :return: None + + Example: + + .. code:: python + + application = ifcopenshell.api.owner.add_application(model) + ifcopenshell.api.owner.remove_address(model, application=application) + """ + file.remove(application) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_organisation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_organisation.py new file mode 100644 index 0000000000000000000000000000000000000000..acee11d9f5e2ae00f5f8d0feaa412b4b3fca8b6a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_organisation.py @@ -0,0 +1,65 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.root +import ifcopenshell.api.owner + + +def remove_organisation(file: ifcopenshell.file, organisation: ifcopenshell.entity_instance) -> None: + """Remove an organisation + + All roles and addresses assigned to the organisation will also be + removed. + + :param organisation: The IfcOrganization to remove + :return: None + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + ifcopenshell.api.owner.remove_organisation(model, organisation=organisation) + """ + for role in organisation.Roles or []: + if (file.get_total_inverses(role)) == 1: + ifcopenshell.api.owner.remove_role(file, role=role) + for address in organisation.Addresses or []: + if (file.get_total_inverses(address)) == 1: + ifcopenshell.api.owner.remove_address(file, address=address) + for inverse in file.get_inverse(organisation): + if inverse.is_a("IfcOrganizationRelationship"): + if inverse.RelatingOrganization == organisation: + file.remove(inverse) + elif inverse.RelatedOrganizations == (organisation,): + file.remove(inverse) + elif inverse.is_a("IfcDocumentInformation"): + if inverse.Editors == (organisation,): + inverse.Editors = None + elif inverse.is_a("IfcPersonAndOrganization"): + ifcopenshell.api.owner.remove_person_and_organisation(file, person_and_organisation=inverse) + elif inverse.is_a("IfcActor"): + ifcopenshell.api.root.remove_product(file, product=inverse) + elif inverse.is_a("IfcResourceLevelRelationship") and not inverse.is_a("IfcOrganizationRelationship"): + if inverse.RelatedResourceObjects == (organisation,): + file.remove(inverse) + elif inverse.is_a("IfcApplication"): + ifcopenshell.api.owner.remove_application(file, application=inverse) + + file.remove(organisation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person.py new file mode 100644 index 0000000000000000000000000000000000000000..0c618c1e74ca56b525cbfdb404bcef853f970726 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person.py @@ -0,0 +1,68 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.root +import ifcopenshell.api.owner + + +def remove_person(file: ifcopenshell.file, person: ifcopenshell.entity_instance) -> None: + """Remove an person + + All roles and addresses assigned to the person will also be + removed. + In IFC2X3 will also remove related inventories if `person` was + the only responsile person for them. + + :param person: The IfcPerson to remove + :return: None + + Example: + + .. code:: python + + ifcopenshell.api.owner.add_person(model, + identification="bobthebuilder", family_name="Thebuilder", given_name="Bob") + ifcopenshell.api.owner.remove_person(model, person=person) + """ + + for role in person.Roles or []: + if file.get_total_inverses(role) == 1: + ifcopenshell.api.owner.remove_role(file, role=role) + for address in person.Addresses or []: + if file.get_total_inverses(address) == 1: + ifcopenshell.api.owner.remove_address(file, address=address) + for inverse in file.get_inverse(person): + if inverse.is_a("IfcWorkControl"): + if inverse.Creators == (person,): + inverse.Creators = None + elif inverse.is_a("IfcInventory"): + if inverse.ResponsiblePersons == (person,): + # in IFC2X3 ResponsiblePersons is not optional and without it IfcInventory is not valid + if file.schema == "IFC2X3": + ifcopenshell.api.root.remove_product(file, product=inverse) + elif inverse.is_a("IfcDocumentInformation"): + if inverse.Editors == (person,): + inverse.Editors = None + elif inverse.is_a("IfcPersonAndOrganization"): + ifcopenshell.api.owner.remove_person_and_organisation(file, person_and_organisation=inverse) + elif inverse.is_a("IfcActor"): + ifcopenshell.api.root.remove_product(file, product=inverse) + elif inverse.is_a("IfcResourceLevelRelationship"): + if inverse.RelatedResourceObjects == (person,): + file.remove(inverse) + file.remove(person) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person_and_organisation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person_and_organisation.py new file mode 100644 index 0000000000000000000000000000000000000000..13607b22f389ad65d678fe4f06e07fd872cf4f87 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_person_and_organisation.py @@ -0,0 +1,58 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.root + + +def remove_person_and_organisation( + file: ifcopenshell.file, person_and_organisation: ifcopenshell.entity_instance +) -> None: + """Removes a person and organisation + + Note that the underlying person and organisation is not removed, only + the "person and organisation" group. + + :param person_and_organisation: The IfcPersonAndOrganization to remove. + :return: None + + Example: + + .. code:: python + + person = ifcopenshell.api.owner.add_person(model, + identification="lecorbycorbycorb", family_name="Curbosiar", given_name="Le") + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + + user = ifcopenshell.api.owner.add_person_and_organisation(model, + person=person, organisation=organisation) + + ifcopenshell.api.owner.remove_person_and_organisation(model, person_and_organisation=user) + """ + for inverse in file.get_inverse(person_and_organisation): + if inverse.is_a("IfcDocumentInformation"): + if inverse.Editors == (person_and_organisation,): + inverse.Editors = None + elif inverse.is_a("IfcActor"): + ifcopenshell.api.root.remove_product(file, product=inverse) + elif inverse.is_a("IfcResourceLevelRelationship"): + if inverse.RelatedResourceObjects == (person_and_organisation,): + file.remove(inverse) + elif inverse.is_a("IfcOwnerHistory"): + file.remove(inverse) + file.remove(person_and_organisation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_role.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_role.py new file mode 100644 index 0000000000000000000000000000000000000000..f3869e7579623ab1fba60459edea93ed5069e661 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/remove_role.py @@ -0,0 +1,49 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_role(file: ifcopenshell.file, role: ifcopenshell.entity_instance) -> None: + """Removes a role + + People and organisations using the role will be untouched. This may + leave some of them without roles. + + :param role: The IfcActorRole to remove. + :return: None + + Example: + + .. code:: python + + organisation = ifcopenshell.api.owner.add_organisation(model, + identification="AWB", name="Architects Without Ballpens") + role = ifcopenshell.api.owner.add_role(model, assigned_object=organisation, role="ARCHITECT") + + # After running this, the organisation will have no role again + ifcopenshell.api.owner.remove_role(model, role=role) + """ + for inverse in file.get_inverse(role): + if inverse.is_a() in ("IfcOrganization", "IfcPerson", "IfcPersonAndOrganization"): + if inverse.Roles == (role,): + inverse.Roles = None + elif inverse.is_a("IfcResourceLevelRelationship"): + # IfcResourceConstraintRelationship or other rels with IfcResourceObjectSelect. + if inverse.RelatedResourceObjects == (role,): + file.remove(inverse) + file.remove(role) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/settings.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/settings.py new file mode 100644 index 0000000000000000000000000000000000000000..b5dedfff49d2bae6c6eea8620c3a5c32cf7ce8a2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/settings.py @@ -0,0 +1,102 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +# Note: it is the intent for you to override these with your own functions + + +import ifcopenshell +from typing import Union + + +def get_application(ifc: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None]: + """Returns the application representing the authoring software + + It is expected for you to overload this function with your own + IfcApplication. See ifcopenshell.api.owner.create_owner_history for details. + + :param ifc: The IFC file object that is being edited. + :return: The IfcApplication with metadata of the authoring software. + """ + app = next(iter(ifc.by_type("IfcApplication")), None) + if not app and ifc.schema == "IFC2X3": + raise Exception( + "Please create an application to continue. See the owner.create_owner_history docs for more info." + "https://docs.ifcopenshell.org/autoapi/ifcopenshell/api/owner/create_owner_history/index.html" + ) + return app + + +def get_user(ifc: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None]: + """Returns the active authoring user + + It is expected for you to overload this function with your own + IfcApplication. See ifcopenshell.api.owner.create_owner_history for details. + + :param ifc: The IFC file object that is being edited. + :return: The IfcPersonAndOrganization with metadata of the authoring user. + """ + pao = next(iter(ifc.by_type("IfcPersonAndOrganization")), None) + if not pao and ifc.schema == "IFC2X3": + raise Exception( + "Please create a user to continue. See the owner.create_owner_history docs for more info." + "https://docs.ifcopenshell.org/autoapi/ifcopenshell/api/owner/create_owner_history/index.html" + ) + return pao + + +get_application_factory = get_application +get_application_backup = get_application +get_user_factory = get_user +get_user_backup = get_user + + +def factory_reset(): + """Reset the get_user and get_application functions to what came out of box + + When you are developing a custom application, you will typically override + the get_user and get_application function to your own needs. Sometimes you + want to reset it to before you monkey-patched it. This function does that + reset. + """ + global get_application_factory + global get_application_backup + global get_application + global get_user_factory + global get_user_backup + global get_user + get_application_backup = get_application + get_application = get_application_factory + get_user_backup = get_user + get_user = get_user_factory + + +def restore(): + """Restore the get_user and get_application function prior to a reset + + In case you want to restore the monkey-patched version of get_user and + get_application that existed before you applied a factory_reset(), this + function will do that. + """ + global get_application_factory + global get_application_backup + global get_application + global get_user_factory + global get_user_backup + global get_user + get_application = get_application_backup + get_user = get_user_backup diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/unassign_actor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/unassign_actor.py new file mode 100644 index 0000000000000000000000000000000000000000..1912fa0e088869814f755a20d00a37f3c4ea222a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/unassign_actor.py @@ -0,0 +1,67 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_actor( + file: ifcopenshell.file, relating_actor: ifcopenshell.entity_instance, related_object: ifcopenshell.entity_instance +) -> None: + """Unassigns an actor to an object + + This means that the actor is no longer responsible for the object. + + :param relating_actor: The IfcActor who is responsible for the object. + :param related_object: The object the actor is responsible for. + :return: None + + Example: + + .. code:: python + + # We need to procure and install 2 of this particular pump type in our facility. + pump_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcPumpType") + + # Define who the manufacturer is + manufacturer = ifcopenshell.api.owner.add_organisation(model, + identification="PWP", name="Pumps With Power") + ifcopenshell.api.owner.add_role(model, assigned_object=manufacturer, role="MANUFACTURER") + + # Make the manufacturer responsible for that pump type. + ifcopenshell.api.owner.assign_actor(model, + relating_actor=manufacturer, related_object=pump_type) + + # Undo the assignment + ifcopenshell.api.owner.unassign_actor(model, + relating_actor=manufacturer, related_object=pump_type) + """ + for rel in related_object.HasAssignments or []: + if not rel.is_a("IfcRelAssignsToActor") or rel.RelatingActor != relating_actor: + continue + if len(rel.RelatedObjects) == 1: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + return + related_objects = list(rel.RelatedObjects) + related_objects.remove(related_object) + rel.RelatedObjects = related_objects + ifcopenshell.api.owner.update_owner_history(file, element=rel) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/update_owner_history.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/update_owner_history.py new file mode 100644 index 0000000000000000000000000000000000000000..99ec6f18d5fcf83ea28cbd28b0f38be87c69d121 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/owner/update_owner_history.py @@ -0,0 +1,88 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import time +import ifcopenshell +import ifcopenshell.api +import ifcopenshell.api.owner.settings +import ifcopenshell.util.element +from typing import Union + + +def update_owner_history( + file: ifcopenshell.file, element: ifcopenshell.entity_instance +) -> Union[ifcopenshell.entity_instance, None]: + """Updates the owner that is assigned to an object + + This ensures that the owner is tracked to have modified the object last, + including the time when the change occured. See + ifcopenshell.api.owner.create_owner_history for details. + + :param element: The IfcRoot element to update the ownership details on + when a change is made. + :return: The updated IfcOwnerHistory element. + + Example: + + .. code:: python + + # See ifcopenshell.api.owner.create_owner_history for setup + # [ ... example setup code ... ] + + # We've finished our ownership setup. Now let's start our script and + # create a space. Notice we don't actually call + # create_owner_history at all. This is already automatically handled + # by the API when necessary. Under the hood, the API is actually + # running this code on the IfcSpace element: + # element.OwnerHistory = ifcopenshell.api.owner.create_owner_history(model) + space = ifcopenshell.api.root.create_entity(model, ifc_class="IfcSpace") + + # Any edits we make will have ownership tracking automatically + # applied. There is no need to run any owner.update_owner_history + # API calls either. + ifcopenshell.api.attribute.edit_attributes(model, product=space, attributes={"Name": "Lobby"}) + """ + if not element.is_a("IfcRoot"): + return + user = ifcopenshell.api.owner.settings.get_user(file) + if not user: + return + application = ifcopenshell.api.owner.settings.get_application(file) + if not application: + return + + # 1 IfcRoot IfcOwnerHistory + owner_history = element[1] + if not owner_history: + owner_history = ifcopenshell.api.owner.create_owner_history(file) + element[1] = owner_history + return owner_history + + if file.get_total_inverses(owner_history) > 1: + owner_history = ifcopenshell.util.element.copy(file, owner_history) + element[1] = owner_history + + # 3 IfcOwnerHistory ChangeAction + owner_history[3] = "MODIFIED" + # 4 IfcOwnerHistory LastModifiedDate + owner_history[4] = int(time.time()) + # 5 IfcOwnerHistory LastModifyingUser + owner_history[5] = user + # 6 IfcOwnerHistory LastModifyingApplication + owner_history[6] = application + return owner_history diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3a438e35b4313075143e2ff652b718c414cf8f47 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/__init__.py @@ -0,0 +1,42 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Create an IFC project + +All IFCs must have one, and only one IFC project before any data may be +associated. If you are starting from scratch, see :func:create_file. + +Once a project exists, you may optionally create project libraries and +associate type assets with it. You may also append assets from other projects +into your project. +""" + +from .. import wrap_usecases +from .append_asset import append_asset +from .assign_declaration import assign_declaration +from .create_file import create_file +from .unassign_declaration import unassign_declaration + +wrap_usecases(__path__, __name__) + +__all__ = [ + "append_asset", + "assign_declaration", + "create_file", + "unassign_declaration", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/append_asset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/append_asset.py new file mode 100644 index 0000000000000000000000000000000000000000..22eb022e999611893d651b667de2594b270673bb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/append_asset.py @@ -0,0 +1,765 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.ifcopenshell_wrapper as W +import ifcopenshell.api.geometry +import ifcopenshell.api.type +import ifcopenshell.api.project +import ifcopenshell.api.context +import ifcopenshell.api.owner.settings +import ifcopenshell.util.element +import ifcopenshell.util.geolocation +import ifcopenshell.util.placement +import ifcopenshell.util.unit +from typing import Optional, Any, Union, Literal, get_args, Callable +from functools import partial + + +APPENDABLE_ASSET = Literal[ + "IfcTypeProduct", + "IfcProduct", + "IfcMaterial", + "IfcCostSchedule", + "IfcProfileDef", + "IfcPresentationStyle", +] +APPENDABLE_ASSET_TYPES = get_args(APPENDABLE_ASSET) +MATERIAL_SETS = ("IfcMaterialLayerSet", "IfcMaterialConstituentSet", "IfcMaterialProfileSet") + + +def append_asset( + file: ifcopenshell.file, + library: ifcopenshell.file, + element: ifcopenshell.entity_instance, + reuse_identities: Optional[dict[int, ifcopenshell.entity_instance]] = None, + assume_asset_uniqueness_by_name: bool = True, +) -> ifcopenshell.entity_instance: + """Appends an asset from a library into the active project + + A BIM library asset may be a type product (e.g. wall type), product + (e.g. pump), material, profile, or cost schedule. + + This copies the asset from the specified library file into the active + project. It handles all details like ensuring that product materials, + styles, properties, quantities, and so on are preserved. + + If an asset contains geometry, the geometric contexts are also + intelligentely transplanted such that existing equivalent contexts are + reused. + + Do not mix units. + + :param library: The file object containing the asset. + :param element: An element in the library file of the asset. It may be + an IfcTypeProduct, IfcProduct, IfcMaterial, IfcCostSchedule, or + IfcProfileDef. + :param reuse_identities: Optional dictionary of mapped entities' identities to the + already created elements. It will be used to avoid creating + duplicated inverse elements during multiple `project.append_asset` calls. If you want + to add just 1 asset or if added assets won't have any shared elements, then it can be left empty. + :param assume_asset_uniqueness_by_name: If True, checks if elements (profiles, materials, styles) + with the same name already exist in the project and reuses them instead of appending new ones. + :return: The appended element + + Example: + + .. code:: python + + # Programmatically generate a library. You could do this visually too. + library = ifcopenshell.api.project.create_file() + root = ifcopenshell.api.root.create_entity(library, ifc_class="IfcProject", name="Demo Library") + context = ifcopenshell.api.root.create_entity(library, + ifc_class="IfcProjectLibrary", name="Demo Library") + ifcopenshell.api.project.assign_declaration(library, definitions=[context], relating_context=root) + + # Assign units for our example library + unit = ifcopenshell.api.unit.add_si_unit(library, + unit_type="LENGTHUNIT", prefix="MILLI") + ifcopenshell.api.unit.assign_unit(library, units=[unit]) + + # Let's create a single asset of a 200mm thick concrete wall + wall_type = ifcopenshell.api.root.create_entity(library, ifc_class="IfcWallType", name="WAL01") + concrete = ifcopenshell.api.material.add_material(usecase.file, name="CON", category="concrete") + rel = ifcopenshell.api.material.assign_material(library, + products=[wall_type], type="IfcMaterialLayerSet") + layer = ifcopenshell.api.material.add_layer(library, + layer_set=rel.RelatingMaterial, material=concrete) + layer.Name = "Structure" + layer.LayerThickness = 200 + + # Mark our wall type as a reusable asset in our library. + ifcopenshell.api.project.assign_declaration(library, + definitions=[wall_type], relating_context=context) + + # Let's imagine we're starting a new project + model = ifcopenshell.api.project.create_file() + project = ifcopenshell.api.root.create_entity(model, ifc_class="IfcProject", name="Test") + + # Now we can easily append our wall type from our library + wall_type = ifcopenshell.api.project.append_asset(model, library=library, element=wall_type) + + Example of adding multiple assets and avoiding duplicated inverses: + + .. code:: python + + # since occurrences of IfcWindow of the same type + # might have shared inverses (e.g. IfcStyledItem) + # we provide a dictionary that will be populated with newly created items + # and reused to avoid duplicated elements + reuse_identities = dict() + + for element in ifcopenshell.util.selector.filter_elements(model, "IfcWindow"): + ifcopenshell.api.project.append_asset( + model, library=library, + element=wall_type + reuse_identities=reuse_identities + ) + + """ + usecase = Usecase() + usecase.file: ifcopenshell.file = file + usecase.settings = { + "library": library, + "element": element, + "reuse_identities": {} if reuse_identities is None else reuse_identities, + "assume_asset_uniqueness_by_name": assume_asset_uniqueness_by_name, + } + return usecase.execute() + + +class SafeRemovalContext: + """Context manager to ensure `remove_deep` won't create invalid entities + in `reuse_identities` leading to possible crashes. + + Should be always used if removing an entity that was possibly added by `file_add`. + """ + + file: ifcopenshell.file + reuse_identities: dict[int, ifcopenshell.entity_instance] + + assume_asset_uniqueness_by_name: bool + """If `False`, then all job is done by `file.add` + and we don't need to worry about invalid entities.""" + + def __init__( + self, + ifc_file: ifcopenshell.file, + reuse_identities: dict[int, ifcopenshell.entity_instance], + assume_asset_uniqueness_by_name: bool, + ): + self.file = ifc_file + self.reuse_identities = reuse_identities + self.assume_asset_uniqueness_by_name = assume_asset_uniqueness_by_name + + def __enter__(self): + if not self.assume_asset_uniqueness_by_name: + return + + ifcopenshell.util.element.batch_remove_deep2(self.file) + + def __exit__(self, *args): + if not self.assume_asset_uniqueness_by_name: + return + + # Collect identities. + removed_identities: dict[ifcopenshell.entity_instance, int] = {} + assert self.file.to_delete is not None + removed_elements = self.file.to_delete + for identity, element in self.reuse_identities.items(): + if element in removed_elements: + removed_identities[element] = identity + assert len(removed_identities) == len(removed_elements) + + # Actually remove elements. + for element in self.file.to_delete: + if element in self.file.to_delete: + self.file.remove(element) + self.file.to_delete = None + + # Clean up dead identities. + for identity in removed_identities.values(): + del self.reuse_identities[identity] + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + assume_asset_uniqueness_by_name: bool + whitelisted_inverse_attributes: dict[str, list[str]] + + added_elements: dict[int, ifcopenshell.entity_instance] + """Elements added with ``add_element``.""" + + reuse_identities: dict[int, ifcopenshell.entity_instance] + """Mapping of old element ids to new elements, usually fiiled by ``file_add``.""" + + def execute(self): + # mapping of old element ids to new elements + self.added_elements: dict[int, ifcopenshell.entity_instance] = {} + self.reuse_identities: dict[int, ifcopenshell.entity_instance] = self.settings["reuse_identities"] + self.whitelisted_inverse_attributes = {} + self.base_material_class = "IfcMaterial" if self.file.schema == "IFC2X3" else "IfcMaterialDefinition" + self.assume_asset_uniqueness_by_name = self.settings["assume_asset_uniqueness_by_name"] + + if self.settings["element"].is_a("IfcTypeProduct"): + self.target_class = "IfcTypeProduct" + return self.append_type_product() + elif self.settings["element"].is_a("IfcProduct"): + self.target_class = "IfcProduct" + return self.append_product() + elif self.settings["element"].is_a("IfcMaterial"): + self.target_class = "IfcMaterial" + return self.append_material() + elif self.settings["element"].is_a("IfcCostSchedule"): + self.target_class = "IfcCostSchedule" + return self.append_cost_schedule() + elif self.settings["element"].is_a("IfcProfileDef"): + self.target_class = "IfcProfileDef" + return self.append_profile_def() + elif self.settings["element"].is_a("IfcPresentationStyle"): + self.target_class = "IfcPresentationStyle" + return self.append_presentation_style() + + def by_guid(self, guid: str) -> Union[ifcopenshell.entity_instance, None]: + try: + return self.file.by_guid(guid) + except RuntimeError: + return None + + def get_existing_element(self, element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """Get existing element for a library element. + + Return element if it was already added with ``add_element`` + or if it's not necessary (model already has a replacement for it). + + Note that if element is returned, it will be accepted as-is, + it's subgraph inverses won't be checked. + + Return ``None`` if element wasn't added before and needs to be added. + """ + if element.id() in self.added_elements: + return self.added_elements[element.id()] + if element.is_a("IfcRoot"): + return self.by_guid(element.GlobalId) + elif not self.assume_asset_uniqueness_by_name: + return None + elif element.is_a("IfcMaterial"): + name = element.Name + return next((e for e in self.file.by_type("IfcMaterial") if e.Name == name), None) + + elif element in MATERIAL_SETS: + ifc_class = element.is_a() + name_attr = "LayerSetName" if ifc_class == "IfcMaterialLayerSet" else "Name" + material_set_name = getattr(element, name_attr) + if material_set_name is None: + return + return next((e for e in self.file.by_type(ifc_class) if getattr(e, name_attr) == material_set_name), None) + + elif element.is_a("IfcProfileDef"): + profile_name = element.ProfileName + if profile_name is None: + return None + return next((e for e in self.file.by_type("IfcProfileDef") if e.ProfileName == profile_name), None) + elif element.is_a("IfcPresentationStyle"): + name = element.Name + if name is None: + return None + return next((e for e in self.file.by_type(element.is_a()) if e.Name == name), None) + + # Not really assets but if we don't check them here, + # their subgraph entities may be appended twice. + elif (ifc_class := element.is_a()) == "IfcOrganization": + attr_name = "Id" if self.file.schema == "IFC2X3" else "Identification" + org_id = getattr(element, attr_name) + if org_id is not None: + return next((e for e in self.file.by_type("IfcOrganization") if getattr(e, attr_name) == org_id), None) + elif ifc_class == "IfcPerson": + attr_name = "Id" if self.file.schema == "IFC2X3" else "Identification" + person_id = getattr(element, attr_name) + if person_id is not None: + return next((e for e in self.file.by_type("IfcPerson") if getattr(e, attr_name) == person_id), None) + + else: + return None + + def append_material(self): + self.whitelisted_inverse_attributes = { + "IfcMaterial": ["HasExternalReferences", "HasProperties", "HasRepresentation"] + } + self.existing_contexts = self.file.by_type("IfcGeometricRepresentationContext") + element = self.add_element(self.settings["element"]) + if element.HasRepresentation: + self.reuse_existing_contexts() + return element + + def append_cost_schedule(self): + self.whitelisted_inverse_attributes = {"IfcCostSchedule": ["Controls"], "IfcCostItem": ["IsNestedBy"]} + return self.add_element(self.settings["element"]) + + def append_profile_def(self): + self.whitelisted_inverse_attributes = {"IfcProfileDef": ["HasProperties"]} + return self.add_element(self.settings["element"]) + + def append_presentation_style(self): + self.whitelisted_inverse_attributes = {} + return self.add_element(self.settings["element"]) + + def append_type_product(self): + self.whitelisted_inverse_attributes = { + "IfcObjectDefinition": ["HasAssociations"], + self.base_material_class: ["HasExternalReferences", "HasProperties", "HasRepresentation"], + "IfcRepresentationItem": ["StyledByItem", "LayerAssignment"], + "IfcRepresentation": ["LayerAssignments"], + "IfcProductDefinitionShape": ["HasShapeAspects"], + "IfcRepresentationMap": ["HasShapeAspects"], + } + self.existing_contexts = self.file.by_type("IfcGeometricRepresentationContext") + element = self.add_element(self.settings["element"]) + self.reuse_existing_contexts() + return element + + def append_product(self): + self.whitelisted_inverse_attributes = { + "IfcObjectDefinition": ["HasAssociations"], + "IfcObject": ["IsDefinedBy.IfcRelDefinesByProperties"], + "IfcElement": ["HasOpenings"], + self.base_material_class: ["HasExternalReferences", "HasProperties", "HasRepresentation"], + "IfcRepresentationItem": [ + "StyledByItem", + "LayerAssignments" if self.file.schema == "IFC2X3" else "LayerAssignment", + ], + "IfcRepresentation": ["LayerAssignments"], + "IfcProductDefinitionShape": ["HasShapeAspects"], + "IfcRepresentationMap": ["HasShapeAspects"], + } + self.existing_contexts = self.file.by_type("IfcGeometricRepresentationContext") + element = self.add_element(self.settings["element"]) + self.reuse_existing_contexts() + + placement = element.ObjectPlacement + if placement is not None: + matrix = ifcopenshell.util.placement.get_local_placement(placement) + matrix = ifcopenshell.util.geolocation.auto_local2global(self.settings["library"], matrix) + matrix = ifcopenshell.util.geolocation.auto_global2local(self.file, matrix) + with SafeRemovalContext(self.file, self.reuse_identities, self.assume_asset_uniqueness_by_name): + ifcopenshell.api.geometry.edit_object_placement(self.file, element, matrix, is_si=False) + + element_type = ifcopenshell.util.element.get_type(self.settings["element"]) + if element_type: + ifcopenshell.api.owner.settings.factory_reset() + new_type = ifcopenshell.api.project.append_asset( + self.file, + library=self.settings["library"], + element=element_type, + reuse_identities=self.reuse_identities, + ) + ifcopenshell.api.type.assign_type( + self.file, + should_run_listeners=False, + related_objects=[element], + relating_type=new_type, + should_map_representations=False, + ) + ifcopenshell.api.owner.settings.restore() + + return element + + def add_element(self, element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """Add element and check all it's subgraph inverses.""" + if element.id() == 0: + return + existing_element = self.get_existing_element(element) + if existing_element: + return existing_element + new = self.file_add(element) + self.added_elements[element.id()] = new + self.check_inverses(element) + subelement_queue = self.settings["library"].traverse(element, max_levels=1)[1:] + while subelement_queue: + subelement = subelement_queue.pop(0) + existing_element = self.get_existing_element(subelement) + if existing_element: + self.added_elements[subelement.id()] = existing_element + if not self.has_whitelisted_inverses(existing_element): + self.check_inverses(subelement) + else: + self.added_elements[subelement.id()] = self.file_add(subelement) + self.check_inverses(subelement) + subelement_queue.extend(self.settings["library"].traverse(subelement, max_levels=1)[1:]) + return new + + def has_whitelisted_inverses(self, element: ifcopenshell.entity_instance) -> bool: + for source_class, attributes in self.whitelisted_inverse_attributes.items(): + if not element.is_a(source_class): + continue + for attribute in attributes: + attribute_class = None + if "." in attribute: + attribute, attribute_class = attribute.split(".") + value = getattr(element, attribute, []) + if attribute_class: + for subvalue in value: + if subvalue.is_a(attribute_class): + return True + elif value: + return True + return False + + def check_inverses(self, element: ifcopenshell.entity_instance) -> None: + """Add inverse elements for the whitelisted inverse attributes.""" + for source_class, attributes in self.whitelisted_inverse_attributes.items(): + if not element.is_a(source_class): + continue + for attribute in attributes: + attribute_class = None + if "." in attribute: + attribute, attribute_class = attribute.split(".") + for inverse in getattr(element, attribute, []): + if attribute_class and inverse.is_a(attribute_class): + self.add_inverse_element(inverse) + elif not attribute_class: + self.add_inverse_element(inverse) + + def add_inverse_element(self, element: ifcopenshell.entity_instance) -> None: + """Add inverse element. + + Inverse elements are requiring different method than ``file_add`` + because they can reference many other assets that we are not + interested in. + + E.g. a IfcRelAssociatesMaterial referencing products unrelated + to the current asset. + """ + # For layer assignment we don't want to add it's items + # to avoid adding representations / items that are not related to current append_asset. + skip_not_reused_entities_attr_i = None + if element.is_a("IfcPresentationLayerAssignment"): + # 3 IfcPresentationLayerAssignment.AssignedItems + skip_not_reused_entities_attr_i = 2 + + element_identity = element.wrapped_data.identity() + + # Check if inverse element was created before. + # Still need to recreate it again - e.g. it could be some rel + # that now needs it's RelatingObjects to be extended by the current asset. + existing_rel = None + if (new := self.reuse_identities.get(element_identity)) is not None: + # Currently known cases requiring attributes reassignment are rels. + if not new.is_a("IfcRelationship"): + return + elif element.is_a("IfcRelationship") and (existing_rel := self.by_guid(element.GlobalId)): + new = existing_rel + else: + new = self.file.create_entity(element.is_a()) + self.reuse_identities[element_identity] = new + + for i, attribute in enumerate(element): + new_attribute = None + if isinstance(attribute, ifcopenshell.entity_instance): + # Void and projection relationships are special because they + # are "dependent" relationships, so we always consider them. + # We do _not_ whitelist (i.e. in is_another_asset) + # IfcFeatureElement because you can have things like + # IfcRelAssociatesClassification to openings! We only ever want + # to consider IfcFeatureElements in IfcRelVoidsElements and + # IfcRelProjectsElements. + if element.is_a() in ("IfcRelVoidsElement", "IfcRelProjectsElement") or not self.is_another_asset( + attribute + ): + new_attribute = self.add_element(attribute) + elif isinstance(attribute, tuple) and attribute and isinstance(attribute[0], ifcopenshell.entity_instance): + new_attribute = [] + for item in attribute: + if self.is_another_asset(item): + continue + if skip_not_reused_entities_attr_i is not None and i == skip_not_reused_entities_attr_i: + identity = item.wrapped_data.identity() + if (item := self.reuse_identities.get(identity)) is None: + continue + else: + item = self.add_element(item) + new_attribute.append(item) + # If rel exists we need to make sure previously assigned elements are untouched + # e.g. not to assign a material or a pset from element. + if existing_rel: + new_attribute.extend(existing_rel[i]) + new_attribute = list(set(new_attribute)) + else: + new_attribute = attribute + if new_attribute is not None: + new[i] = new_attribute + + def is_another_asset(self, element: ifcopenshell.entity_instance) -> bool: + """Is IFC entity from inverse attribute is another asset to append that should be skipped.""" + if element == self.settings["element"]: + return False + elif element.is_a("IfcRoot") and self.by_guid(element.GlobalId) is not None: + return False + elif element.is_a(self.target_class): + return True + elif self.target_class == "IfcProduct" and element.is_a("IfcTypeProduct"): + return True + elif self.target_class == "IfcTypeProduct" and element.is_a("IfcProduct"): + return True + return False + + def reuse_existing_contexts(self) -> None: + added_contexts = set([e for e in self.added_elements.values() if e.is_a("IfcGeometricRepresentationContext")]) + added_contexts -= set(self.existing_contexts) + sorted_added_contexts = [c for c in added_contexts if c.is_a() == "IfcGeometricRepresentationContext"] + sorted_added_contexts.extend([c for c in added_contexts if c.is_a() == "IfcGeometricRepresentationSubContext"]) + for added_context in sorted_added_contexts: + equivalent_existing_context = self.get_equivalent_existing_context(added_context) + if not equivalent_existing_context: + equivalent_existing_context = self.create_equivalent_context(added_context) + for inverse in self.file.get_inverse(added_context): + ifcopenshell.util.element.replace_attribute(inverse, added_context, equivalent_existing_context) + + with SafeRemovalContext(self.file, self.reuse_identities, self.assume_asset_uniqueness_by_name): + for added_context in added_contexts: + ifcopenshell.util.element.remove_deep2(self.file, added_context) + + def get_equivalent_existing_context( + self, added_context: ifcopenshell.entity_instance + ) -> Union[ifcopenshell.entity_instance, None]: + for context in self.existing_contexts: + if context.is_a() != added_context.is_a(): + continue + if context.is_a("IfcGeometricRepresentationSubContext"): + if ( + context.ContextType == added_context.ContextType + and context.ContextIdentifier == added_context.ContextIdentifier + and context.TargetView == added_context.TargetView + ): + return context + elif ( + context.ContextType == added_context.ContextType + and context.ContextIdentifier == added_context.ContextIdentifier + ): + return context + + def create_equivalent_context(self, added_context: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + if added_context.is_a("IfcGeometricRepresentationSubContext"): + parent = self.get_equivalent_existing_context(added_context.ParentContext) + if not parent: + parent = self.create_equivalent_context(added_context.ParentContext) + self.existing_contexts.append(parent) + context = ifcopenshell.api.context.add_context( + self.file, + parent=parent, + context_type=added_context.ContextType, + context_identifier=added_context.ContextIdentifier, + target_view=added_context.TargetView, + ) + else: + context = ifcopenshell.api.context.add_context( + self.file, + context_type=added_context.ContextType, + context_identifier=added_context.ContextIdentifier, + ) + self.existing_contexts.append(context) + return context + + def file_add( + self, element: ifcopenshell.entity_instance, conversion_factor: Optional[float] = None + ) -> ifcopenshell.entity_instance: + """Reimplementation of `file.add` but taking into account that some elements (profiles, materials) + are already existing (checking by their name) and shouldn't be duplicated. + + The problem with `file.add` it's recursively adding element and all it's attributes + and there is no control to prevent it from adding certain type of elements. + """ + + def get_conversion_factor() -> float: + nonlocal conversion_factor + if conversion_factor is not None: + return conversion_factor + library_scale = ifcopenshell.util.unit.calculate_unit_scale(self.settings["library"]) + current_scale = ifcopenshell.util.unit.calculate_unit_scale(ifc_file) + conversion_factor = library_scale / current_scale + return conversion_factor + + ifc_file = self.file + if not self.assume_asset_uniqueness_by_name or element.id() == 0: + # file.add doesn't convert units for IfcLengthMeasure entities. + if element.is_a("IfcLengthMeasure"): + return ifc_file.create_entity(element.is_a(), element.wrappedValue * get_conversion_factor()) + return ifc_file.add(element) + + reuse_identities = self.reuse_identities + element_identity = element.wrapped_data.identity() + if added_element := reuse_identities.get(element_identity): + return added_element + + ifc_class = element.is_a() + attributes_ = None + + def get_attributes() -> tuple[W.attribute, ...]: + nonlocal attributes_ + if attributes_ is not None: + return attributes_ + attributes_ = element.wrapped_data.declaration().as_entity().all_attributes() + return attributes_ + + def get_existing_element_( + subelement: ifcopenshell.entity_instance, + ) -> Union[ifcopenshell.entity_instance, None]: + # Check identity because `subelement` might not be the current `element`, + # e.g. for IfcPersonAndOrganization. + element_identity = subelement.wrapped_data.identity() + if subelement_ := reuse_identities.get(element_identity): + return subelement_ + + ifc_class = subelement.is_a() + assert ifc_class in ("IfcOrganization", "IfcPerson") + attr_name = "Id" if ifc_file.schema == "IFC2X3" else "Identification" + subelement_id = getattr(subelement, attr_name) + + if subelement_id is not None: + existing_org = next( + (e for e in ifc_file.by_type(ifc_class) if getattr(e, attr_name) == subelement_id), None + ) + if existing_org is not None: + reuse_identities[element_identity] = existing_org + return existing_org + + # Check if element already exists. + # NOTE: Ensure this part is in sync with `get_existing_element`, + # if some class is present here but not in `get_existing_element`, + # then it might create duplicated subelements. + if element.is_a("IfcProfileDef"): + profile_name = element.ProfileName + if profile_name is not None: + existing_profile = next( + (e for e in ifc_file.by_type("IfcProfileDef") if e.ProfileName == profile_name), None + ) + if existing_profile is not None: + reuse_identities[element_identity] = existing_profile + return existing_profile + + elif element.is_a("IfcMaterial"): + material_name = element.Name + existing_material = next((e for e in ifc_file.by_type("IfcMaterial") if e.Name == material_name), None) + if existing_material is not None: + reuse_identities[element_identity] = existing_material + return existing_material + + elif ifc_class in MATERIAL_SETS: + name_attr = "LayerSetName" if ifc_class == "IfcMaterialLayerSet" else "Name" + material_set_name = getattr(element, name_attr) + if material_set_name is not None: + existing_material_set = next( + (e for e in ifc_file.by_type(ifc_class) if getattr(e, name_attr) == material_set_name), None + ) + if existing_material_set is not None: + reuse_identities[element_identity] = existing_material_set + return existing_material_set + + elif element.is_a("IfcPresentationStyle"): + style_name = element.Name + if style_name is not None: + existing_style = next((e for e in ifc_file.by_type(ifc_class) if e.Name == style_name), None) + if existing_style is not None: + reuse_identities[element_identity] = existing_style + return existing_style + + elif ifc_class == "IfcApplication": + app_id = element.ApplicationIdentifier + if app_id is not None: + existing_app = next( + (e for e in ifc_file.by_type("IfcApplication") if e.ApplicationIdentifier == app_id), None + ) + if existing_app is not None: + reuse_identities[element_identity] = existing_app + return existing_app + + elif ifc_class == "IfcOrganization": + existing_org = get_existing_element_(element) + if existing_org is not None: + reuse_identities[element_identity] = existing_org + return existing_org + + elif ifc_class == "IfcPerson": + existing_person = get_existing_element_(element) + if existing_person is not None: + reuse_identities[element_identity] = existing_person + return existing_person + + elif ifc_class == "IfcPersonAndOrganization": + if (person := get_existing_element_(element.ThePerson)) and ( + org := get_existing_element_(element.TheOrganization) + ): + for pao in ifc_file.by_type("IfcPersonAndOrganization"): + if pao.ThePerson == person and pao.TheOrganization == org: + reuse_identities[element_identity] = pao + return pao + + attrs: dict[int, Any] = {} + + # Utils method for the loop. + def get_tuple_type(tuple_: tuple) -> type: + while isinstance(tuple_, tuple): + tuple_ = tuple_[0] + return type(tuple_) + + def is_length_measure(attribute: W.attribute) -> bool: + return ">" in str(attribute.type_of_attribute()) + + def apply_to_array(arr: Any, func: Callable[[Any], Any]) -> Any: + if isinstance(arr, tuple): + return tuple(apply_to_array(sub, func) for sub in arr) + return func(arr) + + file_add_ = partial(self.file_add, conversion_factor=conversion_factor) + apply_conversion = lambda x: x * conversion_factor + + # Migrate attributes to another file. + for attr_index, attr_value in enumerate(element): + # `None` is set by default already. + if attr_value is None: + continue + + elif isinstance(attr_value, ifcopenshell.entity_instance): + attr_value = file_add_(attr_value) + + elif isinstance(attr_value, tuple): + # Assume type is consistent across the tuple. + tuple_type = get_tuple_type(attr_value) + if tuple_type == ifcopenshell.entity_instance: + attr_value = apply_to_array(attr_value, file_add_) + elif tuple_type == float: + attributes = get_attributes() + if is_length_measure(attributes[attr_index]): + get_conversion_factor() # Ensure conversion factor is not None. + attr_value = apply_to_array(attr_value, apply_conversion) + + elif isinstance(attr_value, float): + attributes = get_attributes() + if is_length_measure(attributes[attr_index]): + attr_value *= get_conversion_factor() + + attrs[attr_index] = attr_value + + # Adding entity at the end just to keep it consistent with `file.add`. + new = ifc_file.create_entity(ifc_class) + reuse_identities[element_identity] = new + for attr_index, attr_value in attrs.items(): + new[attr_index] = attr_value + + return new diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/assign_declaration.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/assign_declaration.py new file mode 100644 index 0000000000000000000000000000000000000000..2daa7dc7293be092877d7c9984610f10883934e1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/assign_declaration.py @@ -0,0 +1,141 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Union + + +def assign_declaration( + file: ifcopenshell.file, + definitions: list[ifcopenshell.entity_instance], + relating_context: ifcopenshell.entity_instance, +) -> Union[ifcopenshell.entity_instance, None]: + """Declares the list of elements to the project + + Feature was added in IFC4. + + All data in a model must be directly or indirectly related to the + project. Most data is indirectly related, existing instead within the + spatial decomposition tree. Other data, such as types, may be declared + at the top level. + + Most of the time, the API handles declaration automatically for you. + There is one scenario where you might want to explicitly declare objects + to the project, and that's when you want to organise objects into + project libraries for future use (such as an assets library). Assigning + a declaration lets you say that an object belongs to a library. + + :param definitions: The list of objects you want to declare. Typically a list of assets. + :param relating_context: The IfcProject, or more commonly the + IfcProjectLibrary that you want the object to be part of. + :return: The new IfcRelDeclares relationship or None if all definitions + were already declared / do not support declaration. + + Example: + + .. code:: python + + # Programmatically generate a library. You could do this visually too. + library = ifcopenshell.api.project.create_file() + root = ifcopenshell.api.root.create_entity(library, ifc_class="IfcProject", name="Demo Library") + context = ifcopenshell.api.root.create_entity(library, + ifc_class="IfcProjectLibrary", name="Demo Library") + + # It's necessary to say our library is part of our project. + ifcopenshell.api.project.assign_declaration(library, definitions=[context], relating_context=root) + + # Assign units for our example library + unit = ifcopenshell.api.unit.add_si_unit(library, + unit_type="LENGTHUNIT", prefix="MILLI") + ifcopenshell.api.unit.assign_unit(library, units=[unit]) + + # Let's create a single asset of a 200mm thick concrete wall + wall_type = ifcopenshell.api.root.create_entity(library, ifc_class="IfcWallType", name="WAL01") + concrete = ifcopenshell.api.material.add_material(file, name="CON", category="concrete") + rel = ifcopenshell.api.material.assign_material(library, + products=[wall_type], type="IfcMaterialLayerSet") + layer = ifcopenshell.api.material.add_layer(library, + layer_set=rel.RelatingMaterial, material=concrete) + layer.Name = "Structure" + layer.LayerThickness = 200 + + # Mark our wall type as a reusable asset in our library. + ifcopenshell.api.project.assign_declaration(library, + definitions=[wall_type], relating_context=context) + + # All done, just for fun let's save our asset library to disk for later use. + library.write("/path/to/my-library.ifc") + """ + + all_declares = relating_context.Declares + definitions_set = set(definitions) + + previous_declares_rels: set[ifcopenshell.entity_instance] = set() + objects_without_contexts: list[ifcopenshell.entity_instance] = [] + objects_with_contexts: list[ifcopenshell.entity_instance] = [] + + # check if there is anything to change + for definition in definitions_set: + has_context = getattr(definition, "HasContext", None) + if has_context is None: + continue + + object_rel = next(iter(has_context), None) + if object_rel is None: + objects_without_contexts.append(definition) + continue + + # either rel doesn't exist or product is part of different rel + if object_rel not in all_declares: + previous_declares_rels.add(object_rel) + objects_with_contexts.append(definition) + + objects_to_change = objects_without_contexts + objects_with_contexts + # nothing to change + if not objects_to_change: + return None + + for has_context in previous_declares_rels: + related_definitions = set(has_context.RelatedDefinitions) - set(objects_with_contexts) + if related_definitions: + has_context.RelatedDefinitions = list(related_definitions) + ifcopenshell.api.owner.update_owner_history(file, element=has_context) + else: + history = has_context.OwnerHistory + file.remove(has_context) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + declares = next(iter(all_declares), None) + if declares: + declares.RelatedDefinitions = list(set(declares.RelatedDefinitions) | set(objects_to_change)) + ifcopenshell.api.owner.update_owner_history(file, element=declares) + else: + declares = file.create_entity( + "IfcRelDeclares", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedDefinitions": list(objects_to_change), + "RelatingContext": relating_context, + }, + ) + return declares diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/create_file.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/create_file.py new file mode 100644 index 0000000000000000000000000000000000000000..41bc45fdd561947c53187f4f409ebd9386cb4297 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/create_file.py @@ -0,0 +1,62 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021, 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import datetime +import ifcopenshell +import ifcopenshell.util.schema + + +def create_file(version: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4") -> ifcopenshell.file: + """Create a blank IFC model file object + + Create a new IFC file object based on the nominated schema version. The + schema version you choose determines what type of IFC data you can store + in this model. The file is blank and contains no entities. + + It also sets up header data for STEP file serialisation, such as the + current timestamp, IfcOpenShell as the preprocessor, and defaults to a + DesignTransferView MVD. + + :param version: The schema version of the IFC file. Choose from + "IFC2X3", "IFC4", or "IFC4X3". If you have loaded in a custom + schema, you may specify that schema identifier here too. + :return: The created IFC file object. + + Example: + + .. code:: python + + # Start a new model. + model = ifcopenshell.api.project.create_file() + + # It's currently a blank model, so typically the first thing we do + # is create a project in it. + project = ifcopenshell.api.root.create_entity(model, ifc_class="IfcProject", name="Test") + + # ... and off we go! + """ + file = ifcopenshell.file(schema=version) + file.header.file_name.name = "/dev/null" # Hehehe + file.header.file_name.time_stamp = ( + datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc).astimezone().replace(microsecond=0).isoformat() + ) + file.header.file_name.preprocessor_version = "IfcOpenShell {}".format(ifcopenshell.version) + file.header.file_name.originating_system = "IfcOpenShell {}".format(ifcopenshell.version) + file.header.file_name.authorization = "Nobody" + file.header.file_description.description = ("ViewDefinition[DesignTransferView]",) + return file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/unassign_declaration.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/unassign_declaration.py new file mode 100644 index 0000000000000000000000000000000000000000..75bf389dfd7a4b7ca301c8bb8b7c9fa67c0f9d3d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/project/unassign_declaration.py @@ -0,0 +1,72 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_declaration( + file: ifcopenshell.file, + definitions: list[ifcopenshell.entity_instance], + relating_context: ifcopenshell.entity_instance, +) -> None: + """Unassigns a list of objects from a project or project library + + Typically used to remove an asset from a project library. + + :param definitions: The list of objects you want to undeclare. + Typically a list of assets. + :param relating_context: The IfcProject, or more commonly the + IfcProjectLibrary that you want the object to no longer be part of. + :return: None + + Example: + + .. code:: python + + # Programmatically generate a library. You could do this visually too. + library = ifcopenshell.api.project.create_file() + root = ifcopenshell.api.root.create_entity(library, ifc_class="IfcProject", name="Demo Library") + context = ifcopenshell.api.root.create_entity(library, + ifc_class="IfcProjectLibrary", name="Demo Library") + + # It's necessary to say our library is part of our project. + ifcopenshell.api.project.assign_declaration(library, definitions=[context], relating_context=root) + + # Remove the library from our project + ifcopenshell.api.project.unassign_declaration(library, definitions=[context], relating_context=root) + """ + settings = { + "definitions": definitions, + "relating_context": relating_context, + } + + definitions = set(settings["definitions"]) + rels = {rel for obj in definitions if (rel := next(iter(obj.HasContext), None))} + + for rel in rels: + related_definitions = set(rel.RelatedDefinitions) - definitions + if related_definitions: + rel.RelatedDefinitions = list(related_definitions) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..90333d164aef5b4484f9679de82e485f8b90aa21 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/__init__.py @@ -0,0 +1,47 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Property sets and quantity sets let you store simple key value metadata +associated with elements + +This is the simplest and most common way to store information about an element. +For example, if a door has a fire rating, it is stored as a property. +""" + +from .. import wrap_usecases +from .add_pset import add_pset +from .add_qto import add_qto +from .assign_pset import assign_pset +from .edit_pset import edit_pset +from .edit_qto import edit_qto +from .remove_pset import remove_pset +from .unassign_pset import unassign_pset +from .unshare_pset import unshare_pset + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_pset", + "add_qto", + "assign_pset", + "edit_pset", + "edit_qto", + "remove_pset", + "unassign_pset", + "unshare_pset", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a99bd84720b8a4ed79337f9533f2a9ce72e6f2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_pset.py @@ -0,0 +1,171 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.api.pset +import ifcopenshell.guid +from typing import Optional, Any + + +def add_pset( + file: ifcopenshell.file, + product: ifcopenshell.entity_instance, + name: str, + ifc2x3_subclass: Optional[str] = None, +) -> ifcopenshell.entity_instance: + """Adds a new property set to a product + + Products, such as physical objects or types in IFC may have properties + associated with them. These properties are typically simple key value + metadata with data types. For example, a wall type may have a property + called FireRating with a text value of "2HR". Properties are grouped + into property sets, so that related properties are grouped together. + + If a property is assigned to a type, the property is inherited by all + occurrences of that type. For example, a wall type with a FireRating + property of "2HR" automatically implies that all walls of that wall type + also have a FireRating of "2HR". It is not necessary to explictly define + the property again for each occurrence. This also means that properties + are typically defined on types. If the same property is defined at an + occurrence, this overrides the property defined on the type. + + buildingSMART has come up with a long list of standardised properties + for the most common properties required internationally. This solves the + age-old question of "where do I store my FireRating data for walls"? The + answer, in this case, is in the "FireRating" property with an "IfcLabel" + data type grouped in the "Pset_WallCommon" property set. It is + recommended to view the list of standardised buildingSMART properties + and see if any suit your needs first. If none are appropriate, then you + are free to create your own custom properties. + + This function adds a blank named property set. One you have a property + set you may add properties using ifcopenshell.api.pset.edit_pset. + + See also ifcopenshell.api.pset.add_qto if you want to add quantification + data, rather than arbitrary metadata. + + :param product: The IfcObject that you want to assign a property set to. + :param name: The name of the property set. Property sets that are + standardised by buildingSMART typically have a prefix of "Pset_", + like "Pset_WallCommon". If you create your own, you must not use + that prefix. It is recommended to use your own prefix tailored to + your project, company, or local government requirement. + + In IFC2X3 should be provided as an empty string for profile properties + (they all don't have a name property) and all material properties + besides IfcExtendedMaterialProperties. + :param ifc2x3_subclass: IFC2X3 subclass for material or profile properties. + In IFC2X3 IfcProfileProperties and IfcMaterialProperties are abstract + so you need one of their subclasses to instantiate them. + By default, for profile will be created IfcGeneralProfileProperties + and for material - IfcExtendedMaterialProperties. + Will have no effect in >=IFC4. + + :raises TypeError: If `product` class doesn't support adding a pset. + + :return: The newly created IfcPropertySet + + Example: + + .. code:: python + + # Let's imagine we have a new wall type. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType") + + # Note that this only creates and assigns an empty property set. We + # still need to add properties into the property set. Having blank + # property sets are invalid. + pset = ifcopenshell.api.pset.add_pset(model, product=wall_type, name="Pset_WallCommon") + + # Add a fire rating property standardised by buildingSMART. + ifcopenshell.api.pset.edit_pset(model, pset=pset, properties={"FireRating": "2HR"}) + """ + is_ifc2x3 = file.schema == "IFC2X3" + + if product.is_a("IfcObject") or product.is_a("IfcContext"): + for rel in product.IsDefinedBy or []: + if rel.is_a("IfcRelDefinesByProperties") and rel.RelatingPropertyDefinition.Name == name: + return rel.RelatingPropertyDefinition + + pset = file.create_entity( + "IfcPropertySet", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "Name": name, + }, + ) + ifcopenshell.api.pset.assign_pset(file, [product], pset) + return pset + + elif product.is_a("IfcTypeObject"): + for definition in product.HasPropertySets or []: + if definition.Name == name: + return definition + + pset = file.create_entity( + "IfcPropertySet", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "Name": name, + }, + ) + ifcopenshell.api.pset.assign_pset(file, [product], pset) + return pset + + # in IFC2X3 IfcMaterialDefinition not yet existed + elif product.is_a("IfcMaterialDefinition") or product.is_a("IfcMaterial"): + kwargs: dict[str, Any] + kwargs = {"Material": product} + if file.schema == "IFC2X3": + ifc_class = ifc2x3_subclass or "IfcExtendedMaterialProperties" + definitions = (d for d in file.by_type("IfcMaterialProperties") if d.Material == product) + if ifc_class == "IfcExtendedMaterialProperties": + kwargs["Name"] = name + else: + ifc_class = "IfcMaterialProperties" + definitions = product.HasProperties + kwargs["Name"] = name + for definition in definitions: + # In IFC2X3 not all IfcMaterialProperties has Name + if getattr(definition, "Name", None) == name: + return definition + + return file.create_entity(ifc_class, **kwargs) + + elif product.is_a("IfcProfileDef"): + # in IFC2X3 IfcProfileProperties doesn't have Name and we cannot identify them + if file.schema != "IFC2X3": + for definition in product.HasProperties or []: + if definition.Name == name: + return definition + + kwargs = {} + kwargs["ProfileDefinition"] = product + if file.schema != "IFC2X3": + kwargs["Name"] = name + + if is_ifc2x3: + ifc_class = ifc2x3_subclass or "IfcGeneralProfileProperties" + else: + ifc_class = "IfcProfileProperties" + return file.create_entity(ifc_class, **kwargs) + + raise TypeError(f"Class '{product.is_a(True)}' doesn't support adding a property set.") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_qto.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_qto.py new file mode 100644 index 0000000000000000000000000000000000000000..695ca21dd82754bd45cf8a8a4cc4c667449df8ed --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/add_qto.py @@ -0,0 +1,127 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +from typing import Any + + +def add_qto(file: ifcopenshell.file, product: ifcopenshell.entity_instance, name: str) -> ifcopenshell.entity_instance: + """Adds a new quantity set to a product + + Products, such as physical objects or types in IFC may have quantities + associated with them. These quantities are typically simple key value + metadata with data types. For example, a wall type may have a quantity + called NetSideArea with a area value of "4.2". Quantities are grouped + into quantity sets, so that related quantities are grouped together. + + Quantities are similar to, but different from properties in that they + may store a method of measurement or formula. Quantities may also have + parametric relationships to other calculated values, such as cost + schedules, resource utilisation, or construction task durations. + + buildingSMART has come up with a long list of standardised quantities + for the most common quantities required internationally. This solves the + age-old question of "what's the standard way of storing quantity + take-off data"? It is recommended to view the list of standardised + buildingSMART quantities and see if any suit your needs first. If none + are appropriate, then you are free to create your own custom quantities. + + This function adds a blank named quantity set. One you have a quantity + set you may add quantities using ifcopenshell.api.pset.edit_qto. + + See also ifcopenshell.api.pset.add_qto if you want to arbitrary + metadata, rather than quantification data. + + :param product: The IfcObject that you want to assign a quantity set to. + :param name: The name of the quantity set. Quantity sets that are + standardised by buildingSMART typically have a prefix of "Qto_", + like "Qto_WallBaseQuantities". If you create your own, you must not + use that prefix. It is recommended to use your own prefix tailored + to your project, company, or local government requirement. + :return: The newly created IfcElementQuantity + + Example: + + .. code:: python + + # Let's imagine we have a new wall. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Note that this only creates and assigns an empty quantity set. We + # still need to add quantities into the property set. Having blank + # quantity sets are invalid. + qto = ifcopenshell.api.pset.add_qto(model, product=wall_type, name="Qto_WallBaseQuantities") + + # Add a side area property standardised by buildingSMART. This + # allows quantity take-off to occur, even though no geometry has + # even been modelled! + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"NetSideArea": 4.2}) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = {"product": product, "name": name} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + product: ifcopenshell.entity_instance = self.settings["product"] + name: str = self.settings["name"] + + if product.is_a("IfcObject") or product.is_a("IfcContext"): + for rel in product.IsDefinedBy or []: + if ( + rel.is_a("IfcRelDefinesByProperties") + and rel.RelatingPropertyDefinition.Name == self.settings["name"] + ): + return rel.RelatingPropertyDefinition + + qto = self.create_qto() + self.file.create_entity( + "IfcRelDefinesByProperties", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(self.file), + "RelatedObjects": [self.settings["product"]], + "RelatingPropertyDefinition": qto, + } + ) + return qto + elif product.is_a("IfcTypeObject"): + for definition in product.HasPropertySets or []: + if definition.Name == name: + return definition + qto = self.create_qto() + has_property_sets = list(product.HasPropertySets or []) + has_property_sets.append(qto) + product.HasPropertySets = has_property_sets + return qto + + def create_qto(self): + return self.file.create_entity( + "IfcElementQuantity", + GlobalId=ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(self.file), + Name=self.settings["name"], + MethodOfMeasurement="BaseQuantities" if self.settings["name"].endswith("BaseQuantities") else None, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/assign_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/assign_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..ed309944a19f3d291bb197ea6c6080da04b85134 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/assign_pset.py @@ -0,0 +1,94 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Union + + +def assign_pset( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + pset: ifcopenshell.entity_instance, +) -> Union[ifcopenshell.entity_instance, None]: + """Assign property set to provided elements. + + This method can be used to make psets shared by multiple elements. + + :param products: Elements (or element types) to assign the pset to. + :param pset: Property set. + :return: None if `products` is empty or has only type elements. + IfcRelDefinesByProperties if `products` contains occurrences. + + Example: + + .. code:: python + + element = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + ifcopenshell.api.pset.assign_pset(model, [element], pset) + # Pset is now assigned. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element} + + element1 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + element2 = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + ifcopenshell.api.pset.assign_pset(model, [element1, element2], pset) + # Pset is now shared by multiple elements. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element, element1, element2} + + # Same for element types. + element_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType") + ifcopenshell.api.pset.assign_pset(model, [element_type], type_pset) + # Pset is now assigned to the type. + assert ifcopenshell.util.element.get_elements_by_pset(type_pset) == {element_type} + """ + is_ifc2x3 = file.schema == "IFC2X3" + + products_occurrences: set[ifcopenshell.entity_instance] = set() + products_types: set[ifcopenshell.entity_instance] = set() + for product in products: + if product.is_a("IfcTypeProduct"): + products_types.add(product) + else: + products_occurrences.add(product) + + rel = None + # Check occurrences using pset. + if products_occurrences: + rels = pset.PropertyDefinitionOf if is_ifc2x3 else pset.DefinesOccurrence + rel = next(iter(rels), None) + if rel is not None: + objs = set(rel.RelatedObjects) | products_occurrences + rel.RelatedObjects = list(objs) + else: + rel = file.create_entity( + "IfcRelDefinesByProperties", + **{ + "GlobalId": ifcopenshell.guid.new(), + "OwnerHistory": ifcopenshell.api.owner.create_owner_history(file), + "RelatedObjects": list(products_occurrences), + "RelatingPropertyDefinition": pset, + }, + ) + + for product in products_types: + psets = list(product.HasPropertySets or []) + product.HasPropertySets = psets + [pset] + + return rel diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..35ef9ee6a86008c1619d7d128bad021fa157af9e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_pset.py @@ -0,0 +1,489 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import datetime +import ifcopenshell +import ifcopenshell.util.element +import ifcopenshell.util.pset +from typing import Optional, Any, Union + + +def edit_pset( + file: ifcopenshell.file, + pset: ifcopenshell.entity_instance, + name: Optional[str] = None, + properties: Optional[dict[str, Any]] = None, + pset_template: Optional[ifcopenshell.entity_instance] = None, + should_purge: bool = True, +) -> None: + """Edits a property set and its properties + + At its simplest usage, this may be used to edit the name of a property + set. It may also be used to add, edit, or remove properties, either + arbitrarily or using a property set template. + + A list of properties are provided as a dictionary, where the keys are + property names, and values are property values. Keys that don't already + exist are interpreted as properties to be added. Keys that already exist + are interpreted as properties to be edited. A "None" value may specify a + property to be deleted. + + Properties must have a data type. There are lots of data types in IFCs, + not just simple unitless data types like integers, booleans, text, but + also distinguishing between types of text, like labels versus + descriptive text. There are also lots of unit-based data types like + areas, volumes, lengths, power, density, flow rates, pressure, etc. + + To ensure the appropriate data type is used for properties, a property + set template may be used. These can be seen as "property + specifications". A default selection is provided by buildingSMART, so + that all buildingSMART defined standard properties have exactly the same + data types and exactly the right property names without fear of invalid + data or typos. The built-in buildingSMART templates are always loaded. + However, you may also specify your own templates. If you try to add a + non-standard property that does not exist in either your own template or + in the built-in buildingSMART template, then you have the responsibility + to ensure that data types are always consistent and correct. + + :param pset: The IfcPropertySet to edit. + :param name: A new name for the property set. If no name is specified, + the property set name is not changed. + :param properties: A dictionary of properties. The keys must be a string + of the name of the property. The data type of the value will be + determined by the property set template. If no property set + template is found, the data types of the Python values will + influence the IFC data type of the property. String values will + become IfcLabel, float values will become IfcReal, booleans will + become IfcBoolean, and integers will become IfcInteger. If more + control is desired, you may explicitly specify IFC data objects + directly. Note that provided `properties` might be mutated in the process. + :param pset_template: If a property set template is provided, this will + be used to determine data types. If no user-defined template is + provided, the built-in buildingSMART templates will be loaded. + :param should_purge: If set as False, properties set to None will be + left as None but not removed. If set to true, properties set to None + will actually be removed. The default of true is the same behaviour as + :func:`ifcopenshell.api.pset.edit_qto`. + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a new wall type. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType") + + # This is a standard buildingSMART property set. + pset = ifcopenshell.api.pset.add_pset(model, product=wall_type, name="Pset_WallCommon") + + # In this scenario, we don't specify any pset_template because it is + # part of the built-in buildingSMART templates, and so the + # FireRating will automatically be an IfcLabel, and the thermal + # transmittance value will automatically be an + # IfcThermalTransmittanceMeasure. Neither of these properties exist + # yet, so they will be created. + ifcopenshell.api.pset.edit_pset(model, + pset=pset, properties={"FireRating": "2HR", "ThermalTransmittance": 42.3}) + + # We can edit existing properties. In this case, "FireRating" is + # edited from "2HR" to "1HR". Combustible is new, and will be added. + # The existing "ThermalTransmittance" property will be left + # unchanged. + ifcopenshell.api.pset.edit_pset(model, + pset=pset, properties={"FireRating": "1HR", "Combustible": False}) + + # Setting to None will change the value but not delete the property. + ifcopenshell.api.pset.edit_pset(model, pset=pset, properties={"Combustible": None}) + + # If you actually want to delete the property, enable purging. + ifcopenshell.api.pset.edit_pset(model, pset=pset, + properties={"Combustible": None}, should_purge=True) + + # What if we wanted to manage our own properties? Let's create our + # own "Company Standard" property set templates. Notice how we + # prefix our property set with "Foo_", if our company name was "Foo" + # this would make sense. + template = ifcopenshell.api.pset_template.add_pset_template(model, name="Foo_bar") + + # Let's imagine we want all model authors to specify two properties, + # one being a length measurement and another being a boolean. + prop1 = ifcopenshell.api.pset_template.add_prop_template(model, + pset_template=template, name="DemoA", primary_measure_type="IfcLengthMeasure") + prop2 = ifcopenshell.api.pset_template.add_prop_template(model, + pset_template=template, name="DemoB", primary_measure_type="IfcBoolean") + + # Now we can use our property set template to add our properties, + # and the data types will always match our template. + pset = ifcopenshell.api.pset.add_pset(model, product=wall_type, name="Foo_Bar") + ifcopenshell.api.pset.edit_pset(model, + pset=pset, properties={"DemoA": 42.3, "DemoB": True}, pset_template=template) + + # Here's a third scenario where we want to add arbitrary properties + # that are not standardised by anything, not even our own custom + # templates. + pset = ifcopenshell.api.pset.add_pset(model, product=wall_type, name="Custom_Pset") + ifcopenshell.api.pset.edit_pset(model, + pset=pset, properties={ + # Basic Python data types are mapped to a sensible default + "SomeLabel": "Foo", + "SomeNumber": 12.3, + # But we can always specify exactly what we're after too + "ExplicitLength": model.createIfcLengthMeasure(42.3) + }) + + # Editing existing properties will retain their current data types + # if possible. So this will still be a length measure. + ifcopenshell.api.pset.edit_pset(model, pset=pset, properties={"ExplicitLength": 12.3}) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "pset": pset, + "name": name, + "properties": properties or {}, + "pset_template": pset_template, + "should_purge": should_purge, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self) -> None: + self.update_pset_name() + self.load_pset_template() + existing_props = self.update_existing_properties() + new_props = self.add_new_properties() + self.assign_new_properties(existing_props + new_props) + + def update_pset_name(self) -> None: + if self.settings["name"]: + self.settings["pset"].Name = self.settings["name"] + + def load_pset_template(self) -> None: + if self.settings["pset_template"]: + self.pset_template = self.settings["pset_template"] + else: + self.psetqto = ifcopenshell.util.pset.get_template(self.file.schema_identifier) + self.pset_template = self.psetqto.get_by_name(self.settings["pset"].Name) + + def _should_update_prop(self, prop: ifcopenshell.entity_instance) -> bool: + """ + Checks if the given property should be changed + """ + return prop.Name in self.settings["properties"] + + def _try_purge(self, prop: ifcopenshell.entity_instance) -> bool: + """ + Tries to remove the property + if successful, returns True, otherwise False + NOTE: Assumes the prop exists + """ + if not self.settings["should_purge"]: + return False + + del self.settings["properties"][prop.Name] + self.file.remove(prop) + return True + + # TODO - Add support for changing property types? + # For example - IfcPropertyEnumeratedValue to + # IfcPropertySingleValue. Or maybe the user should + # just delete the property first? - vulevukusej + def update_existing_properties(self) -> list[ifcopenshell.entity_instance]: + existing_props = [] + for prop in self.get_properties(): + if not self._should_update_prop(prop): + existing_props.append(prop) + continue + + if self.file.get_total_inverses(prop) > 1: + continue # Treat as a new property to avoid affecting other psets. + + if prop.is_a("IfcPropertyEnumeratedValue"): + prop = self.update_existing_prop_enum(prop) + if prop: + existing_props.append(prop) + elif prop.is_a("IfcPropertySingleValue"): + prop = self.update_existing_prop_single_value(prop) + if prop: + existing_props.append(prop) + else: + raise NotImplementedError(f"Updating '{prop.is_a()}' properties is not supported yet") + return existing_props + + def update_existing_prop_enum( + self, prop: ifcopenshell.entity_instance + ) -> Union[ifcopenshell.entity_instance, None]: + """ + NOTE: Assumes the prop exists + """ + value = self.settings["properties"][prop.Name] + unit, value = self.unpack_unit_value(value) + + if isinstance(value, (tuple, list)): + sel_vals = [] + if not value: + if self._try_purge(prop): + return + # Only need the first enum type since all enums are of the same type. + if reference := prop.EnumerationReference: + primary_measure_type = reference.EnumerationValues[0].is_a() + elif enum_values := prop.EnumerationValues: + primary_measure_type = enum_values[0].is_a() + else: + primary_measure_type = self.get_primary_measure_type(prop.Name, new_value=value[0]) + assert primary_measure_type, f"Couldn't find primary measure type for the prop value: '{value[0]}'." + for val in value: + ifc_val = self.file.create_entity(primary_measure_type, val) + sel_vals.append(ifc_val) + prop.EnumerationValues = tuple(sel_vals) or None + + elif isinstance(value, ifcopenshell.entity_instance) and value.is_a("IfcPropertyEnumeratedValue"): + # Copy enum value. + if (value_enum_values := value.EnumerationValues) is None: + if self._try_purge(prop): + return + prop.EnumerationValues = value_enum_values + + # Copy values from / recreate value EnumerationReference in prop. + value_reference = value.EnumerationReference + prop_reference = prop.EnumerationReference + if value_reference is None: + if prop_reference: + ifcopenshell.util.element.remove_deep2(self.file, prop_reference) + prop.EnumerationReference = None + else: + if prop_reference is None: + prop_reference = ifcopenshell.util.element.copy_deep(self.file, value_reference) + prop.EnumerationReference = prop_reference + else: + prop_reference.Name = value_reference.Name + prop_reference.EnumerationValues = value_reference.EnumerationValues + prop_reference.Unit = value_reference.Unit + + else: + raise ValueError( + f'Value "{self.settings["properties"][prop.Name]}" is not a valid value for enum property {prop.Name}.' + ) + + if unit: + prop.Unit = unit + del self.settings["properties"][prop.Name] + return prop + + def update_existing_prop_single_value( + self, prop: ifcopenshell.entity_instance + ) -> Union[ifcopenshell.entity_instance, None]: + """ + NOTE: Assumes the prop exists + """ + value = self.settings["properties"][prop.Name] + unit, value = self.unpack_unit_value(value) + if value is None: + if self._try_purge(prop): + return + prop.NominalValue = None + elif isinstance(value, ifcopenshell.entity_instance): + prop.NominalValue = value + else: + primary_measure_type = self.get_primary_measure_type( + prop.Name, old_value=prop.NominalValue, new_value=value + ) + value = self.cast_value_to_primary_measure_type(value, primary_measure_type) + prop.NominalValue = self.file.create_entity(primary_measure_type, value) + if unit: + prop.Unit = unit + del self.settings["properties"][prop.Name] + return prop + + def add_new_properties(self) -> list[ifcopenshell.entity_instance]: + properties: list[ifcopenshell.entity_instance] = [] + for name, value in self.settings["properties"].items(): + if value is None and self.settings["should_purge"]: + continue + unit, value = self.unpack_unit_value(value) + + if isinstance(value, ifcopenshell.entity_instance): + if value.is_a("IfcProperty"): + properties.append(value) + + # If it's not an entity, then it's a primitive data type + elif not value.is_entity(): + kwargs = {"Name": name, "NominalValue": value} + if unit: + kwargs["Unit"] = unit + properties.append(self.file.create_entity("IfcPropertySingleValue", **kwargs)) + + else: + raise ValueError(f"{value.is_a()} cannot be assigned to the property set '{name}'") + + elif isinstance(value, (tuple, list)): + if not value: + continue + for pset_template in self.pset_template.HasPropertyTemplates: + if pset_template.Name != name: + continue + + if pset_template.TemplateType == "P_LISTVALUE": + ifc_class = getattr(pset_template, "PrimaryMeasureType", None) + if ifc_class is None: + raise ValueError(f"pset template '{pset_template.Name}' is missing PrimaryMeasureType") + + properties.append( + self.file.create_entity( + "IfcPropertyListValue", + Name=name, + ListValues=[self.file.create_entity(ifc_class, v) for v in value], + Unit=unit, + ) + ) + break + + elif pset_template.TemplateType == "P_ENUMERATEDVALUE": + prop_enum = self.file.create_entity( + "IFCPROPERTYENUMERATION", + Name=name, + EnumerationValues=pset_template.Enumerators.EnumerationValues, + **({"Unit": unit} if unit else {}), + ) + prop_enum_value = self.file.create_entity( + "IFCPROPERTYENUMERATEDVALUE", + Name=name, + EnumerationValues=tuple( + self.file.create_entity(pset_template.PrimaryMeasureType, v) for v in value + ), + EnumerationReference=prop_enum, + ) + properties.append(prop_enum_value) + break + + raise NotImplementedError(f"Template type '{pset_template.TemplateType}' is not supported yet") + + else: + raise NotImplementedError(f"No template found for property '{name}'") + + else: + primary_measure_type = self.get_primary_measure_type(name, new_value=value) + if value is None: + nominal_value = value + else: + value = self.cast_value_to_primary_measure_type(value, primary_measure_type) + nominal_value = self.file.create_entity(primary_measure_type, value) + args = {"Name": name, "NominalValue": nominal_value} + if unit: + args["Unit"] = unit + + properties.append(self.file.create_entity("IfcPropertySingleValue", **args)) + return properties + + def assign_new_properties(self, props: list[ifcopenshell.entity_instance]) -> None: + if hasattr(self.settings["pset"], "HasProperties"): + self.settings["pset"].HasProperties = props + + # Material / Profile properties + elif hasattr(self.settings["pset"], "Properties"): + self.settings["pset"].Properties = props + + # IFC2X3 IfcMaterialProperties + elif self.settings["pset"].is_a("IfcMaterialProperties"): + self.settings["pset"].ExtendedProperties = props + + def get_properties(self) -> list[ifcopenshell.entity_instance]: + """ + Returns list of existing properties + """ + if (props := getattr(self.settings["pset"], "HasProperties", ...)) is not ...: + return props or [] + + # Material / Profile properties + elif (props := getattr(self.settings["pset"], "Properties", ...)) is not ...: + return props or [] + + # IFC2X3 IfcMaterialProperties + elif (props := getattr(self.settings["pset"], "ExtendedProperties", ...)) is not ...: + return props or [] + + raise TypeError(f"'{self.settings['pset']}' is not a valid pset") + + def get_primary_measure_type( + self, + name: str, + old_value: Optional[ifcopenshell.entity_instance] = None, + new_value: Optional[Union[ifcopenshell.entity_instance, str, float, bool, int]] = None, + ) -> Union[str, None]: + if old_value: + return old_value.is_a() + if self.pset_template: + for prop_template in self.pset_template.HasPropertyTemplates: + if prop_template.Name != name: + continue + return prop_template.PrimaryMeasureType or "IfcLabel" + if isinstance(new_value, ifcopenshell.entity_instance): + return new_value.is_a() + elif new_value is not None: + if isinstance(new_value, str): + return "IfcLabel" + elif isinstance(new_value, float): + return "IfcReal" + elif isinstance(new_value, bool): + return "IfcBoolean" + elif isinstance(new_value, int): + return "IfcInteger" + # @nb datetime is also a date, so needs to be checked first + elif isinstance(new_value, datetime.datetime): + return "IfcDateTime" + elif isinstance(new_value, datetime.date): + return "IfcDate" + + def cast_value_to_primary_measure_type(self, value, primary_measure_type): + type_str = self.file.create_entity(primary_measure_type).attribute_type(0) + type_fn = { + "AGGREGATE OF DOUBLE": list, + "AGGREGATE OF INT": list, + "AGGREGATE OF ENTITY INSTANCE": list, + "BINARY": bytes, + "LOGICAL": str, + "BOOL": bool, + "INT": int, + "DOUBLE": float, + "STRING": str, + }[type_str] + if type_str == "AGGREGATE OF DOUBLE": + return [float(i) for i in value] + elif type_str == "AGGREGATE OF INT": + return [int(i) for i in value] + elif isinstance(value, (datetime.date, datetime.datetime)): + return value.isoformat() + return type_fn(value) + + @staticmethod + def unpack_unit_value(value_candidate): + """ + Returns tuple of the format: (Unit, NominalValue) + NOTE: Unit fallbacks to None + """ + if value_candidate is None: + return (None, None) + + if isinstance(value_candidate, dict): # Custom IfcUnits can be passed in a dict along with the pset value + return (value_candidate["Unit"], value_candidate["NominalValue"]) + + return (None, value_candidate) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_qto.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_qto.py new file mode 100644 index 0000000000000000000000000000000000000000..54405efdd1b4ddf9759e68f06d24691b033596f4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/edit_qto.py @@ -0,0 +1,242 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.pset +import ifcopenshell.util.pset +from typing import Optional, Any, Union +from typing_extensions import assert_never + +FLOAT_TYPE_KEYWORDS = ( + ("Area", ("area",)), + ("Volume", ("volume",)), + ("Weight", ("weight", "mass")), + ("Length", ("length", "width", "height", "depth", "distance")), + ("Time", ("time", "duration")), +) + +PROP_VALUE_TYPE = Union[ifcopenshell.entity_instance, float, int, dict[str, "PROP_VALUE_TYPE"]] + + +def edit_qto( + file: ifcopenshell.file, + qto: ifcopenshell.entity_instance, + name: Optional[str] = None, + properties: Optional[dict[str, PROP_VALUE_TYPE]] = None, + pset_template: Optional[ifcopenshell.entity_instance] = None, +) -> None: + """Edits a quantity set and its quantities + + At its simplest usage, this may be used to edit the name of a quantity + set. It may also be used to add, edit, or remove quantities. + + See ifcopenshell.api.pset.edit_pset for documentation on how this is + intended to be used. + + One major difference is that quantities set to None are always purged. + It is not allowed to have None quantities in IFC. + + :param qto: The IfcElementQuantity or IfcPhysicalComplexQuantity to edit. + :param name: A new name for the quantity set. If no name is specified, + the quantity set name is not changed. + :param properties: A dictionary of properties. The keys must be a string + of the name of the quantity. The data type of the value will be + determined by the quantity set template. If no quantity set + template is found, the data types of the Python values and + properties names will influence the IFC data type of the quantity. + + - For `float` values - see `FLOAT_TYPE_KEYWORDS` for the keywords in property name + used to detect the quantity type. If no keyword matches, + the default quantity type will be IfcQuantityLength. + + - `int` values will map to IfcQuantityCount. + + - dictionary values will be used to create IfcPhysicalComplexQuantity with + properties from the dictionary. + + If more control is desired, you may explicitly specify IFC data objects directly. + :param pset_template: If a quantity set template is provided, this will + be used to determine data types. If no user-defined template is + provided, the built-in buildingSMART templates will be loaded. + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a new wall type. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # This is a standard buildingSMART property set. + qto = ifcopenshell.api.pset.add_qto(model, product=wall, name="Qto_WallBaseQuantities") + + # In this scenario, we don't specify any pset_template because it is + # part of the built-in buildingSMART templates, and so the Length + # will automatically be an IfcLengthMeasure, and the NetVolume will + # automatically be an IfcVolumeMeasure. Neither of these properties + # exist yet, so they will be created. + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"Length": 12, "NetVolume": 7.2}) + + # Setting to None will delete the quantity. + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"Length": None}) + + # What if we wanted to manage our own properties? Let's create our + # own "Company Standard" property set templates. Notice how we + # prefix our property set with "Foo_", if our company name was "Foo" + # this would make sense. In this example, we say that our template + # only applies to walls and is for quantities. + template = ifcopenshell.api.pset_template.add_pset_template(model, + name="Foo_Wall", template_type="QTO_OCCURRENCEDRIVEN", applicable_entity="IfcWall") + + # Let's imagine we want all model authors to specify a length + # measurement for the portion of a wall that is overhanging. + prop = ifcopenshell.api.pset_template.add_prop_template(model, pset_template=template, + name="OverhangLength", template_type="Q_LENGTH", primary_measure_type="IfcLengthMeasure") + + # Now we can use our property set template to add our properties, + # and the data types will always match our template. + qto = ifcopenshell.api.pset.add_qto(model, product=wall, name="Foo_Wall") + ifcopenshell.api.pset.edit_qto(model, + qto=qto, properties={"OverhangLength": 42.3}, pset_template=template) + + # Here's a third scenario where we want to add arbitrary quantities + # that are not standardised by anything, not even our own custom + # templates. + qto = ifcopenshell.api.pset.add_qto(model, product=wall, name="Custom_Qto") + ifcopenshell.api.pset.edit_qto(model, + qto=qto, properties={ + "SomeLength": model.createIfcLengthMeasure(42.3), + "SomeArea": model.createIfcAreaMeasure(21.0) + }) + + # Editing existing quantities will retain their current data types + # if possible. So this will still be a length measure. + ifcopenshell.api.pset.edit_qto(model, qto=qto, properties={"SomeLength": 12.3}) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = {"qto": qto, "name": name, "properties": properties or {}, "pset_template": pset_template} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + self.qto_idx = 5 + if self.settings["qto"].is_a("IfcPhysicalComplexQuantity"): + self.qto_idx = 2 + + self.update_qto_name() + self.load_qto_template() + self.update_existing_properties() + new_properties = self.add_new_properties() + self.extend_qto_with_new_properties(new_properties) + + def update_qto_name(self) -> None: + if self.settings["name"]: + self.settings["qto"].Name = self.settings["name"] + + def load_qto_template(self) -> None: + if self.settings["pset_template"]: + self.pset_template = self.settings["pset_template"] + else: + self.psetqto = ifcopenshell.util.pset.get_template(self.file.schema_identifier) + self.qto_template = self.psetqto.get_by_name(self.settings["qto"].Name) + + def update_existing_properties(self) -> None: + for prop in self.settings["qto"][self.qto_idx] or []: + self.update_existing_property(prop) + + def update_existing_property(self, prop: ifcopenshell.entity_instance) -> None: + if prop.Name not in self.settings["properties"]: + return + value = self.settings["properties"][prop.Name] + name = prop.Name + if value is None: + self.file.remove(prop) + elif prop.is_a("IfcPhysicalComplexQuantity") and isinstance(value, dict): + prop.Discrimination = value.get("Discrimination", prop.Discrimination) + ifcopenshell.api.pset.edit_qto(self.file, qto=prop, properties=value["HasQuantities"]) + elif prop.is_a("IfcPhysicalSimpleQuantity"): + value = value.wrappedValue if isinstance(value, ifcopenshell.entity_instance) else value + # 3 IfcPhysicalSimpleQuantity.XXXValue + if self.file.schema == "IFC4X3" and prop.is_a("IfcQuantityCount"): + prop[3] = int(value) + else: + prop[3] = float(value) + del self.settings["properties"][name] + + def add_new_properties(self) -> list[ifcopenshell.entity_instance]: + properties = [] + for name, value in self.settings["properties"].items(): + if value is None: + continue + if isinstance(value, dict): + complex_qto = self.file.create_entity( + "IfcPhysicalComplexQuantity", Name=name, Discrimination=value["Discrimination"] + ) + properties.append(complex_qto) + ifcopenshell.api.pset.edit_qto(self.file, qto=complex_qto, properties=value["HasQuantities"]) + else: + property_type = self.get_canonical_property_type(name, value) + value = value.wrappedValue if isinstance(value, ifcopenshell.entity_instance) else value + properties.append( + self.file.create_entity( + "IfcQuantity{}".format(property_type), + **{"Name": name, "{}Value".format(property_type): value}, + ) + ) + return properties + + def extend_qto_with_new_properties(self, new_properties: list[ifcopenshell.entity_instance]) -> None: + props = list(self.settings["qto"][self.qto_idx]) if self.settings["qto"][self.qto_idx] else [] + props.extend(new_properties) + self.settings["qto"][self.qto_idx] = props + + def get_canonical_property_type(self, name: str, value: Union[ifcopenshell.entity_instance, float, int]) -> str: + if isinstance(value, ifcopenshell.entity_instance): + result = value.is_a().replace("Ifc", "").replace("Measure", "") + # Sigh, IFC inconsistencies + if result == "Numeric": + result = "Number" + elif result == "Mass": + result = "Weight" + return result + if self.qto_template: + for prop_template in self.qto_template.HasPropertyTemplates: + if prop_template.Name != name: + continue + return prop_template.TemplateType[2:].lower().capitalize() + return infer_property_type(name, value) + + +def infer_property_type(name: str, value: Union[float, int]) -> str: + name_lower = name.lower() + # Only undetected type is IfcQuantityNumber (IFC4X3), + # not sure when it's appropriate. + if isinstance(value, float): + for category, keywords in FLOAT_TYPE_KEYWORDS: + if any(keyword in name_lower for keyword in keywords): + return category + return "Length" + elif isinstance(value, int): + return "Count" + else: + assert_never(value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/remove_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/remove_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..7c27dbd9bfb9241f2a969a6cccb14bcd1b1361ab --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/remove_pset.py @@ -0,0 +1,81 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_pset( + file: ifcopenshell.file, product: ifcopenshell.entity_instance, pset: ifcopenshell.entity_instance +) -> None: + """Removes a property set from a product + + All properties that are part of this property set are also removed. + + :param product: The IfcObject to remove the property set from. + :param pset: The IfcPropertySet or IfcElementQuantity to remove. + :return: None + + Example: + + .. code:: python + + # Let's imagine we have a new wall type with a property set. + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType") + pset = ifcopenshell.api.pset.add_pset(model, product=wall_type, name="Pset_WallCommon") + + # Remove it! + ifcopenshell.api.pset.remove_pset(model, product=wall_type, pset=pset) + """ + to_purge = [] + should_remove_pset = True + for inverse in file.get_inverse(pset): + if inverse.is_a("IfcRelDefinesByProperties"): + if not inverse.RelatedObjects or len(inverse.RelatedObjects) == 1: + to_purge.append(inverse) + else: + related_objects = list(inverse.RelatedObjects) + related_objects.remove(product) + inverse.RelatedObjects = related_objects + should_remove_pset = False + if should_remove_pset: + properties = [] # Predefined psets have no properties + if pset.is_a("IfcPropertySet"): + properties = pset.HasProperties or [] + elif pset.is_a("IfcQuantitySet"): + properties = pset.Quantities or [] + elif pset.is_a() in ("IfcMaterialProperties", "IfcProfileProperties"): + properties = pset.Properties or [] + for prop in properties: + if file.get_total_inverses(prop) != 1: + continue + if prop.is_a("IfcPropertyEnumeratedValue"): + enumeration = prop.EnumerationReference + if enumeration and file.get_total_inverses(enumeration) == 1: + file.remove(enumeration) + file.remove(prop) + # IfcMaterialProperties and IfcProfileProperties don't have OwnerHistory + history = getattr(pset, "OwnerHistory", None) + file.remove(pset) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + for element in to_purge: + history = getattr(element, "OwnerHistory", None) + file.remove(element) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unassign_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unassign_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..24256f77feb3bc9b5cc0d8408a57e294a2fa747d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unassign_pset.py @@ -0,0 +1,80 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.guid +import ifcopenshell.util.element + + +def unassign_pset( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + pset: ifcopenshell.entity_instance, +) -> None: + """Unassign property set from the provided elements. + + :param products: Elements (or element types) to assign the pset from. + :param pset: Property set. + + Example: + + .. code:: python + + element1 = ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcWall") + element2 = ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcWall") + ifcopenshell.api.pset.assign_pset(self.file, [element1, element2], pset) + + # Pset is now shared by 2 elements. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element1, element2} + + ifcopenshell.api.pset.unassign_pset(self.file, [element2], pset) + # Pset was unassigned from element2. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element1} + + """ + is_ifc2x3 = file.schema == "IFC2X3" + + products_occurrences: set[ifcopenshell.entity_instance] = set() + products_types: set[ifcopenshell.entity_instance] = set() + for product in products: + if product.is_a("IfcTypeProduct"): + products_types.add(product) + else: + products_occurrences.add(product) + + # Check occurrences using pset. + if products_occurrences: + rels = pset.PropertyDefinitionOf if is_ifc2x3 else pset.DefinesOccurrence + for rel in rels: + objs = set(rel.RelatedObjects) + if not any(p in objs for p in products_occurrences): + continue + objs.difference_update(products_occurrences) + if objs: + rel.RelatedObjects = list(objs) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) + + for product in products_types: + psets = list(product.HasPropertySets) + psets.remove(pset) + product.HasPropertySets = psets or None diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unshare_pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unshare_pset.py new file mode 100644 index 0000000000000000000000000000000000000000..051905b2b7f53a5f7f50bee819e891e2249b47f8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/pset/unshare_pset.py @@ -0,0 +1,95 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.api.pset +import ifcopenshell.guid +import ifcopenshell.util.element + + +def unshare_pset( + file: ifcopenshell.file, + products: list[ifcopenshell.entity_instance], + pset: ifcopenshell.entity_instance, +) -> list[ifcopenshell.entity_instance]: + """Copy a shared pset as linked only to the provided elements. + + Note that method will create a copy of the pset for each element provided. + + :param products: Elements (or element types) to link the pset to. + :param pset: Shared property set. + :return: List of copied property sets. + + Example: + + .. code:: python + + element1 = ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcWall") + element2 = ifcopenshell.api.root.create_entity(self.file, ifc_class="IfcWall") + ifcopenshell.api.pset.assign_pset(self.file, [element1, element2], pset) + + # Pset is now shared by 2 elements. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element1, element2} + + new_psets = ifcopenshell.api.pset.unshare_pset(self.file, [element2], pset) + + # element2 was unassigned from the original pset. + assert ifcopenshell.util.element.get_elements_by_pset(pset) == {element1} + new_pset = new_psets[0] + + # New pset was created and was assigned to element2. + assert new_pset != pset + assert ifcopenshell.util.element.get_elements_by_pset(new_pset) == {element2} + """ + + if not products: + raise Exception("No products provided.") + + # If pset has no other elements besides the provided products, + # then we skip the first product, so it won't get additional pset copy + # leaving the original pset orphaned. + pset_elements = ifcopenshell.util.element.get_elements_by_pset(pset) + products_original = products + + if set(products) == pset_elements: + products = products[1:] + + if not products: + raise Exception(f"Provided product is the only element to which pset is assigned: {products_original[0]}.") + + products_occurrences: set[ifcopenshell.entity_instance] = set() + products_types: set[ifcopenshell.entity_instance] = set() + for product in products: + if product.is_a("IfcTypeProduct"): + products_types.add(product) + else: + products_occurrences.add(product) + + ifcopenshell.api.pset.unassign_pset(file, products, pset) + + pset_copies: list[ifcopenshell.entity_instance] = [] + for product in products: + # No need to consider about profile/material properties since + # they are assigned to 1 element directly and therefore cannot be shared. + # Don't copy_deep to keep it light - edit_pset supports unsharing shared props. + pset_copy = ifcopenshell.util.element.copy(file, pset) + pset_copies.append(pset_copy) + ifcopenshell.api.pset.assign_pset(file, [product], pset_copy) + + return pset_copies diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c951cfabb46b3dfc0069e4803d8df8171602f0d9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/__init__.py @@ -0,0 +1,57 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Manage visual styles of geometry (colours, transparency, rendering, etc) + +Geometry may have visual styles associated with it, including surface styles, +2D curve styles, text styles, and more. Surface styles are most commonly used +for simple colouring. +""" + +from .. import wrap_usecases +from .add_style import add_style +from .add_surface_style import add_surface_style +from .add_surface_textures import add_surface_textures +from .assign_item_style import assign_item_style +from .assign_material_style import assign_material_style +from .assign_representation_styles import assign_representation_styles +from .edit_presentation_style import edit_presentation_style +from .edit_surface_style import edit_surface_style +from .remove_style import remove_style +from .remove_styled_representation import remove_styled_representation +from .remove_surface_style import remove_surface_style +from .unassign_material_style import unassign_material_style +from .unassign_representation_styles import unassign_representation_styles + +wrap_usecases(__path__, __name__) + +__all__ = [ + "add_style", + "add_surface_style", + "add_surface_textures", + "assign_item_style", + "assign_material_style", + "assign_representation_styles", + "edit_presentation_style", + "edit_surface_style", + "remove_style", + "remove_styled_representation", + "remove_surface_style", + "unassign_material_style", + "unassign_representation_styles", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_style.py new file mode 100644 index 0000000000000000000000000000000000000000..54e5ffd2a886e80fb01019bc8c06ac5681753012 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_style.py @@ -0,0 +1,64 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Optional + + +def add_style( + file: ifcopenshell.file, name: Optional[str] = None, ifc_class="IfcSurfaceStyle" +) -> ifcopenshell.entity_instance: + """Add a new presentation style + + A presentation style is a container of visual settings (called + presentation items) that affect the appearance of objects. There are + four types of style: + + - Surface styles, which give 3D objects (which have surfaces / faces) + their colours and textures. This is the most common type of style. + - Curve styles, which give 2D and 3D curves, lines, polylines, their + stroke thickness and colour. + - Fill area styles, which gives 2D polygons and flat 3D planes their + colours, hatch patterns, tiled patterns, and pattern scales. + - Text styles, which gives text their font family, weight, variant, + size, indentation, alignment, decoration, spacing, and transformation. + + Once you have created a presentation style object, you can further + define the properties of your style using other API functions by adding + presentation items, such as ifcopenshell.api.style.add_surface_style. + + :param name: The name of the style. Used to easily identify it using a + style library. + :param ifc_class: Choose from IfcSurfaceStyle, IfcCurveStyle, + IfcFillAreaStyle, or IfcTextStyle. + :return: The newly created style element, based on the provided + ifc_class. + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + """ + + kwargs = {"Name": name} + if ifc_class == "IfcSurfaceStyle": + # Name is filled out because Revit treats this incorrectly as the material name + kwargs["Side"] = "BOTH" + + return file.create_entity(ifc_class, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_style.py new file mode 100644 index 0000000000000000000000000000000000000000..55af1b35b2da563fdccbb9cc643e20f798b7a467 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_style.py @@ -0,0 +1,143 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.style +from typing import Any, Optional, Literal + + +SURFACE_STYLE_TYPES = Literal[ + "IfcSurfaceStyleShading", + "IfcSurfaceStyleRendering", + "IfcSurfaceStyleWithTextures", + "IfcSurfaceStyleLighting", + "IfcSurfaceStyleRefraction", + "IfcExternallyDefinedSurfaceStyle", +] + + +def add_surface_style( + file: ifcopenshell.file, + style: ifcopenshell.entity_instance, + ifc_class: SURFACE_STYLE_TYPES = "IfcSurfaceStyleShading", + attributes: Optional[dict[str, Any]] = None, +) -> ifcopenshell.entity_instance: + """Adds a new presentation item to a surface style + + A surface style can have multiple different types of presentation items + assigned to it: + + - Shading, this is the simplest item, which defines a single basic + colour and transparency that can be used to display the object on a + screen. It is an indicative colour of what the object would be in real + life. It is commonly incorrectly abused to colour code systems for MEP + equipment or object types for structural steel. If you just want to + give something a colour, this is what you need. + - Rendering, this is an advanced extension of shading, which includes + the definition of a shader for a rendering engine. You may select the + reflectance / lighting model such as PHYSICAL, for PBR style + rendering, or FLAT, for flat shading, or PHONG for older biased + rendering workflows. Based on the chosen lighting model, you may then + specify the appropriate colour maps, such as diffuse colours, + specularity, emissive component, etc. These lighting models are fully + compatible with glTF and X3D. This should be used if your model is + prepared to be rendered by a rendering engine which is compatible with + glTF / X3D shader descriptions. If you are doing archviz or 3D + rendering, this is what you need. + - Textures, this is a special type of Rendering presentation item that + uses image textures instead of single colours. Textures may be either + mapped using a bounding box stretch mapping, or with UV coordinates + for mesh-like geometry. + - Lighting, this is used to define photometrically accurate colour + parameters used in lighting simulation. If you are a simulationist, + this is what you need. + - Reflectance, this is a special type of Lighting presentation item + which includes some lesser used photometric properties, typically + required for advanced materials like glazing. + - External, this is for any other surface style defined using an + external URI. This is relevant if you are using a third-party non-glTF + compatible shader definition such as for Cycles, Renderman, V-Ray, + etc, or a complex lighting simulation definition, such as for + Radiance. + + Shading is sufficient for the majority of basic models. + + The attributes you specify will depend on the type of presentation item + you are adding. An example is shown below, but for full details please + refer to the IFC documentation. + + :param style: The IfcSurfaceStyle you want to add to presentation item + to. See ifcopenshell.api.style.add_style. + :param ifc_class: Choose from IfcSurfaceStyleShading, + IfcSurfaceStyleRendering, IfcSurfaceStyleWithTextures, + IfcSurfaceStyleLighting, IfcSurfaceStyleReflectance, or + IfcExternallyDefinedSurfaceStyle. + :param attributes: a dictionary of attribute names and values. + :return: The newly created presentation item based on the provided + ifc_class. + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a simple shading colour and transparency. + ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleShading", attributes={ + "SurfaceColour": { "Name": None, "Red": 1.0, "Green": 0.8, "Blue": 0.8 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + }) + + # Alternatively, create a rendering style. + ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleRendering", attributes={ + # A surface colour and transparency is still supplied for + # viewport display only. This will supersede the shading + # presentation item. + "SurfaceColour": { "Name": None, "Red": 1.0, "Green": 0.8, "Blue": 0.8 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + + # NOTDEFINED is assumed to be a PHYSICAL (PBR) lighting + # model. In IFC4X3, you may choose PHYSICAL directly. + "ReflectanceMethod": "NOTDEFINED", + + # For PBR shading, you may specify these parameters: + "DiffuseColour": { "Name": None, "Red": 0.9, "Green": 0.8, "Blue": 0.8 }, + "SpecularColour": 0.1, # Metallic factor + "SpecularHighlight": {"SpecularRoughness": 0.5}, # Roughness factor + }) + """ + attributes = attributes or {} + style_item = file.create_entity(ifc_class) + ifcopenshell.api.style.edit_surface_style(file, style=style_item, attributes=attributes) + styles: list[ifcopenshell.entity_instance] + styles = list(style.Styles or []) + + select_class = ifc_class + if select_class == "IfcSurfaceStyleRendering": + select_class = "IfcSurfaceStyleShading" + duplicate_items = [s for s in styles if s.is_a(select_class)] + for duplicate_item in duplicate_items: + ifcopenshell.api.style.remove_surface_style(file, style=duplicate_item) + + styles = list(style.Styles or []) + styles.append(style_item) + style.Styles = styles + return style_item diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_textures.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_textures.py new file mode 100644 index 0000000000000000000000000000000000000000..89505d1a98356a9f7993b29388876741f5ed3c70 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/add_surface_textures.py @@ -0,0 +1,203 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +from __future__ import annotations +import ifcopenshell +import ifcopenshell.api +from typing import TYPE_CHECKING, Optional, Any + +if TYPE_CHECKING: + import bpy + + +def add_surface_textures( + file: ifcopenshell.file, + material: Optional[bpy.types.Material] = None, + textures: Optional[list[dict]] = None, + uv_maps: Optional[list[ifcopenshell.entity_instance]] = None, +) -> list[ifcopenshell.entity_instance]: + """Add surface texture based on a Blender material definition or texture data. + + Either `material` or `textures` should be provided. + + :param material: The Blender material definition with a node tree that + is compatible with glTF. See one of the valid combinations here: + https://docs.blender.org/manual/en/dev/addons/import_export/scene_gltf2.html + :param uv_maps: A list of IfcIndexedTextureMap for any + IfcTessellatedFaceSets that the representation has, obtained from + the HasTextures attribute. + :param textures: A list of dictionaries containing: + + 1. Attributes to create IfcImageTexture. + 2. One additional parameter `uv_mode` to map IfcImageTexture to correct + IfcTextureCoordinate type. + + Possible `uv_mode` values: + + * `UV` - use IfcTextureCoordinate from `uv_maps` parameter; + * `Generated` - IfcTextureCoordinateGenerator with mode COORD (autogenerated UV + based on geometry); + * `Camera` - IfcTextureCoordinateGenerator with mode COORD_EYE (autogenerated UV + based on camera position) + :return: A list of IfcImageTexture + """ + usecase = Usecase() + # TODO: This usecase currently depends on Blender's data model + usecase.file = file + usecase.settings = {"material": material, "uv_maps": uv_maps or [], "textures": textures or []} + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + if self.file.schema == "IFC2X3": + # TODO: research how compatible IFC2X3 and IFC4 textures are + return [] + + # We optimistically assume the user has specified one of these valid combinations + # https://docs.blender.org/manual/en/dev/addons/import_export/scene_gltf2.html + # glTF, X3D, and IFC are compatible. As long as they have something that + # loosely resembles the node tree, we treat it as valid. + self.textures = [] + + for texture in self.settings["textures"]: + uv_mode = texture.get("uv_mode", None) + texture_data = texture.copy() + texture_data.pop("uv_mode", None) + texture = self.file.create_entity("IfcImageTexture", **texture_data) + if uv_mode == "Generated": + self.file.create_entity("IfcTextureCoordinateGenerator", Maps=[texture], Mode="COORD") + elif uv_mode == "Camera": + self.file.create_entity("IfcTextureCoordinateGenerator", Maps=[texture], Mode="COORD-EYE") + elif uv_mode == "UV": + self.apply_uv_map_to_texture(texture) + self.textures.append(texture) + + if self.settings["material"] is None: + return self.textures + + output = {n.type: n for n in self.settings["material"].node_tree.nodes}.get("OUTPUT_MATERIAL", None) + + if not output: + return self.textures + + bsdf = output.inputs["Surface"].links[0].from_node + + if bsdf.type == "ADD_SHADER": + for socket in bsdf.inputs: + if socket.links and socket.links[0].from_node.type == "BSDF_PRINCIPLED": + bsdf = socket.links[0].from_node + break + + if bsdf.type == "MIX_SHADER": + self.detect_unlit_emissive_map(bsdf) + elif bsdf.type == "BSDF_PRINCIPLED": + self.detect_normal_map(bsdf) + self.detect_emissive_map(bsdf) + self.detect_metallicroughness_map(bsdf) + self.detect_occlusion_map() + self.detect_diffuse_map(bsdf) + # We do not support Phong shading. What year is this, 1995? + + return self.textures + + def detect_unlit_emissive_map(self, bsdf): + for socket in bsdf.inputs: + if socket.links and socket.links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(socket.links[0].from_node, "EMISSIVE") + + def detect_normal_map(self, bsdf): + if bsdf.inputs["Normal"].links and bsdf.inputs["Normal"].links[0].from_node.type == "NORMAL_MAP": + normal = bsdf.inputs["Normal"].links[0].from_node + if normal.inputs["Color"].links and normal.inputs["Color"].links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(normal.inputs["Color"].links[0].from_node, "NORMAL") + + def detect_emissive_map(self, bsdf): + if bsdf.outputs[0].links[0].to_node.type != "ADD_SHADER": + return + bsdf = bsdf.outputs[0].links[0].to_node + for socket in bsdf.inputs: + if socket.links and socket.links[0].from_node.type == "EMISSION": + bsdf = socket.links[0].from_node + if bsdf.inputs["Color"].links and bsdf.inputs["Color"].links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(bsdf.inputs["Color"].links[0].from_node, "EMISSIVE") + + def detect_metallicroughness_map(self, bsdf): + if bsdf.inputs["Metallic"].links and bsdf.inputs["Metallic"].links[0].from_node.type == "SEPRGB": + seprgb = bsdf.inputs["Metallic"].links[0].from_node + if seprgb.inputs["Image"].links and seprgb.inputs["Image"].links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(seprgb.inputs["Image"].links[0].from_node, "METALLICROUGHNESS") + if bsdf.inputs["Roughness"].links and bsdf.inputs["Roughness"].links[0].from_node.type == "SEPRGB": + seprgb = bsdf.inputs["Roughness"].links[0].from_node + if seprgb.inputs["Image"].links and seprgb.inputs["Image"].links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(seprgb.inputs["Image"].links[0].from_node, "METALLICROUGHNESS") + + def detect_occlusion_map(self): + for node in self.settings["material"].node_tree.nodes: + if ( + node.type != "GROUP" + or not node.node_tree + or node.node_tree.name != "glTF Material Output" + or not node.inputs + or not node.inputs[0].links + ): + continue + from_node = node.inputs[0].links[0].from_node + if from_node.type == "SEPRGB": + sep = from_node + if sep.inputs["Image"].links and sep.inputs["Image"].links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(sep.inputs["Image"].links[0].from_node, "OCCLUSION") + elif from_node.type == "TEX_IMAGE": + return self.create_surface_texture(from_node, "OCCLUSION") + + def detect_diffuse_map(self, bsdf): + links = bsdf.inputs["Base Color"].links + if links and links[0].from_node.type == "TEX_IMAGE": + return self.create_surface_texture(links[0].from_node, "DIFFUSE") + + def create_surface_texture(self, node, mode): + import bonsai.tool as tool + + texture = self.file.create_entity( + "IfcImageTexture", + RepeatS=node.extension == "REPEAT", + RepeatT=node.extension == "REPEAT", + Mode=mode, + URLReference=tool.Blender.blender_path_to_posix(node.image.filepath), + ) + self.textures.append(texture) + self.process_texture_coordinates(node, texture) + + def process_texture_coordinates(self, node, texture): + if node.inputs["Vector"].links and node.inputs["Vector"].links[0].from_node.type == "TEX_COORD": + if node.inputs["Vector"].links[0].from_socket.name == "UV": + self.apply_uv_map_to_texture(texture) + elif node.inputs["Vector"].links[0].from_socket.name == "Generated": + self.file.create_entity("IfcTextureCoordinateGenerator", Maps=[texture], Mode="COORD") + elif node.inputs["Vector"].links[0].from_socket.name == "Camera": + self.file.create_entity("IfcTextureCoordinateGenerator", Maps=[texture], Mode="COORD-EYE") + elif node.inputs["Vector"].links and node.inputs["Vector"].links[0].from_node.type == "UVMAP": + self.apply_uv_map_to_texture(texture) + + def apply_uv_map_to_texture(self, texture): + for uv_map in self.settings["uv_maps"]: + maps = set(uv_map.Maps or []) + maps.add(texture) + uv_map.Maps = list(maps) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_item_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_item_style.py new file mode 100644 index 0000000000000000000000000000000000000000..0712bc2f83f088f07ad9dd288f9e57600687bbef --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_item_style.py @@ -0,0 +1,132 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Optional, Union + + +def assign_item_style( + file: ifcopenshell.file, + item: ifcopenshell.entity_instance, + style: Optional[ifcopenshell.entity_instance], + should_use_presentation_style_assignment: bool = False, +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns a style directly to a representation item + + A style may either be assigned directly to an object's representation + items, or to a material which is then associated with the object. If both + exist, then the style assigned directly to the object's representation + takes precedence. It is recommended to use materials and assign styles to + materials. However, sometimes you may want to assign colours directly to + the object representation as an override. This API function provides that + capability. + + If you want to assign styles to a material instead (recommended), then + please see ifcopenshell.api.style.assign_material_style. + + :param item: The IfcRepresentationItem of the object + that you want to assign styles to. + :param style: A presentation style, typically IfcSurfaceStyle. None if you + want to remove an existing style from the item. + :return: Created or existing IfcStyledItem, or None if the style was removed. + + Example: + + .. code:: python + + # A model context is needed to store 3D geometry + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + + # Specifically, we want to store body geometry + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Let's create a new block shaped furniture. The furniture does not have any geometry yet. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's use the "3D Body" representation we created earlier to add a + # new wall-like body geometry, 5 meters long, 3 meters high, and + # 200mm thick + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.2) + + # Assign our new body geometry back to our wall + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a simple grey shading colour and transparency. + ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleShading", attributes={ + "SurfaceColour": { "Name": None, "Red": 0.5, "Green": 0.5, "Blue": 0.5 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + }) + + # Now specifically our wall's only item only will be coloured grey. + ifcopenshell.api.style.assign_item_style(model, + style=style, item=representation.Items[0]) + """ + if not (styled_item := next(iter(item.StyledByItem), None)): + if style is None: + return + if file.schema == "IFC2X3" or should_use_presentation_style_assignment: + style = file.create_entity("IfcPresentationStyleAssignment", (style,)) + return file.create_entity("IfcStyledItem", item, (style,)) + + styled_item_styles = styled_item.Styles + if style and styled_item_styles == (style,): + return styled_item + + if file.schema == "IFC4X3": + if style is None: + file.remove(styled_item) + return + styled_item.Styles = (style,) + return styled_item + + # < IFC4X3 + # Can't just remove a styled item or assign a style + # since we need to remove/change the possible style assignments. + assignment = None + for style_ in styled_item_styles: + if not style_.is_a("IfcPresentationStyleAssignment"): + continue + # Remove second assignment. + if style is None or assignment: + file.remove(style_) + else: + assignment = style_ + if assignment.Styles != (style,): + assignment.Styles = (style,) + + if style is None: + file.remove(styled_item) + return + + if assignment: + if styled_item_styles == (assignment,): + return styled_item + styled_item.Styles = (assignment,) + return styled_item + + styled_item.Styles = (style,) + return styled_item diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_material_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_material_style.py new file mode 100644 index 0000000000000000000000000000000000000000..a9050a3379fc24b168d0f60b90a380b7111796a5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_material_style.py @@ -0,0 +1,246 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.style +import ifcopenshell.util.element +from typing import Any + + +def assign_material_style( + file: ifcopenshell.file, + material: ifcopenshell.entity_instance, + style: ifcopenshell.entity_instance, + context: ifcopenshell.entity_instance, + should_use_presentation_style_assignment: bool = False, +) -> None: + """Assigns a style to a material + + A style may either be assigned directly to an object's representation, + or to a material which is then associated with the object. If both + exist, then the style assigned directly to the object's representation + takes precedence. It is recommended to use materials and assign styles + to materials. This API function provides that capability. + + :param material: The IfcMaterial which you want to assign the style to. + :param style: The IfcPresentationStyle (typically IfcSurfaceStyle) that + you want to assign to the material. This will then be applied to all + objects that have that material. + :param context: The IfcGeometricRepresentationSubContext at which this + style should be used. Typically this is the Model BODY context. + :param should_use_presentation_style_assignment: This is a technical + detail to accomodate a bug in Revit. This should always be left as + the default of False, unless you are finding that colours aren't + showing up in Revit. In that case, set it to True, but keep in mind + that this is no longer a valid IFC. Blame Autodesk. + :return: None + + Example: + + .. code:: python + + # A model context is needed to store 3D geometry + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + + # Specifically, we want to store body geometry + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Let's create a new wall. The wall does not have any geometry yet. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's use the "3D Body" representation we created earlier to add a + # new wall-like body geometry, 5 meters long, 3 meters high, and + # 200mm thick + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.2) + + # Assign our new body geometry back to our wall + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + + # Let's prepare a concrete material. Note that our concrete material + # does not have any colours (styles) at this point. + concrete = ifcopenshell.api.material.add_material(model, name="CON01", category="concrete") + + # Assign our concrete material to our wall + ifcopenshell.api.material.assign_material(model, + products=[wall], type="IfcMaterial", material=concrete) + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a simple grey shading colour and transparency. + ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleShading", attributes={ + "SurfaceColour": { "Name": None, "Red": 0.5, "Green": 0.5, "Blue": 0.5 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + }) + + # Now any element (like our wall) with a concrete material will have + # a grey colour applied. + ifcopenshell.api.style.assign_material_style(model, material=concrete, style=style, context=body) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "material": material, + "style": style, + "context": context, + "should_use_presentation_style_assignment": should_use_presentation_style_assignment, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + self.style = self.settings["style"] + if self.file.schema == "IFC2X3" or self.settings["should_use_presentation_style_assignment"]: + self.style = self.file.createIfcPresentationStyleAssignment([self.settings["style"]]) + + if self.settings["material"].HasRepresentation: + self.modify_existing_definition_representation() + else: + self.create_new_definition_representation() + + # handle material constituents and shape aspects + material_constituents_names = [] + for inverse in self.file.get_inverse(self.settings["material"]): + if inverse.is_a("IfcMaterialConstituent") and inverse.Name: + material_constituents_names.append(inverse.Name) + if not material_constituents_names: + return + + elements = ifcopenshell.util.element.get_elements_by_material(self.file, self.settings["material"]) + shape_aspects = [] + for element in elements: + shape_aspects += ifcopenshell.util.element.get_shape_aspects(element) + + for shape_aspect in shape_aspects: + if shape_aspect.Name not in material_constituents_names: + continue + + for rep in shape_aspect.ShapeRepresentations: + ifcopenshell.api.style.assign_representation_styles( + self.file, shape_representation=rep, styles=[self.style] + ) + + def modify_existing_definition_representation(self): + # NOTE: while it's theoritically possible to have multiple styles per 1 material + # (either with multiple styled items or multiple styles in 1 item) + # we use an implicit convention that there is only 1 style per material. + definition_representation = self.settings["material"].HasRepresentation[0] + representation = self.get_styled_representation(definition_representation) + if representation: + items = list(representation.Items) + new_items = [] + same_style_items = [] + for item in items: + if not item.is_a("IfcStyledItem"): + continue + if self.has_proposed_style(item): + return + if self.has_same_style_type(item): + same_style_items.append(item) + else: + new_items.append(item) + item_to_reuse = same_style_items.pop(0) if same_style_items else None + new_items.append(self.create_styled_item(item_to_reuse)) + representation.Items = new_items + for item in same_style_items: + if self.file.get_total_inverses(item) == 0: + self.file.remove(item) + else: + representations = list(definition_representation.Representations) + representations.append(self.create_styled_representation()) + definition_representation.Representations = representations + + def has_proposed_style(self, styled_item: ifcopenshell.entity_instance) -> bool: + style = self.settings["style"] + styles = styled_item.Styles + if style in styles: + return True + if self.file.schema != "IFC4X3": + # IfcPresentationStyleAssignment is removed in IFC4X3 + for s in styles: + if s.is_a("IfcPresentationStyleAssignment"): + if style in s.Styles: + return True + return False + + def has_same_style_type(self, styled_item: ifcopenshell.entity_instance) -> bool: + style = self.settings["style"] + style_class = style.is_a() + for s in styled_item.Styles: + s_class = s.is_a() + if s_class == style_class: + return True + elif s_class == "IfcPresentationStyleAssignment": + for ss in s.Styles: + if ss.is_a() == style_class: + return True + return False + + def create_new_definition_representation(self): + representation = self.create_styled_representation() + definition_representation = self.file.create_entity( + "IfcMaterialDefinitionRepresentation", + **{"Representations": [representation], "RepresentedMaterial": self.settings["material"]}, + ) + + def get_styled_representation(self, definition_representation): + representations = [ + r + for r in definition_representation.Representations + if r.is_a("IfcStyledRepresentation") and r.ContextOfItems == self.settings["context"] + ] + if representations: + return representations[0] + + def create_styled_representation(self): + return self.file.create_entity( + "IfcStyledRepresentation", + **{ + "ContextOfItems": self.settings["context"], + "RepresentationIdentifier": self.settings["context"].ContextIdentifier, + "Items": [self.create_styled_item()], + }, + ) + + def create_styled_item(self, reuse_item=None): + if reuse_item is None: + return self.file.create_entity( + "IfcStyledItem", **{"Styles": [self.style], "Name": self.settings["style"].Name} + ) + + # IfcPresentationStyleAssignment we created end up not being used + # TODO: do not create IfcPresentationStyleAssignment in the first place + # as it might get removed + if reuse_item.is_a("IfcPresentationStyleAssignment") and self.style.is_a("IfcPresentationStyleAssignment"): + self.file.remove(self.style) + self.style = reuse_item + + reuse_item.Styles = (self.settings["style"],) + reuse_item.Name = self.settings["style"].Name + return reuse_item diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_representation_styles.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_representation_styles.py new file mode 100644 index 0000000000000000000000000000000000000000..b4d0fbe0e537b265ea1078f896cb116a8470fb85 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/assign_representation_styles.py @@ -0,0 +1,203 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def assign_representation_styles( + file: ifcopenshell.file, + shape_representation: ifcopenshell.entity_instance, + styles: list[ifcopenshell.entity_instance], + replace_previous_same_type_style: bool = True, + should_use_presentation_style_assignment: bool = False, +) -> list[ifcopenshell.entity_instance]: + """Assigns a style directly to an object representation + + A style may either be assigned directly to an object's representation, + or to a material which is then associated with the object. If both + exist, then the style assigned directly to the object's representation + takes precedence. It is recommended to use materials and assign styles + to materials. However, sometimes you may want to assign colours directly + to the object representation as an override. This API function provides + that capability. + + This function assigns styles in bulk in an ordered manner to every item in + the representation, so the order and total styles provided is significant. + If you want more granular control, use + :func:`ifcopenshell.api.style.assign_item_style`. + + If you want to assign styles to a material instead (recommended), then + please see ifcopenshell.api.style.assign_material_style. + + :param shape_representation: The IfcShapeRepresentation of the object + that you want to assign styles to. This implicitly defines the + context at which the styles should be used. + :param styles: A list of presentation styles, typically IfcSurfaceStyle. + The number of items in the list should correlate with the number of + items in the shape_representation's Items attribute. If you have + more items than styles, the last style is used. + :param replace_previous_same_type_style: Remove previously assigned styles + of the same type as currently assign style`. Defaults to `True`. + :param should_use_presentation_style_assignment: This is a technical + detail to accomodate a bug in Revit. This should always be left as + the default of False, unless you are finding that colours aren't + showing up in Revit. In that case, set it to True, but keep in mind + that this is no longer a valid IFC. Blame Autodesk. + :return: List of created IfcStyledItems + + Example: + + .. code:: python + + # A model context is needed to store 3D geometry + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + + # Specifically, we want to store body geometry + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Let's create a new wall. The wall does not have any geometry yet. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's use the "3D Body" representation we created earlier to add a + # new wall-like body geometry, 5 meters long, 3 meters high, and + # 200mm thick + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.2) + + # Assign our new body geometry back to our wall + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a simple grey shading colour and transparency. + ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleShading", attributes={ + "SurfaceColour": { "Name": None, "Red": 0.5, "Green": 0.5, "Blue": 0.5 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + }) + + # Now specifically our wall only will be coloured grey. + ifcopenshell.api.style.assign_representation_styles(model, + shape_representation=representation, styles=[style]) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "shape_representation": shape_representation, + "styles": styles or [], + "replace_previous_same_type_style": replace_previous_same_type_style, + "should_use_presentation_style_assignment": should_use_presentation_style_assignment, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + results: list[ifcopenshell.entity_instance] + + def execute(self): + if not self.settings["styles"]: + return [] + self.settings["styles"] = self.settings["styles"].copy() + self.results = [] + use_style_assignment = self.file.schema == "IFC2X3" or self.settings["should_use_presentation_style_assignment"] + replace_previous_same_type_style = self.settings["replace_previous_same_type_style"] + + for element in self.file.traverse(self.settings["shape_representation"]): + if not element.is_a("IfcShapeModel"): + continue + for item in element.Items: + if not item.is_a("IfcGeometricRepresentationItem") and not item.is_a( + "IfcTopologicalRepresentationItem" + ): + continue + if self.settings["styles"]: + # If there are more items than styles, fallback to using the last style + style = self.settings["styles"].pop(0) + name = style.Name + current_style_type = style.is_a() + + # item may had previous styled item + prev_styled_item = next((i for i in item.StyledByItem), None) + style_assignment = None # try to find some style assignment to reuse + + if prev_styled_item is None: + if use_style_assignment: + style_assignment = self.file.createIfcPresentationStyleAssignment([style]) + self.results.append(self.file.createIfcStyledItem(item, [style_assignment], name)) + else: + self.results.append(self.file.createIfcStyledItem(item, [style], name)) + continue + + if replace_previous_same_type_style: + self.remove_same_type_styles(prev_styled_item, current_style_type, remove_item=False) + for style_ in prev_styled_item.Styles: + if style_.is_a("IfcPresentationStyleAssignment"): + if use_style_assignment and style_assignment is None: + style_assignment = style_ + self.remove_same_type_styles(style_assignment, current_style_type, remove_item=False) + else: + self.remove_same_type_styles(style_assignment, current_style_type, remove_item=True) + + if use_style_assignment: + if style_assignment: + style_assignment.Styles = style_assignment.Styles + (style,) + else: + style_assignment = self.file.createIfcPresentationStyleAssignment([style]) + prev_styled_item.Styles = prev_styled_item.Styles + (style_assignment,) + else: + prev_styled_item.Styles = prev_styled_item.Styles + (style,) + continue + + # collect previously assigned styles + assigned_styles = [] + for style_ in prev_styled_item.Styles: + if style_.is_a("IfcPresentationStyleAssignment"): + if style_assignment is None: + style_assignment = style_ + assigned_styles.extend(style_.Styles) + else: # IfcPresentationStyle + assigned_styles.append(style_) + + if style in assigned_styles: + continue + + if use_style_assignment: + if style_assignment is not None: + style_assignment.Styles = style_assignment.Styles + (style,) + else: + style_assignment = self.file.createIfcPresentationStyleAssignment([style]) + prev_styled_item.Styles = prev_styled_item.Styles + (style_assignment,) + else: + prev_styled_item.Styles = prev_styled_item.Styles + (style,) + + return self.results + + def remove_same_type_styles(self, style_item, current_style_type: str, remove_item: bool) -> None: + styles = [s for s in style_item.Styles if s.is_a() != current_style_type] + if remove_item and not styles: + self.file.remove(style_item) + else: + style_item.Styles = styles diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_presentation_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_presentation_style.py new file mode 100644 index 0000000000000000000000000000000000000000..7a39629528dda5cf5dc69e154e305a781df11148 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_presentation_style.py @@ -0,0 +1,45 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def edit_presentation_style( + file: ifcopenshell.file, style: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcPresentationStyle + + For more information about the attributes and data types of an + IfcPresentationStyle, consult the IFC documentation. + + :param style: The IfcPresentationStyle entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Change the name of the style to "Foo" + ifcopenshell.api.style.edit_presentation_style(model, style=style, attributes={"Name": "Foo"}) + """ + for name, value in attributes.items(): + setattr(style, name, value) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_surface_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_surface_style.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7f05948d28b4dbb27a901c553a38745f4bde95 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/edit_surface_style.py @@ -0,0 +1,137 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any, Union + + +def edit_surface_style( + file: ifcopenshell.file, style: ifcopenshell.entity_instance, attributes: dict[str, Any] +) -> None: + """Edits the attributes of an IfcPresentationItem + + For more information about the attributes and data types of an + IfcPresentationItem, consult the IFC documentation. + + The IfcPresentationItem is expected to be one of IfcSurfaceStyleShading, + IfcSurfaceStyleRendering, IfcSurfaceStyleWithTextures, + IfcSurfaceStyleLighting, IfcSurfaceStyleReflectance, or + IfcExternallyDefinedSurfaceStyle. + + To represent a colour, a nested dictionary should be used. See the + example below. + + :param style: The IfcPresentationStyle entity you want to edit + :param attributes: a dictionary of attribute names and values. + :return: None + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a blank rendering style. + rendering = ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleRendering") + + # Edit the attributes of the rendering style. + ifcopenshell.api.style.edit_surface_style(model, + style=rendering, attributes={ + # A surface colour and transparency is still supplied for + # viewport display only. This will supersede the shading + # presentation item. + "SurfaceColour": { "Name": None, "Red": 1.0, "Green": 0.8, "Blue": 0.8 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + + # NOTDEFINED is assumed to be a PHYSICAL (PBR) lighting + # model. In IFC4X3, you may choose PHYSICAL directly. + "ReflectanceMethod": "NOTDEFINED", + + # For PBR shading, you may specify these parameters: + "DiffuseColour": { "Name": None, "Red": 0.9, "Green": 0.8, "Blue": 0.8 }, + "SpecularColour": 0.1, # Metallic factor + "SpecularHighlight": {"SpecularRoughness": 0.5}, # Roughness factor + }) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(style, attributes) + + +class Usecase: + file: ifcopenshell.file + + def execute(self, style: ifcopenshell.entity_instance, attributes: dict[str, Any]) -> None: + self.style = style + + attribute_types: dict[str, str] = {} + for attribute in style.wrapped_data.declaration().as_entity().all_attributes(): + attribute_type = attribute.type_of_attribute() + if attribute_type.as_aggregation_type() is None: + attribute_type = attribute_type.declared_type().name() + else: + # doesn't have .declared_type() + attribute_type = attribute_type.type_of_element() + attribute_types[attribute.name()] = attribute_type + + for key, value in attributes.items(): + attribute_class = attribute_types.get(key) + if attribute_class == "IfcColourRgb": + self.edit_colour_rgb(key, value) + elif key == "SpecularHighlight": + self.edit_specular_highlight(value) + elif attribute_class == "IfcColourOrFactor": + self.edit_colour_or_factor(key, value) + else: + setattr(style, key, value) + + def edit_colour_rgb(self, name: str, value: dict[str, Any]): + if (attribute := getattr(self.style, name)) is None: + attribute = self.file.createIfcColourRgb() + setattr(self.style, name, attribute) + attribute.Name = value.get("Name", None) + attribute.Red = value["Red"] + attribute.Green = value["Green"] + attribute.Blue = value["Blue"] + + def edit_colour_or_factor(self, name: str, value: Union[dict[str, Any], ifcopenshell.entity_instance, None]): + if isinstance(value, dict): + attribute = getattr(self.style, name) + if not attribute or not attribute.is_a("IfcColourRgb"): + colour = self.file.createIfcColourRgb(None, 0, 0, 0) + setattr(self.style, name, colour) + attribute = getattr(self.style, name) + attribute[1] = value["Red"] + attribute[2] = value["Green"] + attribute[3] = value["Blue"] + else: # assume it's float value for IfcNormalisedRatioMeasure or None + existing_value = getattr(self.style, name) + if existing_value and existing_value.id(): + self.file.remove(existing_value) + if value is not None: + value = self.file.create_entity("IfcNormalisedRatioMeasure", value) + setattr(self.style, name, value) + + def edit_specular_highlight(self, value: Union[dict[str, Any], None]) -> None: + if value is None: + self.style.SpecularHighlight = None + elif value.get("IfcSpecularExponent", None): + self.style.SpecularHighlight = self.file.createIfcSpecularExponent(value["IfcSpecularExponent"]) + elif value.get("IfcSpecularRoughness", None): + self.style.SpecularHighlight = self.file.createIfcSpecularRoughness(value["IfcSpecularRoughness"]) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_style.py new file mode 100644 index 0000000000000000000000000000000000000000..3637dcaca7d8001f0c6d377fbab91a8525eca837 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_style.py @@ -0,0 +1,92 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.api.style +import ifcopenshell.util.element +from collections.abc import Iterable + + +def remove_style(file: ifcopenshell.file, style: ifcopenshell.entity_instance) -> None: + """Removes a presentation style + + All of the presentation items of the style will also be removed. + + :param style: The IfcPresentationStyle to remove. + :return: None + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Not anymore! + ifcopenshell.api.style.remove_style(model, style=style) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(style) + + +class Usecase: + file: ifcopenshell.file + + def execute( + self, style: ifcopenshell.entity_instance, do_not_delete: Iterable[ifcopenshell.entity_instance] = () + ) -> None: + self.purge_inverses(style) + ifc_class = style.is_a() + if ifc_class == "IfcSurfaceStyle": + for style_ in style.Styles: + ifcopenshell.api.style.remove_surface_style(self.file, style=style_) + elif ifc_class == "IfcFillAreaStyle": + for style_ in style.FillStyles: + ifcopenshell.util.element.remove_deep2( + self.file, style_, also_consider=[style], do_not_delete=list(do_not_delete) + ) + self.file.remove(style) + + def purge_inverses(self, style: ifcopenshell.entity_instance) -> None: + for inverse in self.file.get_inverse(style): + if inverse.is_a("IfcStyledItem"): + if len(inverse.Styles) == 1: + self.purge_styled_representations(inverse) + self.file.remove(inverse) + # IfcCurveStyle -> IfcFillAreaStyleHatching. + elif inverse.is_a("IfcFillAreaStyleHatching"): + self.purge_fill_area_style_hatching(inverse, style) + + def purge_styled_representations(self, styled_item: ifcopenshell.entity_instance) -> None: + for inverse in self.file.get_inverse(styled_item): + if inverse.is_a("IfcStyledRepresentation") and len(inverse.Items) == 1: + self.purge_material_definition_representations(inverse) + self.file.remove(inverse) + + def purge_material_definition_representations(self, styled_representation: ifcopenshell.entity_instance) -> None: + for inverse in self.file.get_inverse(styled_representation): + if inverse.is_a("IfcMaterialDefinitionRepresentation") and len(inverse.Representations) == 1: + self.file.remove(inverse) + + def purge_fill_area_style_hatching( + self, fill_area_style_hatching: ifcopenshell.entity_instance, style: ifcopenshell.entity_instance + ) -> None: + for inverse in self.file.get_inverse(fill_area_style_hatching): + if inverse.is_a("IfcFillAreaStyle"): + self.execute(inverse, do_not_delete=(fill_area_style_hatching, style)) + ifcopenshell.util.element.remove_deep2(self.file, fill_area_style_hatching, do_not_delete=[style]) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_styled_representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_styled_representation.py new file mode 100644 index 0000000000000000000000000000000000000000..d8441cd43a6c89af67f0c5fc494f155030ab2a08 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_styled_representation.py @@ -0,0 +1,48 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell + + +def remove_styled_representation(file: ifcopenshell.file, representation: ifcopenshell.entity_instance) -> None: + """Removes a styled representation + + Styled representations are typically associated with materials. This + removes the representation but not the underlying styles. + + :param representation: The IfcStyledRepresentation to remove. + :return: None + + Example: + + .. code:: python + + # Remove a styled representation + ifcopenshell.api.style.remove_styled_representation(model, representation=representation) + """ + for inverse in file.get_inverse(representation): + if inverse.is_a("IfcMaterialDefinitionRepresentation") and len(inverse.Representations) == 1: + file.remove(inverse) + + for item in representation.Items: + if item.is_a("IfcStyledItem") and file.get_total_inverses(item) == 1: + for style in item.Styles: + if style.is_a("IfcPresentationStyleAssignment"): + file.remove(style) + file.remove(item) + + file.remove(representation) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_surface_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_surface_style.py new file mode 100644 index 0000000000000000000000000000000000000000..19bb9e1b7940a04af395bc9e9133ee90f75fef2a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/remove_surface_style.py @@ -0,0 +1,67 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.util.element + + +def remove_surface_style(file: ifcopenshell.file, style: ifcopenshell.entity_instance) -> None: + """Removes a presentation item from a presentation style + + :param style: The IfcPresentationItem to remove. + :return: None + + Example: + + .. code:: python + + # Create a new surface style + style = ifcopenshell.api.style.add_style(model) + + # Create a simple shading colour and transparency. + shading = ifcopenshell.api.style.add_surface_style(model, + style=style, ifc_class="IfcSurfaceStyleShading", attributes={ + "SurfaceColour": { "Name": None, "Red": 1.0, "Green": 0.8, "Blue": 0.8 }, + "Transparency": 0., # 0 is opaque, 1 is transparent + }) + + # Remove the shading item + ifcopenshell.api.style.remove_surface_style(model, style=shading) + """ + + to_delete = set() + if style.is_a("IfcSurfaceStyleWithTextures"): + textures = style.Textures + if file.schema == "IFC2X3": + to_delete.update(textures) + else: + for texture in textures: + if coords := texture.IsMappedBy: + for coordinate in coords: + to_delete.add(coordinate) + else: + to_delete.add(texture) + + for attribute in style: + if isinstance(attribute, ifcopenshell.entity_instance) and attribute.id(): + to_delete.add(attribute) + + file.remove(style) + + for element in to_delete: + ifcopenshell.util.element.remove_deep2(file, element) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_material_style.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_material_style.py new file mode 100644 index 0000000000000000000000000000000000000000..7b4c6578bd95c745390cfe85c658f3de65d031b4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_material_style.py @@ -0,0 +1,101 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import ifcopenshell +import ifcopenshell.api.style +import ifcopenshell.util.element + + +def unassign_material_style( + file: ifcopenshell.file, + material: ifcopenshell.entity_instance, + style: ifcopenshell.entity_instance, + context: ifcopenshell.entity_instance, +) -> None: + """Unassigns a style to a material + + This does the inverse of assign_material_style. + + :param material: The IfcMaterial which you want to unassign the style from. + :param style: The IfcPresentationStyle (typically IfcSurfaceStyle) that + you want to unassign from material. This will then be applied to all + objects that have that material. + :param context: The IfcGeometricRepresentationSubContext at which this + style should be unassigned. Typically this is the Model BODY context. + :return: None + + Example: + + .. code:: python + + ifcopenshell.api.style.unassign_material_style(model, material=concrete, style=style, context=body) + """ + settings = { + "material": material, + "style": style, + "context": context, + } + + for definition in settings["material"].HasRepresentation: + for representation in definition.Representations: + if not representation.is_a("IfcStyledRepresentation"): + continue + if representation.ContextOfItems != settings["context"]: + continue + for item in representation.Items: + if not item.is_a("IfcStyledItem"): + continue + styles = [] + for s in item.Styles: + if s == settings["style"]: + continue + if s.is_a("IfcPresentationStyleAssignment"): + if s.Styles == (settings["style"],): + continue + styles.append(s) + if not styles: + file.remove(item) + elif len(styles) != len(item.Styles): + item.Styles = styles + if not representation.Items: + file.remove(representation) + if not definition.Representations: + file.remove(definition) + + # handle material constituents and shape aspects + material_constituents_names = [] + for inverse in file.get_inverse(settings["material"]): + if inverse.is_a("IfcMaterialConstituent") and inverse.Name: + material_constituents_names.append(inverse.Name) + if not material_constituents_names: + return + + elements = ifcopenshell.util.element.get_elements_by_material(file, settings["material"]) + shape_aspects = [] + for element in elements: + shape_aspects += ifcopenshell.util.element.get_shape_aspects(element) + + for shape_aspect in shape_aspects: + if shape_aspect.Name not in material_constituents_names: + continue + + for rep in shape_aspect.ShapeRepresentations: + ifcopenshell.api.style.unassign_representation_styles( + file, shape_representation=rep, styles=[settings["style"]] + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_representation_styles.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_representation_styles.py new file mode 100644 index 0000000000000000000000000000000000000000..47a542c1b7f3a011b86d45b551d9a6ef90823e62 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/style/unassign_representation_styles.py @@ -0,0 +1,96 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +import ifcopenshell +from typing import Any + + +def unassign_representation_styles( + file: ifcopenshell.file, + shape_representation: ifcopenshell.entity_instance, + styles: list[ifcopenshell.entity_instance], + should_use_presentation_style_assignment: bool = False, +) -> None: + """Unassigns styles directly assigned to an object representation + + This does the inverse of assign_representation_styles. + + :param shape_representation: The IfcShapeRepresentation of the object + that you want to unassign styles from. + :param styles: A list of presentation styles, typically IfcSurfaceStyle. + The number of items in the list should correlate with the number of + items in the shape_representation's Items attribute. If you have + more items than styles, the last style is used. + :param should_use_presentation_style_assignment: This is a technical + detail to accomodate a bug in Revit. This should always be left as + the default of False, unless you are finding that colours aren't + showing up in Revit. In that case, set it to True, but keep in mind + that this is no longer a valid IFC. Blame Autodesk. + :return: None + + Example: + + .. code:: python + + ifcopenshell.api.style.unassign_representation_styles(model, + shape_representation=representation, styles=[style]) + """ + usecase = Usecase() + usecase.file = file + usecase.settings = { + "shape_representation": shape_representation, + "styles": styles or [], + "should_use_presentation_style_assignment": should_use_presentation_style_assignment, + } + return usecase.execute() + + +class Usecase: + file: ifcopenshell.file + settings: dict[str, Any] + + def execute(self): + if not self.settings["styles"]: + return [] + self.results = [] + use_style_assignment = self.file.schema == "IFC2X3" or self.settings["should_use_presentation_style_assignment"] + + for element in self.file.traverse(self.settings["shape_representation"]): + if not element.is_a("IfcShapeRepresentation"): + continue + for item in element.Items: + if not item.is_a("IfcGeometricRepresentationItem"): + continue + + if not item.StyledByItem: + continue + + item = item.StyledByItem[0] + if use_style_assignment: + for style_ in item.Styles: + if style_.is_a("IfcPresentationStyleAssignment"): + self.remove_styles(style_) + self.remove_styles(item) + + def remove_styles(self, item): + """Removes styles from a styled item or a style assignment + and purges item if doesn't have any styles after""" + styles = [s for s in item.Styles if s not in self.settings["styles"]] + if not styles: + self.file.remove(item) + elif len(styles) != len(item.Styles): + item.Styles = styles diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..709e4aa00f874f65a3505864d790a730de683969 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/__init__.py @@ -0,0 +1,38 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Manage common construction types of physical elements + +Almost all constructed elements may be grouped into "types". Types include wall +types, window types, column types, equipment types, and more. + +Using types is critical to the success of any project. +""" + +from .. import wrap_usecases +from .assign_type import assign_type +from .map_type_representations import map_type_representations +from .unassign_type import unassign_type + +wrap_usecases(__path__, __name__) + +__all__ = [ + "assign_type", + "map_type_representations", + "unassign_type", +] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/assign_type.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/assign_type.py new file mode 100644 index 0000000000000000000000000000000000000000..f412d4dd2e262f861276680747425ff2000f8dbb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/assign_type.py @@ -0,0 +1,279 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.type +import ifcopenshell.api.owner +import ifcopenshell.api.material +import ifcopenshell.guid +import ifcopenshell.util.element +from typing import Union + + +def assign_type( + file: ifcopenshell.file, + related_objects: list[ifcopenshell.entity_instance], + relating_type: ifcopenshell.entity_instance, + should_map_representations=True, +) -> Union[ifcopenshell.entity_instance, None]: + """Assigns a type to occurrences of an object + + IFC supports the concept of occurrences and types. An occurrence is an + actual physical product in the real world: like a wall, a chair, a door, + a column, a pump, and so on. + + Most occurrences have a corresponding type. A type describes either a + common shape and set of properties of a particular model of equipment, + or a construction typology. An occurrence may only have zero or one + type. + + For example, architects would typically have a door schedule for + individual occurrences of doors and a door types schedule for a handful + of door types, described by the door hardware, frame, and panel. Other + examples might be window types or wall types. Structural engineers would + have a list of column types, beam types, slab types, etc, such as a 400 + diameter column, a 500 diameter column, and so on. Services consultant + might nominate a particular type of sprinkler which have many + occurrences, or light fixture types, and so on. + + Types are critical as they communicate to the procurement team what + types of equipment and products need to be procured. The individual + occurrences of that type tell them how many to procure. Types are also + critical in construction as they indicate succinctly how to manufacture + or construct something. For example, a wall type is enough information + for a builder to understand the build up and construction of a wall. + Types are used to help break down cost plans, or isolate portions of an + assembly process for construction scheduling. Types are also used in + facility maintenance, as occurrences sharing the same type can be + repaired in the same way or by replacing the same parts. + + An occurrence of a type inherits all the properties and materials of the + type. For example, a 2HR fire rated wall type implies that all + wall occurrences of that wall type will also be 2HR fire rated. + + A type may or may not have a geometric representation. If a type does + not have any representation, then the occurrences are free to have any + representation of their own. However, if a type has a representation, + all occurrences must have the same representation. For example, if a + light fixture downlight type has a representation of a cylinder, then + all occurrences must have exactly the same cylinder as its + representation. If you change the cylinder's shape of the type, then all + occurrence representations will also change. + + If a type does not have any geometric representation, they may have a + parametric material representation. This may be either a parametric + layered material or parametric cross-sectional profile material. If this + is the case, the occurrence must be constructed out of the parametric + material. For example, if a wall type uses a list of parametric layers + indicating a thickness of 13mm plasterboard and 90mm stud, then the + thickness of every wall occurrence representation must be 103mm. The + length of each wall, however, may vary. Similarly, if a beam type has a + parametric profile material of an I-beam, then all beam occurrences must + also be this I-beam shape, though the length may vary. + + It is highly recommended for every occurrence to have a type. There are + some exceptions to the rule, such as in heritage architecture or + as-built or dilapidation models, where existing conditions are + ambiguous, unknown or are so bespoke as to have no logical type. + + :param related_objects: The IfcElement occurrences. + :param relating_type: The IfcElementType type. + :param should_map_representations: If a type has a representation map, + IFC requires all occurrences to map those representations. Some IFC + vendors might disobey this, or you might want to handle it + yourusecase. In this scenario, you may set this to False. + This also enabled adding material usages mapping. + :return: The IfcRelDefinesByType relationship + or `None` if `related_objects` was empty list. + + Example: + + .. code:: python + + # A furniture type. This would correlate to a particular model in a + # manufacturer's catalogue. Like an Ikea sofa :) + furniture_type = ifcopenshell.api.root.create_entity(model, + ifc_class="IfcFurnitureType", name="FUN01") + + # An individual occurrence of a that sofa. + furniture = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + + # Assign the furniture to the furniture type. If the furniture_type + # had a representation, the furniture occurrence will also now have + # the exact same representation. This is highly efficient as you + # don't need to define the representation for every occurrence. + ifcopenshell.api.type.assign_type(model, related_objects=[furniture], relating_type=furniture_type) + + # Let's imagine a parametric material layer set + wall_type = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWallType", name="WAL01") + + # First, let's create a material set. This will later be assigned + # to our wall type element. + material_set = ifcopenshell.api.material.add_material_set(model, + name="GYP-ST-GYP", set_type="IfcMaterialLayerSet") + + # Let's create a few materials, it's important to also give them + # categories. This makes it easy for model recipients to do things + # like "show me everything made out of aluminium / concrete / steel + # / glass / etc". The IFC specification states a list of categories + # you can use. + gypsum = ifcopenshell.api.material.add_material(model, name="PB01", category="gypsum") + steel = ifcopenshell.api.material.add_material(model, name="ST01", category="steel") + + # Now let's use those materials as three layers in our set, such + # that the steel studs are sandwiched by the gypsum. Let's imagine + # we're setting the layer thickness in millimeters. + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": .013}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=steel) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": .092}) + layer = ifcopenshell.api.material.add_layer(model, layer_set=material_set, material=gypsum) + ifcopenshell.api.material.edit_layer(model, layer=layer, attributes={"LayerThickness": .013}) + + # Great! Let's assign our material set to our wall type. + ifcopenshell.api.material.assign_material(model, products=[wall_type], material=material_set) + + # Now, let's create a wall. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # The wall is a WAL01 wall type. + ifcopenshell.api.type.assign_type(model, related_objects=[wall], relating_type=wall_type) + + # A bit of preparation, let's create some geometric contexts since + # we want to create some geometry for our wall. + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Notice how our thickness of 0.118 must equal .013 + .092 + .013 from our type + representation = ifcopenshell.api.geometry.add_wall_representation(model, + context=body, length=5, height=3, thickness=0.118) + + # Assign our new body geometry back to our wall + ifcopenshell.api.geometry.assign_representation(model, + product=wall, representation=representation) + + # Place our wall at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=wall) + """ + usecase = Usecase() + usecase.file = file + return usecase.execute(related_objects, relating_type, should_map_representations) + + +class Usecase: + file: ifcopenshell.file + + def execute( + self, + related_objects: list[ifcopenshell.entity_instance], + relating_type: ifcopenshell.entity_instance, + should_map_representations: bool, + ): + if not related_objects: + return + + ifc2x3 = self.file.schema == "IFC2X3" + related_objects_set = set(related_objects) + if ifc2x3: + types = next(iter(relating_type.ObjectTypeOf), None) + else: + types = next(iter(relating_type.Types), None) + + previous_types_rels: set[ifcopenshell.entity_instance] = set() + objects_without_types: list[ifcopenshell.entity_instance] = [] + objects_with_types: list[ifcopenshell.entity_instance] = [] + + # check if there is anything to change + for obj in related_objects_set: + if ifc2x3: + object_rel = next((i for i in obj.IsDefinedBy if i.is_a("IfcRelDefinesByType")), None) + else: + object_rel = next(iter(obj.IsTypedBy), None) + + if object_rel is None: + objects_without_types.append(obj) + continue + + # either rel doesn't exist or product is part of different rel + if object_rel != types: + previous_types_rels.add(object_rel) + objects_with_types.append(obj) + + objects_to_change = objects_without_types + objects_with_types + # nothing to change + if not objects_to_change: + return types + + # unassign from previous types + for is_typed_by in previous_types_rels: + cur_related_objects = set(is_typed_by.RelatedObjects) - related_objects_set + if cur_related_objects: + is_typed_by.RelatedObjects = list(cur_related_objects) + ifcopenshell.api.owner.update_owner_history(self.file, element=is_typed_by) + else: + history = is_typed_by.OwnerHistory + self.file.remove(is_typed_by) + if history: + ifcopenshell.util.element.remove_deep2(self.file, history) + + # assign objects to a new type + if types: + types.RelatedObjects = list(set(types.RelatedObjects) | related_objects_set) + ifcopenshell.api.owner.update_owner_history(self.file, element=types) + else: + types = self.file.create_entity( + "IfcRelDefinesByType", + GlobalId=ifcopenshell.guid.new(), + OwnerHistory=ifcopenshell.api.owner.create_owner_history(self.file), + RelatedObjects=list(related_objects_set), + RelatingType=relating_type, + ) + + if should_map_representations: + if getattr(relating_type, "RepresentationMaps", None): + for related_object in objects_to_change: + ifcopenshell.api.type.map_type_representations( + self.file, + related_object=related_object, + relating_type=relating_type, + ) + self.map_material_usages(objects_to_change, relating_type) + + # Remove PredefinedType / ObjectType if existing to forbid double typing(See #7006) + predefined_type = ifcopenshell.util.element.get_predefined_type(relating_type) + if predefined_type != "NOTDEFINED" and predefined_type is not None: + for obj in related_objects_set: + obj.ObjectType = None + if hasattr(obj, "PredefinedType"): + obj.PredefinedType = None + return types + + def map_material_usages( + self, related_objects: list[ifcopenshell.entity_instance], relating_type: ifcopenshell.entity_instance + ) -> None: + type_material = ifcopenshell.util.element.get_material(relating_type) + if not type_material: + return + ifc_class = type_material.is_a() + if ifc_class in ("IfcMaterialLayerSet", "IfcMaterialProfileSet"): + ifcopenshell.api.material.assign_material( + self.file, + products=related_objects, + type=f"{ifc_class}Usage", + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/map_type_representations.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/map_type_representations.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4c66ae16005e39cc1c0523de020c6c5a88fd5f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/map_type_representations.py @@ -0,0 +1,103 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.geometry +import ifcopenshell.util.element + + +def map_type_representations( + file: ifcopenshell.file, + related_object: ifcopenshell.entity_instance, + relating_type: ifcopenshell.entity_instance, +) -> None: + """Ensures that all occurrences has the same representation as the type + + If a type has a representation, all occurrences must have the same + representation. If the type's representation changes, this function may + be used to ensure consistency of the occurrence's representations. + + :param related_object: The IfcElement occurrence. + :param relating_type: The IfcElementType type. + :return: None + + Example: + + .. code:: python + + # A furniture type. This would correlate to a particular model in a + # manufacturer's catalogue. Like an Ikea sofa :) + furniture_type = ifcopenshell.api.root.create_entity(model, + ifc_class="IfcFurnitureType", name="FUN01") + + # An individual occurrence of a that sofa. + furniture = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + + # Place our furniture at the origin + ifcopenshell.api.geometry.edit_object_placement(model, product=furniture) + + # Assign the furniture to the furniture type. Right now, the + # furniture type has no representation, so the furniture may also + # have no representation, or any arbitrary representation that may + # vary from occurrence to occurrence. + ifcopenshell.api.type.assign_type(model, related_objects=[furniture], relating_type=furniture_type) + + # A bit of preparation, let's create some geometric contexts since + # we want to create some geometry for our furniture type. + model3d = ifcopenshell.api.context.add_context(model, context_type="Model") + body = ifcopenshell.api.context.add_context(model, + context_type="Model", context_identifier="Body", target_view="MODEL_VIEW", parent=model3d) + + # Let's create a mesh representation of an arbitrary 2m cube. + representation = ifcopenshell.api.geometry.add_sverchok_representation(model, context=body, + vertices=[[(-1.0, -1.0, 0.0), (-1.0, -1.0, 2.0), (-1.0, 1.0, 0.0), (-1.0, 1.0, 2.0), + (1.0, -1.0, 0.0), (1.0, -1.0, 2.0), (1.0, 1.0, 0.0), (1.0, 1.0, 2.0)]], + faces=[[[0, 1, 3, 2], [2, 3, 7, 6], [6, 7, 5, 4], [4, 5, 1, 0], [2, 6, 4, 0], [7, 3, 1, 5]]]) + + # Assign our new body geometry back to our furniture type. In this + # case, since we use the API, all occurrences automatically get the + # representation mapped, so there is nothing more we need to do. + ifcopenshell.api.geometry.assign_representation(model, + product=furniture_type, representation=representation) + + # However, if you were doing some sort of manual IFC patching, like + # assigning furniture_type.RepresentationMaps directly, then you + # might make this call: + # ifcopenshell.api.type.map_type_representations(model, + # related_object=furniture, relating_type=furniture_type) + """ + if not relating_type.RepresentationMaps: + return + representations = [] + if related_object.Representation: + representations = related_object.Representation.Representations + for representation in representations: + ifcopenshell.api.geometry.unassign_representation( + file, + product=related_object, + representation=representation, + ) + ifcopenshell.api.geometry.remove_representation(file, representation=representation) + for representation_map in relating_type.RepresentationMaps: + representation = representation_map.MappedRepresentation + mapped_representation = ifcopenshell.api.geometry.map_representation(file, representation=representation) + ifcopenshell.api.geometry.assign_representation( + file, + product=related_object, + representation=mapped_representation, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/unassign_type.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/unassign_type.py new file mode 100644 index 0000000000000000000000000000000000000000..bd09018aa0af27a9a69b5f64502e169277f1b630 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/api/type/unassign_type.py @@ -0,0 +1,71 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.api.owner +import ifcopenshell.util.element + + +def unassign_type(file: ifcopenshell.file, related_objects: list[ifcopenshell.entity_instance]) -> None: + """Unassigns a type from occurrences + + Note that unassigning a type doesn't automatically remove mapped representations + and material usages associated with the previously assigned type. + + :param related_objects: List of IfcElement occurrences. + :return: None + + Example: + + .. code:: python + + # A furniture type. This would correlate to a particular model in a + # manufacturer's catalogue. Like an Ikea sofa :) + furniture_type = ifcopenshell.api.root.create_entity(model, + ifc_class="IfcFurnitureType", name="FUN01") + + # An individual occurrence of a that sofa. + furniture = ifcopenshell.api.root.create_entity(model, ifc_class="IfcFurniture") + + # Assign the furniture to the furniture type. + ifcopenshell.api.type.assign_type(model, related_objects=[furniture], relating_type=furniture_type) + + # Change our mind. Maybe it's a different type? + ifcopenshell.api.type.unassign_type(model, related_objects=[furniture]) + """ + related_objects_set = set(related_objects) + + if file.schema == "IFC2X3": + rels = set( + rel + for object in related_objects_set + if (rel := next((rel for rel in object.IsDefinedBy if rel.is_a("IfcRelDefinesByType")), None)) + ) + else: + rels = set(rel for object in related_objects_set if (rel := next((rel for rel in object.IsTypedBy), None))) + + for rel in rels: + related_objects_set = set(rel.RelatedObjects) - related_objects_set + if related_objects_set: + rel.RelatedObjects = list(related_objects_set) + ifcopenshell.api.owner.update_owner_history(file, element=rel) + else: + history = rel.OwnerHistory + file.remove(rel) + if history: + ifcopenshell.util.element.remove_deep2(file, history) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocAttribute.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocAttribute.csv new file mode 100644 index 0000000000000000000000000000000000000000..0853276dbc3da568b3f854476c2770a4f2fa79c7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocAttribute.csv @@ -0,0 +1,4891 @@ +32;Identification;Identification of the organization. +33;Name;The word, or group of words, by which the organization is referred to. +34;Description;Text that relates the nature of the organization. +35;Roles;Roles played by the organization. +36;Addresses;" +Postal and telecom addresses of an organization. +
NOTE: There may be several addresses related to an organization. +
+
" +37;IsRelatedBy;The inverse relationship for relationship RelatedOrganizations of IfcOrganizationRelationship. +38;Relates;The inverse relationship for relationship RelatingOrganization of IfcOrganizationRelationship. +39;Engages;Inverse relationship to IfcPersonAndOrganization relationships in which IfcOrganization is engaged. +41;Role;"The name of the role played by an actor. If the Role has value USERDEFINED, then +the user defined role shall be provided as a value of the attribute UserDefinedRole." +42;UserDefinedRole;"Allows for specification of user defined roles beyond the +enumeration values provided by Role attribute of type IfcRoleEnum. +When a value is provided for attribute UserDefinedRole in parallel +the attribute Role shall have enumeration value USERDEFINED." +43;Description;A textual description relating the nature of the role played by an actor. +44;HasExternalReference;" +Reference to external information, e.g. library, classification, or document information, which is associated with the actor role. +
+ + +IFC2x4 CHANGE New inverse attribute. + + +
+
" +73;Purpose;Identifies the logical location of the address. +74;Description;Text that relates the nature of the address. +75;UserDefinedPurpose;"Allows for specification of user specific purpose of the address beyond the +enumeration values provided by Purpose attribute of type IfcAddressTypeEnum. +When a value is provided for attribute UserDefinedPurpose, in parallel the +attribute Purpose shall have enumeration value USERDEFINED." +76;OfPerson;The inverse relationship to Person to whom address is associated. +77;OfOrganization;The inverse relationship to Organization to whom address is associated. +80;InternalLocation;An organization defined address for internal mail delivery. +81;AddressLines;" +The postal address. +
NOTE: A postal address may occupy several lines (or elements) when recorded. +It is expected that normal usage will incorporate relevant elements of the following address concepts: +A location within a building (e.g. 3rd Floor) Building name (e.g. Interoperability House) Street number +(e.g. 6400) Street name (e.g. Alliance Boulevard). Typical content of address lines may vary in different +countries. +
+
" +82;PostalBox;An address that is implied by an identifiable mail drop. +83;Town;The name of a town. +84;Region;" +The name of a region. +
NOTE: The counties of the United Kingdom and the states of North America are examples of regions. +
+
" +85;PostalCode;The code that is used by the country's postal service. +86;Country;The name of a country. +89;TelephoneNumbers;The list of telephone numbers at which telephone messages may be received. +90;FacsimileNumbers;The list of fax numbers at which fax messages may be received. +91;PagerNumber;The pager number at which paging messages may be received. +92;ElectronicMailAddresses;The list of Email addresses at which Email messages may be received. +93;WWWHomePageURL;" +The world wide web address at which the preliminary page of information for the person or organization can be located. +
NOTE: Information on the world wide web for a person or organization may be separated +into a number of pages and across a number of host sites, all of which may be linked together. It is assumed that +all such information may be referenced from a single page that is termed the home page for that person or organization. +
+
" +94;MessagingIDs;IDs or addresses for any other means of telecommunication, for example instant messaging, voice-over-IP, or file transfer protocols. The communication protocol is indicated by the URI value with scheme designations such as irc:, sip:, or ftp:. +103;Identification;Identification of the person. +104;FamilyName;" +The name by which the family identity of the person may be recognized. +
NOTE: Depending on geographical location and culture, family name may appear either as the first or last component of a name.
+
" +105;GivenName;" +The name by which a person is known within a family and by which he or she may be familiarly recognized. +
NOTE: Depending on geographical location and culture, given name may appear either as the first or last component of a name.
+
" +106;MiddleNames;" +Additional names given to a person that enable their identification apart from others who may have the same or similar family and given names. +
NOTE: Middle names are not normally used in familiar communication but may be asserted to provide additional +identification of a particular person if necessary. They may be particularly useful in situations where the person concerned has a +family name that occurs commonly in the geographical region. +
+
" +107;PrefixTitles;The word, or group of words, which specify the person's social and/or professional standing and appear before his/her names. +108;SuffixTitles;The word, or group of words, which specify the person's social and/or professional standing and appear after his/her names. +109;Roles;Roles played by the person. +110;Addresses;" +Postal and telecommunication addresses of a person. +
NOTE - A person may have several addresses. +
+
" +111;EngagedIn;The inverse relationship to IfcPersonAndOrganization relationships in which IfcPerson is engaged. +114;ThePerson;The person who is related to the organization. +115;TheOrganization;The organization to which the person is related. +116;Roles;" + +Roles played by the person within the context of an organization. These may differ from the roles in ThePerson.Roles which may be asserted without organizational context. + + " +118;Name;The word or group of words by which the relationship is referred to. +119;Description;Text that relates the nature of the relationship. +120;RelatingOrganization;Organization which is the relating part of the relationship between organizations. +121;RelatedOrganizations;The other, possibly dependent, organizations which are the related parts of the relationship between organizations. +124;Identifier;A computer interpretable identifier by which the approval is known. +125;Name;A human readable name given to an approval. +126;Description;"A general textual description of a design, work task, plan, etc. that is being approved for. " +127;TimeOfApproval;" +Date and time when the result of the approval process is produced. +
+

+ +IFC2x4 CHANGE  Attribute data type changed to IfcDateTime using ISO 8601 representation, renamed from ApprovalDateTime and made OPTIONAL. + +

+
+
" +128;Status;The result or current status of the approval, e.g. Requested, Processed, Approved, Not Approved. +129;Level;Level of the approval e.g. Draft v.s. Completed design. +130;Qualifier;Textual description of special constraints or conditions for the approval. +131;RequestingApproval;" +The actor that is acting in the role specified at IfcOrganization or individually at IfcPerson and requesting an approval. +
+

+ +IFC2x4 CHANGE  New attribute for approval request replacing IfcApprovalActorRelationship (being deleted). + +

+
+
" +132;GivingApproval;" +The actor that is acting in the role specified at IfcOrganization or individually at IfcPerson and giving an approval. +
+

+ +IFC2x4 CHANGE  New attribute for approval provision replacing IfcApprovalActorRelationship (being deleted). + +

+
+
" +133;HasExternalReferences;" +Reference to external references, e.g. library, classification, or document information, that are associated to the Approval. +
+ + +IFC2x4 CHANGE New inverse attribute. + + +
+
" +134;ApprovedObjects;Reference to the IfcRelAssociatesApproval instances associating this approval to objects (subtypes of IfcRoot +135;ApprovedResources;The set of relationships by which resource objects that are are approved by this approval are known. +136;IsRelatedWith;The set of relationships by which this approval is related to others. +137;Relates;The set of relationships by which other approvals are related to this one. +140;RelatingApproval;The approval that other approval is related to. +141;RelatedApprovals;"The approvals that are related to another (relating) approval.
IFC2x Edition 4 CHANGE The cardinality of this attribute has been changed to SET.
" +143;RelatedResourceObjects;" +Resource objects that are approved. +" +144;RelatingApproval;The approval for the resource objects selected. +147;LifeCyclePhase;Describes the applicable building life-cycle phase. Typical values should be DESIGNDEVELOPMENT, SCHEMATICDEVELOPMENT, CONSTRUCTIONDOCUMENT, CONSTRUCTION, ASBUILT, COMMISSIONING, OPERATION, etc. +148;PredefinedType;" +Predefined generic type for a performace history that is specified in an enumeration. +
+ IFC2x4 CHANGE The attribute has been added at the end of the entity definition. + +
+
" +153;RelatingApproval;Reference to approval that is being applied using this relationship. +155;Intent;The intent of the constraint usage with regard to its related IfcConstraint and IfcObjects, IfcPropertyDefinitions or IfcRelationships. Typical values can be e.g. RATIONALE or EXPECTED PERFORMANCE. +156;RelatingConstraint;Reference to constraint that is being applied using this relationship. +158;ApplicableDates;"Defines an ordered list of the dates for which the time-series data are applicable. For example, the definition of all public holiday dates for a given year (as a list of IfcDate) allows the formulation of a ""holiday"" occupancy schedule from overall occupancy data. + +
IFC2x2 Addendum 1 CHANGE: The attribute has been changed to be optional
+ +
Note IFC2x Edition 4 CHANGE: New underlying type IfcDate using ISO 8601 representation.
+ +
" +159;TimeSeriesScheduleType;Defines the type of schedule, such as DAILY, WEEKLY, MONTHLY or ANNUALLY. +160;TimeSeries;The time series is used to represent the values at discrete points in time that define the schedule. For example, a 24-hour occupancy schedule would be a regular time series with a start time at midnight, end time at (the following) midnight, and with 24 values indicating the occupancy load for each hour of the 24-hour period. +163;PredefinedType;Subtype of pile. +175;PredefinedType;Subtype of footing. +186;PredefinedType;Indicates the kind of surface feature. +195;PredefinedType;Qualifies the feature regarding its shape and configuration relative to the voided element. +207;PredefinedType;" + +The generic type of the footing. + +
IFC 2x4 change:  Attribute made optional. Type information can be provided by IfcRelDefinesByType and IfcFootingType.
+ +
" +211;PredefinedType;" + +The predefined generic type of the pile according to function. + +
IFC 2x4 change:  Attribute made optional. Type information can be provided by IfcRelDefinesByType and IfcPileType.
+ +
" +212;ConstructionType;" + +General designator for how the pile is constructed. + +
IFC 2x4 change:  Material profile association capability by means of IfcRelAssociatesMaterial has been added. The attribute ConstructionType should not be used whenever its information can be provided by a material profile set, either associated with the IfcPile object or, if present, with a corresponding instance of IfcPileType.
+ +
" +225;PredefinedType;Subtype of reinforcement element. +226;BendingShapeCode;" +Shape code per a standard like ACI 315, ISO 3766, or a similar standard. It is presumed that a single standard for defining the bar bending is used throughout the project and that this standard is referenced from the IfcProject object through the IfcDocumentReference mechanism. +" +227;BendingParameters;Bending shape parameters. Their meaning is defined by the bending shape code and the respective standard. +233;PredefinedType;Subtype of reinforcement element. +234;Role;The role, purpose or usage of the reinforcement, i.e. the kind of loads and stresses it is intended to carry. Standard values are 'Main', 'Shear', 'Ligature', 'Stud', 'Punching', 'Edge', 'Ring'. +238;PredefinedType;The predefined type is always BAR. +250;PredefinedType;The predefined type is always MESH. +253;NominalDiameter;The nominal diameter defining the cross-section size of the reinforcing bar. +254;CrossSectionArea;The effective cross-section area of the reinforcing bar. +255;BarLength;"The total length of the reinforcing bar. The total length of bended bars are calculated according to local standards with corrections for the bends. " +256;BarSurface;"Indicator for whether the bar surface is plain or textured. " +257;PredefinedType;The predefined type is always BAR. +259;MeshLength;The overall length of the mesh measured in its longitudinal direction. +260;MeshWidth;The overall width of the mesh measured in its transversal direction. +261;LongitudinalBarNominalDiameter;The nominal diameter denoting the cross-section size of the longitudinal bars. +262;TransverseBarNominalDiameter;The nominal diameter denoting the cross-section size of the transverse bars. +263;LongitudinalBarCrossSectionArea;The effective cross-section area of the longitudinal bars of the mesh. +264;TransverseBarCrossSectionArea;The effective cross-section area of the transverse bars of the mesh. +265;LongitudinalBarSpacing;"The spacing between the longitudinal bars. Note: an even distribution of bars is presumed; other cases are handled by classification or property sets." +266;TransverseBarSpacing;"The spacing between the transverse bars. Note: an even distribution of bars is presumed; other cases are handled by classification or property sets." +267;PredefinedType;The predefined type is always MESH. +272;DefinitionType;Descriptive type name applied to reinforcement definition properties. +273;ReinforcementSectionDefinitions;The list of section reinforcement properties attached to the reinforcement definition properties. +285;Name;" +The string by which the pre defined item is identified. Allowable values for the string are declared at the level of subtypes. +" +293;FontFamily;" +The value is a prioritized list of font family names and/or generic family names. The first list entry has the highest priority, if this font fails, the next list item shall be used. The last list item should (if possible) be a generic family.
+
" +294;FontStyle;" +The font style property selects between normal (sometimes referred to as ""roman"" or ""upright""), italic and oblique faces within a font family.
+
" +295;FontVariant;" +The font variant property selects between normal and small-caps. +
NOTE  It has been introduced for later compliance to full CSS1 support.
+
" +296;FontWeight;" +The font weight property selects the weight of the font. +
NOTE  Values other then 'normal' and 'bold' have been introduced for later compliance to full CSS1 support.
+
" +297;FontSize;" +The font size provides the size or height of the text font. +
NOTE  The following values are allowed, <IfcLengthMeasure, with positive values, the length unit is globally defined at IfcUnitAssignment.
+
" +309;Name;" +Optional name given to a particular colour specification in addition to the colour components (like the RGB values). +
+ NOTE  Examples are the names of a industry colour classification, such as RAL.
+IFC2x Edition 3 CHANGE  Attribute added. +
+
" +311;Red;" +The intensity of the red colour component. +
+NOTE  The colour component value is given within the range of 0..1, and not within the range of 0..255 as otherwise usual. +
+
" +312;Green;" +The intensity of the green colour component. +
+NOTE  The colour component value is given within the range of 0..1, and not within the range of 0..255 as otherwise usual. +
+
" +313;Blue;" +The intensity of the blue colour component. +
+NOTE  The colour component value is given within the range of 0..1, and not within the range of 0..255 as otherwise usual. +
+
" +316;SizeInX;" +The extent in the direction of the x-axis. +" +317;SizeInY;" +The extent in the direction of the y-axis. +" +319;Placement;" +The IfcAxis2Placement positions a local coordinate system for the definition of the rectangle. The origin of this local coordinate system serves as the lower left corner of the rectangular box. +
NOTE  In case of a 3D placement by IfcAxisPlacement3D the IfcPlanarBox is defined within the xy plane of the definition coordinate system.
+
" +325;DependingProperty;" +The property on which the relationship depends. +" +326;DependantProperty;" +The dependant property. +" +327;Expression;Expression that further describes the nature of the dependency relation. +332;Name;" +Name for this property. This label is the significant name string that defines the semantic meaning for the property. +" +333;Description;" +Informative text to explain the property. +" +334;PartOfPset;" +Reference to the IfcPropertySet by which the IfcProperty is referenced. +
+ + +IFC2x4 CHANGE  New inverse attribute to navigate from IfcProperty to IfcPropertySet with upward compatibility for file based exchange. + + +
+
" +335;HasExternalReferences;" +Reference to an external reference, e.g. library, classification, or document information, that is associated to the property. +
+ + +IFC2x4 CHANGE New inverse attribute. + + +
+
" +336;PropertyForDependance;The property on whose value that of another property depends. +337;PropertyDependsOn;The relating property on which the value of the property depends. +338;PartOfComplex;" +Reference to the IfcComplexProperty in which the IfcProperty is contained. +
+IFC2x4 CHANGE  The cardinality has changed to 0..n to allow reuse of instances of IfcProperty in several IfcComplexProperty with upward compatibility for file based exchange. +
+
" +340;UsageName;"Usage description of the IfcComplexProperty within the property set which references the IfcComplexProperty. +
NOTE: Consider a complex property for glazing properties. The Name attribute of the IfcComplexProperty could be Pset_GlazingProperties, and the UsageName attribute could be OuterGlazingPane.
+
" +341;HasProperties;" +Set of properties that can be used within this complex property (may include other complex properties). +" +352;NominalValue;" +Value and measure type of this property. +
+NOTE  By virtue of the defined data type, that is selected from the SELECT IfcValue, the appropriate unit can be found within the IfcUnitAssignment, defined for the project if no value for the unit attribute is given.
+ +IFC2x3 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +353;Unit;Unit for the nominal value, if not given, the default value for the measure type (given by the TYPE of nominal value) is used as defined by the global unit assignment at IfcProject. +355;EnumerationValues;" +Enumeration values, which shall be listed in the referenced IfcPropertyEnumeration, if such a reference is provided. +
+ +IFC2x4 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +356;EnumerationReference;Enumeration from which a enumeration value has been selected. The referenced enumeration also establishes the unit of the enumeration value. +359;Name;Name of this enumeration. +360;EnumerationValues;List of values that form the enumeration. +361;Unit;Unit for the enumerator values, if not given, the default value for the measure type (given by the TYPE of nominal value) is used as defined by the global unit assignment at IfcProject. +366;UpperBoundValue;" +Upper bound value for the interval defining the property value. If the value is not given, it indicates an open bound (all values to be greater than or equal to LowerBoundValue). +" +367;LowerBoundValue;" +Lower bound value for the interval defining the property value. If the value is not given, it indicates an open bound (all values to be lower than or equal to UpperBoundValue). +" +368;Unit;" +Unit for the upper and lower bound values, if not given, the default value for the measure type is used as defined by the global unit assignment at IfcProject.UnitInContext. The applicable unit is then selected by the underlying TYPE of the UpperBoundValue, LowerBoundValue, and SetPointValue) +" +369;SetPointValue;" +Set point value as typically used for operational value setting. +
+ +IFC2x4 CHANGE  The attribute has been added at the end of the attribute list. + +
+
" +374;DefiningValues;" +List of defining values, which determine the defined values. This list shall have unique values only. +
+ +IFC2x4 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +375;DefinedValues;" +Defined values which are applicable for the scope as defined by the defining values. +
+ +IFC2x4 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +376;Expression;Expression for the derivation of defined values from the defining values, the expression is given for information only, i.e. no automatic processing can be expected from the expression. +377;DefiningUnit;Unit for the defining values, if not given, the default value for the measure type (given by the TYPE of the defining values) is used as defined by the global unit assignment at IfcProject. +378;DefinedUnit;Unit for the defined values, if not given, the default value for the measure type (given by the TYPE of the defined values) is used as defined by the global unit assignment at IfcProject. +379;CurveInterpolation;" +Interpolation of the curve between two defining and defined values that are provided. if not provided a linear interpolation is assumed. +
+ +IFC2x4 CHANGE  The attribute has been added at the end of the attribute list. + +
+
" +389;UsageName;Description of the use of the referenced value within the property. +390;PropertyReference;" +Reference to another property entity through one of the select types in the IfcObjectReferenceSelect. +
+ +IFC2x4 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +401;ListValues;" +List of property values. +
+ +IFC2x4 CHANGE  The attribute has been made optional with upward compatibility for file based exchange. + +
+
" +402;Unit;Unit for the list values, if not given, the default value for the measure type (given by the TYPE of nominal value) is used as defined by the global unit assignment at IfcProject. +409;Name;Name of the element quantity or measure. The name attribute has to be made recognizable by further agreements. +410;Description;Further explanation that might be given to the quantity. +411;HasExternalReferences;" +Reference to an external reference, e.g. library, classification, or document information, that is associated to the quantity. +
+ + +IFC2x4 CHANGE New inverse attribute. + + +
+
" +412;PartOfComplex;Reference to a physical complex quantity in which the physical quantity may be contained. +420;Unit;Optional assignment of a unit. If no unit is given, then the global unit assignment, as established at the IfcProject, applies to the quantity measures. +422;LengthValue;Length measure value of this quantity. +423;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +427;AreaValue;Area measure value of this quantity. +428;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +432;VolumeValue;Volume measure value of this quantity. +433;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +437;CountValue;Count measure value of this quantity. +438;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +441;WeightValue;Mass measure value of this quantity. +442;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +446;TimeValue;Time measure value of this quantity. +447;Formula;" +A formula by which the quantity has been calculated. It can be assigned in addition to the actual value of the quantity. Formulas could be mathematic calculations (like width x height), database links, or a combination. The formula is for informational purposes only. +
+IFC2x4 CHANGE Attribute added to the end of the attribute list. + +
+
" +451;HasQuantities;Set of physical quantities that are grouped by this complex physical quantity according to a given discrimination. +452;Discrimination;Identification of the discrimination by which this physical complex property is distinguished. Examples of discriminations are 'layer', 'steel bar diameter', etc. +453;Quality;Additional indication of a quality of the quantities that are grouped under this physical complex quantity. +454;Usage;Additional indication of a usage type of the quantities that are grouped under this physical complex quantity. +463;ServicesBuildings;"Reference to the building spatial structure via the objectified relationship IfcRelServicesBuildings, which is serviced by the system. + " +465;LongName;" +Long name for a zone, used for informal purposes. It should be used, if available, in conjunction with the inherited Name attribute. +
+ NOTE In many scenarios the Name attribute refers to the short name or number of a zone, and the LongName refers to the full name. + +
+ + IFC2x4 CHANGE The attribute has been added at the end of the entity definition. + +
+
" +470;ConnectionGeometry;" +The geometric shape representation of the connection geometry that is provided in the object coordinate system of the RelatingElement (mandatory) and in the object coordinate system of the RelatedElement (optionally). +" +471;RelatingElement;" +Reference to a subtype of IfcElement that is connected by the connection relationship in the role of RelatingElement. + " +472;RelatedElement;" +Reference to a subtype of IfcElement that is connected by the connection relationship in the role of RelatedElement. +" +477;RelatingSpace;Reference to one spaces that is delimited by this boundary. +478;RelatedBuildingElement;" +Reference to Building Element, that defines the Space Boundaries. +
+ + +IFC2x PLATFORM CHANGE  The data type has been changed from IfcBuildingElement to IfcElement with upward compatibility for file based exchange. + + + + +IFC2x4 CHANGE  The attribute has been changed to be mandatory. + + +
+
" +479;ConnectionGeometry;" +Physical representation of the space boundary. Provided as a curve or surface given within the LCS of the space. +
+IFC2x PLATFORM CHANGE  The data type has been changed from IfcConnectionSurfaceGeometry to IfcConnectionGeometry with upward compatibility for file based exchange. +
+
" +480;PhysicalOrVirtualBoundary;"Defines, whether the Space Boundary is physical (Physical) or virtual (Virtual). " +481;InternalOrExternalBoundary;"Defines, whether the Space Boundary is internal (Internal), or external, i.e. adjacent to open space (that can be an partially enclosed space, such as terrace (External). " +484;ParentBoundary;" +Reference to the host, or parent, space boundary within which this inner boundary is defined. +" +485;InnerBoundaries;" +Reference to the inner boundaries of the space boundary. Inner boundaries are defined by the space boundaries of openings, doors and windows. +" +487;ParentBoundary;" +Reference to the host, or parent, space boundary within which this inner boundary is defined. +" +488;CorrespondingBoundary;" +Reference to the other space boundary of the pair of two space boundaries on either side of a space separating thermal boundary element. +" +489;Corresponds;" +Reference to the other space boundary of the pair of two space boundaries on either side of a space separating thermal boundary element. +" +490;InnerBoundaries;" +Reference to the inner boundaries of the space boundary. Inner boundaries are defined by the space boundaries of openings, doors and windows. +" +495;PredefinedType;" +Predefined generic types for a space that are specified in an enumeration. There might be property sets defined specifically for each predefined type. + +
+ +Previous use, prior to IFC2x4, had been to indicates whether the IfcSpace is an interior space by value INTERNAL, or an exterior space by value EXTERNAL. This use is now deprecated, the property 'IsExternal' at 'Pset_SpaceCommon' should be used instead. + +
+ +
+ + +IFC2x4 CHANGE  The attribute has been renamed from ExteriorOrInteriorSpace with upward compatibility for file based exchange. + + +
+
" +496;ElevationWithFlooring;"Level of flooring of this space; the average shall be taken, if the space ground surface is sloping or if there are level differences within this space." +497;HasCoverings;" +Reference to IfcCovering by virtue of the objectified relationship IfcRelCoversSpaces. It defines the concept of a space having coverings assigned. Those coverings may represent different flooring, or tiling areas. + +
+ +NOTE  Coverings are often managed by the space, and not by the building element, which they cover.
+ +IFC2x Edition3 CHANGE  New inverse relationship. Upward compatibility for file based exchange is guaranteed. + +
+ +
" +498;BoundedBy;" +Reference to a set of IfcRelSpaceBoundary's that defines the physical or virtual delimitation of that space against physical or virtual boundaries. +" +506;CompositionType;" +Denotes, whether the predefined spatial structure element represents itself, or an aggregate (complex) or a part (part). The interpretation is given separately for each subtype of spatial structure element. If no CompositionType is asserted, the dafault value 'ELEMENT' applies. +
+

+ + IFC2x4 CHANGE  + Attribute made optional. +

+
+
" +507;ContainsElements;" +Set of spatial containment relationships, that holds those elements, which are contained within this element of the project spatial structure. +
+NOTE  The spatial containment relationship, established by IfcRelContainedInSpatialStructure, is required to be an hierarchical relationship, i.e. each element can only be assigned to 0 or 1 spatial structure element. +
+
" +513;LongName;" +Long name for a spatial structure element, used for informal purposes. It should be used, if available, in conjunction with the inherited Name attribute. +
+ NOTE In many scenarios the Name attribute refers to the short name or number of a spacial element, and the LongName refers to the full name. + +
+
" +514;ServicedBySystems;" +Set of relationships to systems, that provides a certain service to the spatial element for which it is defined. The relationship is handled by the objectified relationship IfcRelServicesBuildings. +
+ +IFC2x Edition 4 CHANGE  The inverse attribute has been promoted to the new supertype IfcSpatialElement with upward compatibility for file based exchange. + +
+
" +515;ReferencesElements;" +Set of spatial reference relationships, that holds those elements, which are referenced, but not contained, within this element of the project spatial structure. +
+ +NOTE  The spatial reference relationship, established by IfcRelReferencedInSpatialStructure, is not required to be an hierarchical relationship, i.e. each element can be assigned to 0, 1 or many spatial structure elements. +

+EXAMPLE  A curtain wall maybe contained in the ground floor, but maybe referenced in all floors, it reaches. +

+ +IFC2x Edition 3 CHANGE  The inverse attribute has been added with upward compatibility for file based exchange. +

+ +IFC2x Edition 4 CHANGE  The inverse attribute has been promoted to the new supertype IfcSpatialElement with upward compatibility for file based exchange. +
+
+
" +525;Tag;The tag (or label) identifier at the particular instance of a product, e.g. the serial number, or the position number. It is the identifier at the occurrence level. +526;FillsVoids;" +Reference to the IfcRelFillsElement Relationship that puts the element as a filling into the opening created within another element. + + " +527;ConnectedTo;"Reference to the element connection relationship. The relationship then refers to the other element to which this element is connected to. " +528;IsInterferedByElements;" +Reference to the interference relationship to indicate the element that is interfered. The relationship, if provided, indicates that this element has an interference with one or many other elements. +
+NOTE There is no indication of precedence between IsInterferedByElements and InterferesElements. +
+IFC2x4 CHANGE New inverse relationship. + +
+
" +529;InterferesElements;" +Reference to the interference relationship to indicate the element that interferes. The relationship, if provided, indicates that this element has an interference with one or many other elements. +
+NOTE There is no indication of precedence between IsInterferedByElements and InterferesElements. +
+IFC2x4 CHANGE New inverse relationship. + +
+
" +530;HasProjections;" +Projection relationship that adds a feature (using a Boolean union) to the IfcBuildingElement. +" +531;ReferencedInStructures;" +Reference relationship to the spatial structure element, to which the element is additionally associated. This relationship may not be hierarchical, an element may be referenced by zero, one or many spatial structure elements. +
+IFC2x Edition 3 CHANGE  The inverse attribute has been added with upward compatibility for file based exchange. +
+
" +532;HasOpenings;" +Reference to the IfcRelVoidsElement relationship that creates an opening in an element. An element can incorporate zero-to-many openings. For each opening, that voids the element, a new relationship IfcRelVoidsElement is generated. + " +533;IsConnectionRealization;" +Reference to the connection relationship with realizing element. The relationship, if provided, assigns this element as the realizing element to the connection, which provides the physical manifestation of the connection relationship. + " +534;ProvidesBoundaries;" +Reference to space boundaries by virtue of the objectified relationship IfcRelSpaceBoundary. It defines the concept of an element bounding spaces. + " +535;ConnectedFrom;"Reference to the element connection relationship. The relationship then refers to the other element that is connected to this element. " +536;ContainedInStructure;" +Containment relationship to the spatial structure element, to which the element is primarily associated. This containment relationship has to be hierachical, i.e. an element may only be assigned directly to zero or one spatial structure. +" +538;HasCoverings;" +Reference to IfcCovering by virtue of the objectified relationship IfcRelCoversBldgElement. It defines the concept of a building element having coverings associated. +" +544;HasPorts;" +Reference to the element to port connection relationship. The relationship then refers to the port which is contained in this element. + +
+ + +IFC2x4 CHANGE  The inverse attribute has been demoted from IfcElement. + + +
+ +
" +548;HasPorts;" +Reference to the element type to port connection relationship. The relationship then refers to the port which is contained in this element type. + +
+ + +IFC2x4 CHANGE  New inverse attribute. + + +
+ +
" +556;ElementType;" +The type denotes a particular type that indicates the object further. The use has to be established at the level of instantiable subtypes. In particular it holds the user defined type, if the enumeration of the attribute 'PredefinedType' is set to USERDEFINED. +" +560;ElementType;" +The type denotes a particular type that indicates the object further. The use has to be established at the level of instantiable subtypes. In particular it holds the user defined type, if the enumeration of the attribute 'PredefinedType' is set to USERDEFINED. +" +564;PredefinedType;" +Predefined types to define the particular type of space. There may be property set definitions available for each predefined type. +" +575;PredefinedType;" +Predefined types to define the particular type of the spatial zone. There may be property set definitions available for each predefined type. +" +591;PredefinedType;" +Predefined types to define the particular type of the transport element. There may be property set definitions available for each predefined type. +" +602;PredefinedType;" +Predefined types to define the particular type of the geographic element. There may be property set definitions available for each predefined type. +" +608;PredefinedType;" +Predefined types to define the particular type of the transport element. There may be property set definitions available for each predefined type. +" +623;RelatingPort;Reference to an Port that is connected by the objectified relationship. +624;RelatedElement;" +Reference to an IfcElement, or IfcElementType that has ports assigned. +
+IFC2x4 CHANGE Data type extended to IfcObjectDefinition to enable elements and element types for the port relationship. + +
+
" +627;ContainedIn;"Reference to the element to port connection relationship. The relationship then refers to the element in which this port is contained. " +628;ConnectedFrom;Reference to a port that is connected by the objectified relationship. +629;ConnectedTo;Reference to the port connection relationship. The relationship then refers to the other port to which this port is connected. +631;RelatingPort;Reference to the first port that is connected by the objectified relationship. +632;RelatedPort;Reference to the second port that is connected by the objectified relationship. +633;RealizingElement;Defines the element that realizes a port connection relationship. +639;PredefinedType;" +Predefined generic types for a transportation element that are specified in an enumeration. There might be property sets defined specifically for each predefined type. +
+ + +IFC2x4 CHANGE  The attribute has been changed to be optional. + + +
+
" +640;CapacityByWeight;Capacity of the transport element measured by weight. +641;CapacityByNumber;Capacity of the transportation element measured in numbers of person. +649;ProjectsElements;" +Reference to the IfcRelProjectsElement relationship that uses this IfcFeatureElementAddition to create a volume addition at an element. The IfcFeatureElementAddition can only be used to create a single addition at a single element using Boolean addition operation. +" +651;PredefinedType;" +Predefined generic type for a projection element that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
+ IFC2x4 CHANGE The attribute has been added at the end of the entity definition. +
+
" +656;RelatingElement;" +Element at which a projection is created by the associated IfcProjectionElement. +" +657;RelatedFeatureElement;" +Reference to the IfcFeatureElementAddition that defines an addition to the volume of the element, by using a Boolean addition operation. An example is a projection at the associated element. +" +659;RelatingElement;" +Reference to building element in which a void is created by associated opening feature subtraction element. +
+

+ +IFC2x PLATFORM CHANGE  The data type has been changed from IfcBuildingElement to IfcElement with upward compatibility for file based exchange.
+ +IFC2x4 CHANGE  +Renamed to RelatingElement. +

+
+
" +660;RelatedOpening;" +Reference to the opening feature subtraction element which defines a void in the associated opening element. +
+

+ +IFC2x PLATFORM CHANGE  The data type has been changed from IfcOpeningElement to IfcFeatureElementSubtraction with upward compatibility for file based exchange.
+ +IFC2x4 CHANGE  +Renamed to RelatedOpening. +

+
+ + +
" +663;VoidsElements;"Reference to the Voids Relationship that uses this Opening Element to create a void within an Element. The Opening Element can only be used to create a single void within a single Element. " +668;PredefinedType;" +Predefined generic type for an opening that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
+ IFC2x4 CHANGE The attribute has been added at the end of the entity definition. +
+
" +669;HasFillings;"Reference to the Filling Relationship that is used to assign Elements as Fillings for this Opening Element. The Opening Element can be filled with zero-to-many Elements. " +677;RelatingOpeningElement;"Opening Element being filled by virtue of this relationship. " +678;RelatedBuildingElement;" +Reference to building element that occupies fully or partially the associated opening. +
+IFC2x PLATFORM CHANGE: The data type has been changed from IfcBuildingElement to IfcElement with upward compatibility for file based exchange. +
+
" +680;AssemblyPlace;A designation of where the assembly is intended to take place defined by an Enum. +681;PredefinedType;" +Predefined generic types for a element assembly that are specified in an enumeration. There might be property sets defined specifically for each predefined type. +
+ + +IFC2x4 CHANGE  The attribute has been changed to be optional. + + +
+
" +690;PredefinedType;" +Predefined generic types for a geographic element that are specified in an enumeration. There might be property sets defined specifically for each predefined type. +" +694;RelatingElement;" +Reference to a subtype of IfcElement that is the RelatingElement in the interference relationship. Depending on the value of ImpliedOrder the RelatingElement may carry the notion to be the element from which the interference geometry should be subtracted. +" +695;RelatedElement;" +Reference to a subtype of IfcElement that is the RelatedElement in the interference relationship. Depending on the value of ImpliedOrder the RelatedElement may carry the notion to be the element from which the interference geometry should not be subtracted. +" +696;InterferenceGeometry;" +The geometric shape representation of the interference geometry that is provided in the object coordinate system of the RelatingElement (mandatory) and in the object coordinate system of the RelatedElement (optionally). +" +697;InterferenceType;" +Optional identifier that describes the nature of the interference. Examples could include 'Clash', 'ProvisionForVoid', etc. +" +698;ImpliedOrder;" +Logical value indicating whether the interference geometry should be subtracted from the RelatingElement (if TRUE), or whether it should be either subtracted from the RelatingElement or the RelatedElement (if FALSE), or whether no indication can be provided (if UNKNOWN). +" +701;RelatedElements;" +Set of products, which are referenced within this level of the spatial structure hierarchy. +
NOTE  Referenced elements are contained elsewhere within the spatial structure, they are referenced additionally by this spatial structure element, e.g., because they span several stories. +
+
" +702;RelatingStructure;" +Spatial structure element, within which the element is referenced. Any element can be contained within zero, one or many elements of the project spatial and zoning structure. +
+ +IFC2x Edition 4 CHANGE  The attribute relatingStructure as been promoted to the new supertype IfcSpatialElement with upward compatibility for file based exchange. + +
+
" +705;RealizingElements;Defines the elements that realize a connection relationship. +706;ConnectionType;The type of the connection given for informal purposes, it may include labels, like 'joint', 'rigid joint', 'flexible joint', etc. +708;RelatedElements;" +Set of elements products, which are contained within this level of the spatial structure hierarchy. +
+IFC2x PLATFORM CHANGE  The data type has been changed from IfcElement to IfcProduct with upward compatibility +
+
" +709;RelatingStructure;" +Spatial structure element, within which the element is contained. Any element can only be contained within one element of the project spatial structure. +" +712;UAxes;List of grid axes defining the first row of grid lines. +713;VAxes;List of grid axes defining the second row of grid lines. +714;WAxes;List of grid axes defining the third row of grid lines. It may be given in the case of a triangular grid. +715;ContainedInStructure;" +Relationship to a spatial structure element, to which the grid is primarily associated. +
IFC2x PLATFORM CHANGE  The inverse relationship has been added to IfcGrid with upward compatibility +
+
" +718;ContainedInStructure;Relationship to a spatial structure element, to which the associate is primarily associated. +720;PredefinedType;" +Predefined types to define the particular type of the spatial zone. There may be property set definitions available for each predefined type. +" +726;PredefinedType;" +Predefined generic types for an external spatial element that are specified in an enumeration. There might be property sets defined specifically for each predefined type. +" +727;BoundedBy;" +Reference to a set of IfcRelSpaceBoundary's that defines the physical or virtual delimitation of that external spacial element against physical or virtual boundaries. +" +736;RelatingSystem;"System that services the Buildings. " +737;RelatedBuildings;" +Spatial structure elements (including site, building, storeys) that are serviced by the system. +
+ +IFC2x PLATFORM CHANGE  The data type has been changed from IfcBuilding to IfcSpatialStructureElement with upward compatibility for file based exchange. +

+IFC2x Edition 4 CHANGE  The data type has been changed from IfcSpatialStructureElement to IfcSpatialElement with upward compatibility for file based exchange. +
+
+
" +739;ElevationOfRefHeight;Elevation above sea level of the reference height used for all storey elevation measures, equals to height 0.0. It is usually the ground floor level. +740;ElevationOfTerrain;Elevation above the minimal terrain level around the foot print of the building, given in elevation above sea level. +741;BuildingAddress;Address given to the building for postal purposes. +743;Elevation;Elevation of the base of this storey, relative to the 0,00 internal reference height of the building. The 0.00 level is given by the absolute above sea level height by the ElevationOfRefHeight attribute given at IfcBuilding. +745;RefLatitude;" +World Latitude at reference point (most likely defined in legal description). Defined as integer values for degrees, minutes, seconds, and, optionally, millionths of seconds with respect to the world geodetic system WGS84. +
Latitudes are measured relative to the geodetic equator, north of the equator by positive values - from 0 till +90, south of the equator by negative values - from 0 till -90.
+
" +746;RefLongitude;" +World Longitude at reference point (most likely defined in legal description). Defined as integer values for degrees, minutes, seconds, and, optionally, millionths of seconds with respect to the world geodetic system WGS84. +
Longitudes are measured relative to the geodetic zero meridian, nominally the same as the Greenwich prime meridian: longitudes west of the zero meridian have negative values - from 0 till -180, longitudes east of the zero meridian have positive values - from 0 till -180.
+Example: Chicago Harbor Light has according to WGS84 a longitude -87.35.40 (or 87.35.40W) and a latitude 41.53.30 (or 41.53.30N). +
+
" +747;RefElevation;"Datum elevation relative to sea level. " +748;LandTitleNumber;The land title number (designation of the site within a regional system). +749;SiteAddress;Address given to the site for postal purposes. +766;MethodOfMeasurement;"Name of the method of measurement used to calculate the element quantity. The method of measurement attribute has to be made recognizable by further agreements. + +
IFC2x2 Addendum 1 change: The attribute has been changed to be optional
+
" +767;Quantities;The individual quantities for the element, can be a set of length, area, volume, weight or count based quantities. +771;RelatingMaterial;" +Material definition assigned to the elements or element types. +" +778;ObjectPlacement;Placement of the product in space, the placement can either be absolute (relative to the world coordinate system), relative (relative to the object placement of another product), or constraint (e.g. relative to grid axes). It is determined by the various subtypes of IfcObjectPlacement, which includes the axis placement information to determine the transformation for the object coordinate system. +779;Representation;Reference to the representations of the product, being either a representation (IfcProductRepresentation) or as a special case a shape representations (IfcProductDefinitionShape). The product definition shape provides for multiple geometric representations of the shape property of the object within the same object coordinate system, defined by the object placement. +780;ReferencedBy;" +Reference to the IfcRelAssignsToProduct relationship, by which other products, processes, controls, resources or actors (as subtypes of IfcObjectDefinition) can be related to this product. +" +789;ObjectType;" +The type denotes a particular type that indicates the object further. The use has to be established at the level of instantiable subtypes. In particular it holds the user defined type, if the enumeration of the attribute PredefinedType is set to USERDEFINED. +
+
" +790;IsDeclaredBy;" +Link to the relationship object pointing to the declaring object that provides the object definitions for this object occurrence. The declaring object has to be part of an object type decomposition. The associated IfcObject, or its subtypes, contains the specific information (as part of a type, or style, definition), that is common to all reflected instances of the declaring IfcObject, or its subtypes. +
+ +IFC2x4 CHANGE  New inverse relationship, change made with upward compatibility for file based exchange. + +
+
" +791;Declares;" +Link to the relationship object pointing to the reflected object(s) that receives the object definitions. The reflected object has to be part of an object occurrence decomposition. The associated IfcObject, or its subtypes, provides the specific information (as part of a type, or style, definition), that is common to all reflected instances of the declaring IfcObject, or its subtypes. +
+ +IFC2x4 CHANGE  New inverse relationship, change made with upward compatibility for file based exchange. + +
+
" +792;IsTypedBy;" +Set of relationships to the object type that provides the type definitions for this object occurrence. The then associated IfcTypeObject, or its subtypes, contains the specific information (or type, or style), that is common to all instances of IfcObject, or its subtypes, referring to the same type. +
+IFC2x4 CHANGE  New inverse relationship, the link to IfcRelDefinesByType had previously be included in the inverse relationship IfcRelDefines. Change made with upward compatibility for file based exchange. +
+
" +793;IsDefinedBy;" +Set of relationships to property set definitions attached to this object. Those statically or dynamically defined properties contain alphanumeric information content that further defines the object. +
+IFC2x4 CHANGE  The data type has been changed from IfcRelDefines to IfcRelDefinesByProperties with upward compatibility for file based exchange. +
+
" +798;HasAssignments;Reference to the relationship objects, that assign (by an association relationship) other subtypes of IfcObject to this object instance. Examples are the association to products, processes, controls, resources or groups. +799;Nests;" +References to the decomposition relationship being a nesting. It determines that this object definition is a part within an ordered whole/part decomposition relationship. An object occurrence or type can only be part of a single decomposition (to allow hierarchical strutures only). + +

+IFC2x4 CHANGE  The inverse attribute datatype has been added and separated from Decomposes defined at IfcObjectDefinition. +

+ +
" +800;IsNestedBy;" +References to the decomposition relationship being a nesting. It determines that this object definition is the whole within an ordered whole/part decomposition relationship. An object or object type can be nested by several other objects (occurrences or types). + +

+IFC2x4 CHANGE  The inverse attribute datatype has been added and separated from IsDecomposedBy defined at IfcObjectDefinition. +

+ +
" +801;HasContext;" +References to the context providing context information such as project unit or representation context. It should only be asserted for the uppermost non-spatial object. + +

+IFC2x4 CHANGE  The inverse attribute datatype has been added. +

+ +
" +802;IsDecomposedBy;" +References to the decomposition relationship being an aggregation. It determines that this object definition is whole within an unordered whole/part decomposition relationship. An object definitions can be aggregated by several other objects (occurrences or parts). + +

+IFC2x4 CHANGE  The inverse attribute datatype has been changed from the supertype IfcRelDecomposes to subtype IfcRelAggregates. +

+ +
" +803;Decomposes;" +References to the decomposition relationship being an aggregation. It determines that this object definition is a part within an unordered whole/part decomposition relationship. An object definitions can only be part of a single decomposition (to allow hierarchical strutures only). + +

+IFC2x4 CHANGE  The inverse attribute datatype has been changed from the supertype IfcRelDecomposes to subtype IfcRelAggregates. +

+ +
" +804;HasAssociations;Reference to the relationship objects, that associates external references or other resource definitions to the object.. Examples are the association to library, documentation or classification. +809;GlobalId;"Assignment of a globally unique identifier within the entire software world. " +810;OwnerHistory;" +Assignment of the information about the current ownership of that object, including owning actor, application, local identification and information captured about the recent changes of the object, + +
+ +NOTE only the last modification in stored - either as addition, deletion or modification. +
+ +IFC2x4 CHANGE  The attribute has been changed to be OPTIONAL. +
+
" +811;Name;"Optional name for use by the participating software systems or users. For some subtypes of IfcRoot the insertion of the Name attribute may be required. This would be enforced by a where rule. " +812;Description;Optional description, provided for exchanging informative comments. +818;HasContext; +819;HasAssociations;Reference to the relationship IfcRelAssociates and thus to those externally defined concepts, like classifications, documents, or library information, which are associated to the property definition. +823;DefinesType;" +The type object to which the property set is assigned. The property set acts as a shared property set to all occurrences of the type object. +
+ + IFC2x4 CHANGE The cardinality has been changed from 0:1 to 0:? with upward compatibility for file based exchange. + + +
+
" +824;DefinesOccurrence;" +Reference to the relation to one or many object occurrences that are characterized by the property set definition. A single property set can be assigned to multiple object occurrences. +
+IFC2x4 CHANGE Inverse attribute renamed from PropertyDefinitionOf with upward compatibility for file-based exchange. +
+
" +826;HasProperties;"Contained set of properties. For property sets defined as part of the IFC Object model, the property objects within a property set are defined as part of the standard. If a property is not contained within the set of predefined properties, its value has not been set at this time. " +827;IsDefinedBy;" +Relation to the property set template, via the objectified relationship IfcRelDefinesByTemplate, that, if given, provides the definition template for the property set and its properties. +
+IFC2x4 CHANGE  New inverse relationship, change made with upward compatibility for file based exchange. +
+
" +831;RelatedPropertySets;" +One or many property sets defined by a single property set template. +" +832;RelatingTemplate;" +Property set template that provides the common definition of related property sets. +" +852;RelatedObjects;Related objects, which are assigned to a single object. The type of the single (or relating) object is defined in the subtypes of IfcRelAssigns. +853;RelatedObjectsType;" +Particular type of the assignment relationship. It can constrain the applicable object types, used within the role of RelatedObjects. +
IFC2x4 CHANGE  The attribute is deprecated and shall no longer be used. A NIL value should always be assigned. +
+
" +856;RelatingProcess;" +Reference to the process to which the objects are assigned to. +
+IFC2x4 CHANGE Datatype expanded to include IfcProcess and IfcTypeProcess. +
+
" +857;QuantityInProcess;" +Quantity of the object specific for the operation by this process. +" +863;Identification;" + An identifying designation given to a process or activity. + It is the identifier at the occurrence level. +
+ + IFC2x4 CHANGE Attribute promoted from subtypes. + +
+
" +864;LongDescription;" +An extended description or narrative that may be provided. +
+

+ +IFC2x4 CHANGE  New attribute. + +

+
+
" +865;IsPredecessorTo;" +Dependency between two activities, it refers to the subsequent activity for which this activity is the predecessor. The link between two activities can include a link type and a lag time. +" +866;IsSuccessorFrom;" +Dependency between two activities, it refers to the previous activity for which this activity is the successor. The link between two activities can include a link type and a lag time. +" +867;OperatesOn;" +Set of relationships to other objects, e.g. products, processes, controls, resources or actors, that are operated on by the process. +" +869;Identification;" +An identifying designation given to a process type. +" +870;LongDescription;" +An long description, or text, describing the activity in detail. +
+NOTE The inherited SELF\IfcRoot.Description attribute is used as the short description. +
+
" +871;ProcessType;" +The type denotes a particular type that indicates the process further. The use has to be established at the level of instantiable subtypes. In particular it holds the user defined type, if the enumeration of the attribute 'PredefinedType' is set to USERDEFINED. +" +872;OperatesOn;" +Set of relationships to other objects, e.g. products, processes, controls, resources or actors that are operated on by the process type. +
+ + IFC2x4 NOTE New inverse relationship. + +
+
" +877;ApplicableOccurrence;" +The attribute optionally defines the data type of the occurrence object, to which the assigned type object can relate. If not present, no instruction is given to which occurrence object the type object is applicable. The following conventions are used: +
    +
  • The IFC entity name of the applicable occurrence using the IFC naming convention, CamelCase with IFC prefix
  • +
  • It can be optionally followed by the predefined type after the separator ""/"" (forward slash), using Uupper case
  • +
  • If one type object is applicable to many occurrence objects, then those occurrence object names should be separate by comma "","" forming a comma separated string. +
+
+ EXAMPLE Refering to a furniture as applicable occurrence entity would be expressed as 'IfcFurnishingElement', refering to a brace as applicable entity would be expressed as 'IfcMember/BRACE', refering to a wall and wall standard case would be expressed as 'IfcWall, IfcWallStandardCase'. +
+
" +878;HasPropertySets;" +Set list of unique property sets, that are associated with the object type and are common to all object occurrences referring to this object type. +
+ IFC2x3 CHANGE  The attribute aggregate type has been changed from LIST to SET. +
+
" +879;Types;Reference to the relationship IfcRelDefinedByType and thus to those occurrence objects, which are defined by this type. +882;RepresentationMaps;List of unique representation maps. Each representation map describes a block definition of the shape of the product style. By providing more than one representation map, a multi-view block definition can be given. +883;Tag;The tag (or label) identifier at the particular type of a product, e.g. the article number (like the EAN). It is the identifier at the specific level. +884;ReferencedBy;" +Reference to the IfcRelAssignsToProduct relationship, by which other products, processes, controls, resources or actors (as subtypes of IfcObjectDefinition) can be related to this product type. +
+ + IFC2x4 NOTE New inverse relationship. + +
+
" +887;RelatingProduct;" +Reference to the product or product type to which the objects are assigned to. +
+IFC2x4 CHANGE Datatype expanded to include IfcProduct and IfcTypeProduct. +
+
" +893;Identification;" +An identifying designation given to a resource type. +" +894;LongDescription;" +An long description, or text, describing the resource in detail. +
+NOTE The inherited SELF\IfcRoot.Description attribute is used as the short description. +
+
" +895;ResourceType;" +The type denotes a particular type that indicates the resource further. The use has to be established at the level of instantiable subtypes. In particular it holds the user defined type, if the enumeration of the attribute 'PredefinedType' is set to USERDEFINED. +" +896;ResourceOf;" +Set of relationships to other objects, e.g. products, processes, controls, resources or actors to which this resource type is a resource. +
+ + + IFC2x4 NOTE New inverse relationship. + + +
+
" +898;RelatingResource;" +Reference to the resource to which the objects are assigned to. +
+ + + IFC2x4 CHANGE Datatype expanded to include IfcResource and IfcTypeResource. + + +
+
" +904;Identification;" + An identifying designation given to a resource. + It is the identifier at the occurrence level. +
+ + IFC2x4 CHANGE Attribute promoted from subtype IfcConstructionResource. + +
+
" +905;LongDescription;" +A detailed description of the resource (e.g. the skillset for a labor resource). +
+

+ +IFC2x4 NOTE:  The attribute LongDescription is added replacing the ResourceGroup attribute at subtype IfcConstructionResource. + +

+
+
" +906;ResourceOf;" +Set of relationships to other objects, e.g. products, processes, controls, resources or actors, for which this resource object is a resource. +" +908;RelatedObjects; +909;RelatingType;Reference to the type (or style) information for that object or set of objects. +911;RelatingControl;" +Reference to the IfcControl that applies a control upon objects. +" +914;Identification;" + An identifying designation given to a control + It is the identifier at the occurrence level. +
+ + IFC2x4 CHANGE Attribute unified by promoting from various subtypes of IfcControl. + +
+
" +915;Controls;"Reference to the relationship that associates the control to the object(s) being controlled. " +917;RelatingActor;"Reference to the information about the actor. It comprises the information about the person or organization and its addresses. " +918;ActingRole;"Role of the actor played within the context of the assignment to the object(s). " +921;TheActor;"Information about the actor. " +922;IsActingUpon;"Reference to the relationship that associates the actor to an object. " +925;RelatingGroup;" +Reference to group that contains all assigned group members. + " +928;Factor;" +Factor provided as a ratio measure that identifies the fraction or weighted factor that applies to the group assignment. +" +930;IsGroupedBy;" +Reference to the relationship IfcRelAssignsToGroup that assigns the one to many group members to the IfcGroup object. +
+IFC2x4 CHANGE  The cardinality has been changed from 1..1 to 0..? in order to allow the exchange of a group concept without having already group members assigned. It now also allows the use of many instances of IfcRelAssignsToGroup to assign the group members. The change has been done with upward compatibility for file based exchange. +
+
" +944;RelatingObject;" +The object definition, either an object type or an object occurrence, that represents the aggregation. It is the whole within the whole/part relationship. + +
+IFC2x4 CHANGE  The attribute has been demoted from the supertype IfcRelDecomposes and defines the non-ordered aggregation relationship. +
+ +
" +945;RelatedObjects;" +The object definitions, either object occurrences or object types, that are being aggregated. They are defined as the parts in the whole/part relationship. No order is implied between the parts. + +
+IFC2x4 CHANGE  The attribute has been demoted from the supertype IfcRelDecomposes and defines the non-ordered set of parts within the aggregation. +
+ +
" +948;RelatingObject;" +The object definition, either an non-product object type or a non-product object occurrence, that represents the nest. It is the whole within the whole/part relationship. + +
+IFC2x4 CHANGE  The attribute has been demoted from the supertype IfcRelDecomposes and defines the ordered nesting relationship. +
+ +
" +949;RelatedObjects;" +The object definitions, either non-product object occurrences or non-product object types, that are being nestes. They are defined as the parts in the ordered whole/part relationship - i.e. there is an implied order among the parts expressed by the position within the list of RelatedObjects. + +
+IFC2x4 CHANGE  The attribute has been demoted from the supertype IfcRelDecomposes and defines the ordered set of parts within the nest. +
+ +
" +955;RelatedObjects;" +Set of object or property definitions to which the external references or information is associated. It includes object and type objects, property set templates, property templates and property sets and contexts. +
+ + IFC2x4 CHANGE  The attribute datatype has been changed from IfcRoot to IfcDefinitionSelect. + + +
+
" +957;RelatingClassification;Classification applied to the objects. +959;RelatingDocument;Document information or reference which is applied to the objects. +961;RelatingLibrary;Reference to a library, from which the definition of the property set is taken. +967;RelatingContext;" +Reference to the IfcProject to which additional information is assigned. +" +968;RelatedDefinitions;" +Set of object or property definitions that are assigned to a context and to which the unit and representation context definitions of that context apply. +" +973;ObjectType;" +The type denotes a particular type that indicates the object further. The use has to be established at the level of instantiable subtypes. +" +974;LongName;" +Long name for the context as used for reference purposes. +" +975;Phase;" +Current project phase, or life-cycle phase of this project. Applicable values have to be agreed upon by view definitions or implementer agreements. + " +976;RepresentationContexts;" +Context of the representations used within the context. When the context is a project and it includes shape representations for its components, one or several geometric representation contexts need to be included that define e.g. the world coordinate system, the coordinate space dimensions, and/or the precision factor. +
+IFC2x4 CHANGE  The attribute has been changed to be optional. Change made with upward compatibility for file based exchange. +
+
" +977;UnitsInContext;" +Units globally assigned to measure types used within the context. +
+IFC2x4 CHANGE  The attribute has been changed to be optional. Change made with upward compatibility for file based exchange. +
+
" +978;Declares;" +Reference to the IfcRelDeclares relationship that assigns the uppermost entities of includes hierarchies to this context instance. +
+ + NOTE  the spatial hiearchy is assigned to IfcProject using the IfcRelAggregates relationship. This is a single exception due to compatibility reasons with earlier releases. + +
+" +986;RelatedObjects;"Reference to the objects (or single object) to which the property definition applies. " +987;RelatingPropertyDefinition;"Reference to the property set definition for that object or set of objects. " +989;RelatedObjects;" +Objects being part of an object occurrence decomposition, acting as the ""reflecting parts"" in the relationship. +" +990;RelatingObject;" +Object being part of an object type decomposition, acting as the ""declaring part"" in the relationship. +" +992;TemplateType;" +Property set type defining whether the property set is applicable to a type (subtypes of IfcTypeObject), to an occurrence (subtypes of IfcObject), or as a special case to a performance history.

+The attribute ApplicableEntity may further refine the applicability to a single or multiple entity type(s). +
" +993;ApplicableEntity;" +The attribute optionally defines the data type of the applicable type or occurrence object, to which the assigned property set template can relate. If not present, no instruction is given to which type or occurrence object the property set template is applicable. The following conventions are used: +
    +
  • The IFC entity name of the applicable entity using the IFC naming convention, CamelCase with IFC prefix
  • +
  • It can be optionally followed by the predefined type after the separator ""/"" (forward slash), using upper case
  • +
  • If a performance history object of a particular distribution object is attributes by the property set template, then the entity name (and potentially amended by the predefined type) is expanded by adding '[PerformanceHistory]' +
  • If one property set template is applicable to many type and/or occurrence objects, then those object names should be separate by comma "","" forming a comma separated string. +
+
+ EXAMPLE Refering to a boiler type as applicable entity would be expressed as 'IfcBoilerType', refering to a steam boiler type as applicable entity would be expressed as 'IfcBoilerType/STEAM', refering to a wall and wall standard case and a wall type would be expressed as 'IfcWall, IfcWallStandardCase, IfcWallType'. +
+ An applicable IfcPerformanceHistory assigned to an occurrence or type object would be indicated by IfcBoilerType[PerformanceHistory], or respectively IfcBoilerType/STEAM[PerformanceHistory]. +
+" +994;HasPropertyTemplates;" +Set of IfcPropertyTemplate's that are defined within the scope of the IfcPropertySetTemplate. +" +995;Defines;" +Relation to the property sets, via the objectified relationship IfcRelDefinesByTemplate, that, if given, utilize the definition template. +" +1004;PartOfComplexTemplate;" +Reference to a complex property templates. It should only be provided, if the PropertyType of the referenced complex property template is set to COMPLEX. +" +1005;PartOfPsetTemplate;" +Reference to the IfcPropertySetTemplate that defines the scope for the IfcPropertyTemplate. A single IfcPropertyTemplate can be defined within the scope of zero, one or many IfcPropertySetTemplate'. +" +1007;UsageName; +1008;TemplateType; +1009;HasPropertyTemplates;" +Reference to a set of property templates. It should only be provided, if the PropertyType is set to COMPLEX. +" +1016;TemplateType;" +Property type defining whether the property template defines a property with a single value, a bounded value, a list value, a table value, an enumerated value, or a reference value. Or the quantity type defining whether the template defines a quantity with a length, area, volume, weight or time value. +
+ + NOTE the value of this property determines the correct use of the PrimaryUnit, SecondaryUnit, PrimaryDataType, SecondaryDataType, and Expression attributes. + +
+
" +1017;PrimaryDataType;" +Primary data type assigned to the definition of the property. It should be provided, if the PropertyType is set to: +
    +
  • P_SINGLEVALUE: determining the data type of IfcPropertySingleValue.NominalValue
  • +
  • P_ENUMERATEDVALUE: determining the data type of IfcPropertyEnumeratedValue.EnumerationValues
  • +
  • P_BOUNDEDVALUE: determining the data type of IfcPropertyBoundedValue.LowerBoundValue
  • +
  • P_LISTVALUE: determining the data type of IfcPropertyListValue.ListValues
  • +
  • P_TABLEVALUE: determining the data type of IfcPropertyTableValue.DefiningValues
  • +
  • P_REFERENCEVALUE: determining the data type of IfcPropertyTableValue.PropertyReference
+
+

+ The value range of the data type is within the select type IfcValue for all PropertyType's with the exeption of P_REFERENCEVALUE. Here it is within the select type IfcObjectReferenceSelect. +

+
+
" +1018;SecondaryDataType;" +Secondary data type assigned to the definition of the property. It should be provided, if the PropertyType is set to: +
    +
  • P_ENUMERATEDVALUE: determining the values of IfcPropertyEnumeration.EnumerationValues as a comma delimited list
  • +
  • P_BOUNDEDVALUE: determining the data type of IfcPropertyBoundedValue.UpperBoundValue
  • +
  • P_TABLEVALUE: determining the data type of IfcPropertyTableValue.DefinedValues
  • +
+The value range of the data type is within the select type IfcValue for all PropertyType's with the exeption of P_ENUMERATEDVALUE. Here it is the comma delimited list of enumerators. +
+ + NOTE The data type of IfcPropertyEnumeration.EnumerationValues is provided as PrimaryDataType. + +
+
" +1019;PrimaryUnit;" +Primary unit assigned to the definition of the property. It should be provided, if the PropertyType is set to: +
    +
  • P_SINGLEVALUE: determining the IfcPropertySingleValue.Unit
  • +
  • P_ENUMERATEDVALUE: determining the IfcPropertyEnumeration.Unit
  • +
  • P_BOUNDEDVALUE: determining the IfcPropertyBoundedValue.Unit
  • +
  • P_LISTVALUE: determining the IfcPropertyListValue.Unit
  • +
  • P_TABLEVALUE: determining the IfcPropertyTableValue.DefiningUnit
  • +
+
" +1020;SecondaryUnit;" +Secondary unit assigned to the definition of the property. It should be provided, if the PropertyType is set to: +
    +
  • P_TABLEVALUE: determining the IfcPropertyTableValue.DefinedUnit
  • +
+
" +1021;Expression;" +The expression used to store additional information for the property template depending on the PropertyType. It should the following definitions, if the PropertyType is set to: +
    +
  • P_TABLEVALUE: the expression that could be evaluated to define the correlation between the defining values and the defined values.
  • +
  • Q_LENGTH, Q_AREA, Q_VOLUME, Q_COUNT, Q_WEIGTH, Q_TIME: the formula to be used to calculate the quantity
  • +
+
+ + NOTE No value shall be asserted if the PropertyType is not listed above. + +
+
" +1022;AccessState;" +Information about the access state of the property. It determines whether a property be viewed and/or modified by any receiving application without specific knowledge of it.

+Attribute use definition for IfcStateEnum + +
    +
  • READWRITE: Properties of this template are readable and writable. They may be viewed and modified by users of any application. These are typical informational properties set by a user.
  • + +
  • READONLY: Properties of this template are read-only. They may be viewed but not modified by users of any application. (Applications may generate such values). These are typical automatically generated properties that should be displayed only, but not written back.
  • + +
  • LOCKED: Properties of this template are locked. They may only be accessed by the owning application (the publisher of the property set template). These are typically application depended, internal properties that should not be published.
  • + +
  • READWRITELOCKED: Properties of this template are locked, readable, and writable. They may only be accessed by the owning application.
  • + +
  • READONLYLOCKED: Properties of this template are locked and read-only. They may only be accessed by the owning application.
  • + +
+
" +1047;ProxyType;"High level (and only) semantic meaning attached to the IfcProxy, defining the basic construct type behind the Proxy, e.g. Product or Process. " +1048;Tag;The tag (or label) identifier at the particular instance of a product, e.g. the serial number, or the position number. It is the identifier at the occurrence level. +1056;RelatedControlElements;"References control elements which may be used to impart control on the Distribution Element. " +1057;RelatingFlowElement;"Relationship to a distribution flow element " +1059;AssignedToFlowElement;Reference through the relationship object to related distribution flow elements. +1061;FlowDirection;"Enumeration that identifies if this port is a Sink (inlet), a Source (outlet) or both a SinkAndSource. " +1062;PredefinedType;Enumeration that identifies the system type. If a system type is defined, the port may only be connected to other ports having the same system type. +1126;PredefinedType;Predefined types of distribution chambers. +1140;LongName;" +Long name for a system, used for informal purposes. It should be used, if available, in conjunction with the inherited Name attribute. +
+ NOTE In many scenarios the Name attribute refers to the short name or number of a distribution system or branch circuit, and the LongName refers to a descriptive name. + +
+
" +1141;PredefinedType;Predefined types of distribution systems. +1152;HasControlElements;Reference to the relationship object that relates control elements. +1162;PredefinedType; +1167;PredefinedType;Subtype of discrete accessory +1181;PredefinedType;Subtype of building element part +1189;PredefinedType;Subtype of discrete accessory +1198;PredefinedType;Subtype of fastener +1207;PredefinedType;Subtype of mechanical fastener +1208;NominalDiameter;The nominal diameter describing the cross-section size of the fastener type. +1209;NominalLength;The nominal length describing the longitudinal dimensions of the fastener type. +1225;PredefinedType;Subtype of fastener +1229;PredefinedType;Subtype of building element part +1233;PredefinedType;Subtype of mechanical fastener +1238;RelatingSpace;" +Relationship to the space object that is covered. +
+ +IFC2x4 CHANGE: The attribute name has been changed from RelatedSpace to RelatingSpace with upward compatibility for file based exchange. + +
+
" +1239;RelatedCoverings;"Relationship to the set of coverings covering this space. " +1241;RelatingPriorities;"Priorities for connection. It refers to the layers of the RelatingObject. " +1242;RelatedPriorities;"Priorities for connection. It refers to the layers of the RelatedObject. " +1243;RelatedConnectionType;"Indication of the connection type in relation to the path of the RelatingObject. " +1244;RelatingConnectionType;"Indication of the connection type in relation to the path of the RelatingObject. " +1252;PredefinedType;" +Predefined generic type for a beam that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcBeamType is assigned, providing its own IfcBeamType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1268;PredefinedType;" +Predefined generic type for a column that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcColumnType is assigned, providing its own IfcColumnType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1279;PredefinedType;" +Predefined generic type for a member that is specified in an enumeration. There may be a property set given for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcMemberType is assigned, providing its own IfcMemberType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1302;PredefinedType;" +Predefined generic type for a wall that is specified in an enumeration. There may be a property set given specifically for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcWallType is assigned, providing its own IfcWallType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1321;PredefinedType;" +Predefined generic type for a slab that is specified in an enumeration. There may be a property set given specifically for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcSlabType is assigned, providing its own IfcSlabType.PredefinedType. +
+FC2x PLATFORM CHANGE: The attribute has been changed into an OPTIONAL attribute.
+
" +1336;PredefinedType;" +Predefined shape types for a ramp that are specified in an enumeration. +
+NOTE The PredefinedType shall only be used, if no type object IfcRampType is assigned, providing its own IfcRampType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been renamed from ShapeType and changed to be OPTIONAL with upward compatibility for file based exchange. +
+
" +1350;PredefinedType;" +Predefined shape types for a stair that are specified in an enumeration. +
+ +IFC2x4 CHANGE The attribute has been renamed from ShapeType and changed to be OPTIONAL with upward compatibility for file based exchange. + +
+
" +1372;PredefinedType;" +Predefined shape types for a roof that are specified in an enumeration. +
+IFC2x4 CHANGE The attribute has been renamed from ShapeType and changed to be OPTIONAL with upward compatibility for file based exchange. +
+
" +1393;NumberOfRiser;" +Number of the risers included in the stair flight +
+ +IFC2x4 CHANGE The attribute has been deprecated it shall only be exposed with a NIL value. Use Pset_StairFlightCommon.NumberOfRisers instead. + +" +1394;NumberOfTreads;" +Number of treads included in the stair flight. +
+ +IFC2x4 CHANGE The attribute has been deprecated it shall only be exposed with a NIL value. Use Pset_StairFlightCommon.NumberOfTreads instead. + +
+
" +4142;PointOnRelatedElement;"Point at which connected objects are aligned at the related element, given in the LCS of the related element. If the information is omitted, then the origin of the related element is used. " +4144;EccentricityInX;" +Distance in x direction between the two points (or vertex points) engaged in the point connection. +" +4145;EccentricityInY;" +Distance in y direction between the two points (or vertex points) engaged in the point connection. +" +4146;EccentricityInZ;" +Distance in z direction between the two points (or vertex points) engaged in the point connection. +" +4151;CurveOnRelatingElement;The bounded curve at which the connected objects are aligned at the relating element, given in the LCS of the relating element. +4152;CurveOnRelatedElement;The bounded curve at which the connected objects are aligned at the related element, given in the LCS of the related element. If the information is omitted, then the origin of the related element is used. +4157;SurfaceOnRelatingElement;Surface at which related object is aligned at the relating element, given in the LCS of the relating element. +4158;SurfaceOnRelatedElement;"Surface at which the relating element is aligned at the related element, given in the LCS of the related element. If the information is omitted, then the origin of the related element is used. " +4164;VolumeOnRelatingElement;" +Volume at which related object overlaps with the relating element, given in the LCS of the relating element. +" +4165;VolumeOnRelatedElement;" +Volume at which related object overlaps with the relating element, given in the LCS of the related element. +" +4170;AxisTag;The tag or name for this grid axis. +4171;AxisCurve;Underlying curve which provides the geometry for this grid axis. +4172;SameSense;Defines whether the original sense of curve is used or whether it is reversed in the context of the grid axis. +4173;PartOfW;" +If provided, the IfcGridAxis is part of the WAxes of IfcGrid. +
+ IFC2x Edition 3 CHANGE  New inverse attribute. +
+
" +4174;PartOfV;" +If provided, the IfcGridAxis is part of the VAxes of IfcGrid. +
+ IFC2x Edition 3 CHANGE  New inverse attribute. +
+
" +4175;PartOfU;" +If provided, the IfcGridAxis is part of the UAxes of IfcGrid. +
+ IFC2x Edition 3 CHANGE  New inverse attribute. +
+
" +4176;HasIntersections;" +The reference to a set of 's, that connect other grid axes to this grid axis. +
+ IFC2x3 CHANGE  New inverse attribute. +
+
" +4180;IntersectingAxes;Two grid axes which intersects at exactly one intersection (see also informal proposition at IfcGrid). If attribute OffsetDistances is omitted, the intersection defines the placement or ref direction of a grid placement directly. If OffsetDistances are given, the intersection is defined by the offset curves to the grid axes. +4181;OffsetDistances;"Offset distances to the grid axes. If given, it defines virtual offset curves to the grid axes. The intersection of the offset curves specify the virtual grid intersection. " +4183;PlacementLocation;" +Placement of the object coordinate system defined by the intersection of two grid axes. + " +4951;Target;A description of the placement, orientation and (uniform or non-uniform) scaling of the defined symbol. +4960;AppliesTextures;" +Reference to the one (or in case of multi textures with identity transformation to geometric surfaces) subtype of IfcSurfaceTexture that is applied to a geometric surface by the texture coordinate transformation. +" +4962;Mode;" +The Mode attribute describes the algorithm used to compute texture coordinates. +
+

+ NOTE  The applicable values for the Mode attribute are determined by view definitions or implementer agreements. It is recommended to use the modes described in ISO/IES 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1. See 18.4.8 TextureCoordinateGenerator for recommended values. +

+
+
" +4963;Parameter;" +The parameters used as arguments by the function as specified by Mode. +
+

+ IFC2x4 CHANGE  Made optional data type restricted to REAL. +

+
+
" +4965;Vertices;" +List of texture coordinate vertices that are applied to the corresponding points of the polyloop defining a face bound. +
+

+ NOTE  The corresponding face bound may be an inner loop. +

+
+
" +4966;AppliedTo;" +Th face bound that defines the corresponding list of points along the bounding poly loop. +
+

+ NOTE  The face bound may be an inner loop. In this case it defines an area to which no texturing shall be applied. +

+
+
" +4968;Coordinates;The first coordinate[1] is the S, the second coordinate[2] is the T parameter value. +4970;Extent;The extent in the x and y direction of the text literal. +4971;BoxAlignment;The alignment of the text literal relative to its position. +4986;Name;"The name given to the light source in presentation. " +4987;LightColour;"Definition from ISO/CD 10303-46:1992: Based on the current lighting model, the colour of the light to be used for shading. +Definition from VRML97 - ISO/IEC 14772-1:1997: The color field specifies the spectral color properties of both the direct and ambient light emission as an RGB value. " +4988;AmbientIntensity;"Definition from VRML97 - ISO/IEC 14772-1:1997: The ambientIntensity specifies the intensity of the ambient emission from the light. Light intensity may range from 0.0 (no light emission) to 1.0 (full intensity). " +4989;Intensity;"Definition from VRML97 - ISO/IEC 14772-1:1997: The intensity field specifies the brightness of the direct emission from the ligth. Light intensity may range from 0.0 (no light emission) to 1.0 (full intensity). " +4992;Orientation;"Definition from ISO/CD 10303-46:1992: This direction is the direction of the light source. +Definition from VRML97 - ISO/IEC 14772-1:1997: The direction field specifies the direction vector of the illumination emanating from the light source in the local coordinate system. Light is emitted along parallel rays from an infinite distance away. " +4995;Position;"Definition from ISO/CD 10303-46:1992: The Cartesian point indicates the position of the light source. +Definition from VRML97 - ISO/IEC 14772-1:1997: A Point light node illuminates geometry within radius of its location. " +4996;Radius;"Definition from IAI: The maximum distance from the light source for a surface still to be illuminated. +Definition from VRML97 - ISO/IEC 14772-1:1997: A Point light node illuminates geometry within radius of its location. " +4997;ConstantAttenuation;"Definition from ISO/CD 10303-46:1992: This real indicates the value of the attenuation in the lighting equation that is constant. " +4998;DistanceAttenuation;"Definition from ISO/CD 10303-46:1992: This real indicates the value of the attenuation in the lighting equation that proportional to the distance from the light source. " +4999;QuadricAttenuation;"Definition from the IAI: This real indicates the value of the attenuation in the lighting equation that proportional to the square value of the distance from the light source. " +5001;Orientation;"Definition from ISO/CD 10303-46:1992: This is the direction of the axis of the cone of the light source specified in the coordinate space of the representation being projected.. +Definition from VRML97 - ISO/IEC 14772-1:1997: The direction field specifies the direction vector of the light's central axis defined in the local coordinate system. " +5002;ConcentrationExponent;"Definition from ISO/CD 10303-46:1992: This real is the exponent on the cosine of the angle between the line that starts at the position of the spot light source and is in the direction of the orientation of the spot light source and a line that starts at the position of the spot light source and goes through a point on the surface being shaded. +NOTE: This attribute does not exists in ISO/IEC 14772-1:1997." +5654;V2;Second v parametric value. +5655;Usense;Flag to indicate whether the direction of the first parameter of the trimmed surface agrees with or opposes the sense of u in the basis surface. +5656;Vsense;Flag to indicate whether the direction of the second parameter of the trimmed surface agrees with or opposes the sense of v in the basis surface. +5662;BasisSurface;" +The surface to be bounded. +" +5663;Boundaries;" +The outer boundary of the surface. +" +5664;ImplicitOuter; +5667;UDegree;" +Algebraic degree of basis functions in u. +" +5668;VDegree;" +Algebraic degree of basis functions in v. +" +5669;ControlPointsList;" +This is a list of lists of control points. +" +5671;SurfaceForm;" +Indicator of special surface types. +" +5672;UClosed;" +Indication of whether the surface is closed in the u direction; this is for information only. +" +5673;VClosed;" +Indication of whether the surface is closed in the v direction; this is for information only. +" +5674;SelfIntersect;" +Flag to indicate whether, or not, surface is self-intersecting; this is for information only. +" +5675;ControlPoints;" +Array (two-dimensional) of control points defining surface geometry. This array is constructed from the control points list. +" +5677;VUpper;" +Upper index on control points in v direction. +" +5678;UUpper;" +Upper index on control points in u direction. +" +5681;UMultiplicities;" +The multiplicities of the knots in the u parameter direction. +" +5682;VMultiplicities;" +The multiplicities of the knots in the v parameter direction. +" +5683;UKnots;" +The list of the distinct knots in the u parameter direction. +" +5684;VKnots;" +The list of the distinct knots in the v parameter direction. +" +1395;RiserHeight;" +Vertical distance from tread to tread. The riser height is supposed to be equal for all stairs in a stair flight. + +IFC2x4 CHANGE The attribute has been deprecated it shall only be exposed with a NIL value. Use Pset_StairFlightCommon.RiserHeight instead. + +" +1396;TreadLength;" +Horizontal distance from the front to the back of the tread. The tread length is supposed to be equal for all steps of the stair flight. + +IFC2x4 CHANGE The attribute has been deprecated it shall only be exposed with a NIL value. Use Pset_StairFlightCommon.TreadLength instead. + +" +1397;PredefinedType;" +Predefined generic type for a stair flight that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcStairFlightType is assigned, providing its own IfcStairFlightType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1409;PredefinedType;" +Predefined generic type for a ramp flight that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcRampFlightType is assigned, providing its own IfcRampFlightType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1418;PredefinedType;" +Predefined generic type for a curtain wall that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcCurtainWallType is assigned, providing its own IfcCurtainWallType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1425;PredefinedType;" +Predefined generic types for a railing that are specified in an enumeration. There may be a property set given for the predefined types. +
NOTE: The use of the predefined type directly at the occurrence object level of IfcRailing is only permitted, if no type object IfcRailingType is assigned.
+
IFC2x PLATFORM CHANGE: The attribute has been changed into an OPTIONAL attribute.
+
" +1436;OverallHeight;"Overall measure of the height, it reflects the Z Dimension of a bounding box, enclosing the body of the door opening. If omitted, the OverallHeight should be taken from the geometric representation of the IfcOpening in which the door is inserted. +
+NOTE  The body of the door might be taller then the door opening (e.g. in cases where the door lining includes a casing). In these cases the OverallHeight shall still be given as the door opening height, and not as the total height of the door lining.
+
" +1437;OverallWidth;"Overall measure of the width, it reflects the X Dimension of a bounding box, enclosing the body of the door opening. If omitted, the OverallWidth should be taken from the geometric representation of the IfcOpening in which the door is inserted. +
+NOTE  The body of the door might be wider then the door opening (e.g. in cases where the door lining includes a casing). In these cases the OverallWidth shall still be given as the door opening width, and not as the total width of the door lining.
+
" +1438;PredefinedType;" +Predefined generic type for a door that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcDoorType is assigned, providing its own IfcDoorType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1439;OperationType;" +Type defining the general layout and operation of the door type in terms of the partitioning of panels and panel operations. +
+ NOTE The OperationType shall only be used, if no type object IfcDoorType is assigned, providing its own IfcDoorType.OperationType. + +
+ IFC2x4 CHANGE The attribute has been added at the end of the entity definition. + +
+
" +1471;OverallHeight;"Overall measure of the height, it reflects the Z Dimension of a bounding box, enclosing the body of the window opening. If omitted, the OverallHeight should be taken from the geometric representation of the IfcOpening in which the window is inserted. +
+NOTE  The body of the window might be taller then the window opening (e.g. in cases where the window lining includes a casing). In these cases the OverallHeight shall still be given as the window opening height, and not as the total height of the window lining.
+
" +1472;OverallWidth;"Overall measure of the width, it reflects the X Dimension of a bounding box, enclosing the body of the window opening. If omitted, the OverallWidth should be taken from the geometric representation of the IfcOpening in which the window is inserted. +
+NOTE  The body of the window might be wider then the window opening (e.g. in cases where the window lining includes a casing). In these cases the OverallWidth shall still be given as the window opening width, and not as the total width of the window lining.
+
" +1473;PredefinedType;" +Predefined generic type for a window that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcWindowType is assigned, providing its own IfcWindowType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1474;PartitioningType;" +Type defining the general layout of the window in terms of the partitioning of panels. +
+ NOTE The PartitioningType shall only be used, if no type object IfcWindowType is assigned, providing its own IfcWindowType.PartitioningType. + +
+ IFC2x4 CHANGE The attribute has been added at the end of the entity definition. + +
+
" +1497;PredefinedType;" +Predefined generic type for a plate that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcPlateType is assigned, providing its own IfcPlateType.PredefinedType. +
+IFC2x4 CHANGE The attribute has been added at the end of the entity definition.
+
" +1508;PredefinedType;" +Predefined generic type for a chimney that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcChimneyType is assigned, providing its own IfcChimneyType.PredefinedType. +
+
" +1515;PredefinedType; +1527;PredefinedType;Predefined types to define the particular type of the covering. There may be property set definitions available for each predefined type. +1528;CoversSpaces;" +Reference to the objectified relationship that handles the relationship of the covering to the covered space. +" +1529;CoversElements;" +Reference to the objectified relationship that handles the relationship of the covering to the covered element. +
IFC2x4 CHANGE Renamed into CoversElements for consistency. +
+
" +1544;RelatingBuildingElement;" +Relationship to the building element that is covered. +
+ +IFC2x4 CHANGE: The attribute type has been changed from IfcElement to IfcBuildingElement. + +
+
" +1545;RelatedCoverings;"Relationship to the set of coverings at this element. " +1547;PredefinedType;" +Predefined generic type for a shading device that is specified in an enumeration. There may be a property set given specificly for the predefined types. +
NOTE The PredefinedType shall only be used, if no type object IfcShadingDeviceType is assigned, providing its own IfcShadingDeviceType.PredefinedType. +
+
" +1557;PredefinedType;" +Identifies the predefined types of a slab element from which the type required may be set. +" +1560;PredefinedType;" +Identifies the predefined types of a wall element from which the type required may be set. +" +1563;PredefinedType;Identifies the predefined types of a stair flight element from which the type required may be set. +1566;PredefinedType;Identifies the predefined types of a railing element from which the type required may be set. +1569;PredefinedType;Identifies the predefined types of a ramp flight element from which the type required may be set. +1572;PredefinedType;" +Identifies the predefined types of a beam element from which the type required may be set. +" +1575;PredefinedType;" +Identifies the predefined types of a column element from which the type required may be set. +" +1578;PredefinedType;" +Identifies the predefined types of a linear structural member element from which the type required may be set. +" +1581;PredefinedType;" +Identifies the predefined types of a curtain wall element from which the type required may be set. +" +1584;PredefinedType;" +Identifies the predefined types of a planar member element from which the type required may be set. +" +1587;PredefinedType;" +Identifies the predefined types of a stair element from which the type required may be set. +" +1590;PredefinedType;" +Identifies the predefined types of a ramp element from which the type required may be set. +" +1593;PredefinedType;" +Identifies the predefined types of a roof element from which the type required may be set. +" +1596;PredefinedType;" +Identifies the predefined types of a chimney element from which the type required may be set. +" +1599;PredefinedType;" +Predefined types to define the particular type of an building element proxy. There may be property set definitions available for each predefined or user defined type. +" +1601;PredefinedType;" +Predefined types to define the particular type of the covering. There may be property set definitions available for each predefined type. +" +1604;PredefinedType;" +Identifies the predefined types of a door element from which the type required may be set. +" +1605;OperationType;" +Type defining the general layout and operation of the door type in terms of the partitioning of panels and panel operations. +" +1607;PredefinedType;" +Identifies the predefined types of a window element from which the type required may be set. +" +1608;PartitioningType;" +Type defining the general layout of the window type in terms of the partitioning of panels. +" +1610;PredefinedType;" +Identifies the predefined types of a shading device element from which the type required may be set. +" +1612;PredefinedType;" +Predefined types of distribution systems. +" +1622;Identification;"A unique identification assigned to an asset that enables its differentiation from other assets. +

NOTE: The asset identifier is unique within the asset register. It differs from the globally unique id assigned to the instance of an entity populating a database.

+
" +1623;OriginalValue;The cost value of the asset at the time of purchase. +1624;CurrentValue;The current cost value of the asset. +1625;TotalReplacementCost;The total cost of replacement of the asset. +1626;Owner;The name of the person or organization that 'owns' the asset. +1627;User;The name of the person or organization that 'uses' the asset. +1628;ResponsiblePerson;"The person designated to be responsible for the asset. +

NOTE: In some regulations (for example, UK Health and Safety at Work Act, Electricity at Work Regulations), management of assets must have a person identified as being responsible and to whom regulatory, insurance and other organizations communicate. In places where there is not a legal requirement, the responsible person would be the asset manager but would not have a legal status.

+
" +1629;IncorporationDate;" +The date on which an asset was incorporated into the works, installed, constructed, erected or completed. +

NOTE: This is the date on which an asset is considered to start depreciating.

+
+ + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
+
" +1630;DepreciatedValue;The current value of an asset within the accounting rules and procedures of an organization. +1632;PredefinedType;"A list of the types of inventories from which that required may be selected. +
+ + +IFC2x4 CHANGE Attribute made optional. + + +
+
" +1633;Jurisdiction;The organizational unit to which the inventory is applicable. +1634;ResponsiblePersons;Persons who are responsible for the inventory. +1635;LastUpdateDate;" +

The date on which the last update of the inventory was carried out.

+
+ + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
+
" +1636;CurrentValue;An estimate of the current cost value of the inventory. +1637;OriginalValue;An estimate of the original cost value of the inventory. +1645;PredefinedType;"Predefined occupant types from which that required may be set. + +
+ + +IFC2x4 CHANGE Attribute made optional. + + +
+ +
" +1658;PredefinedType; +1667;PredefinedType; +1681;PredefinedType; +1684;AssemblyPlace;

A designation of where the assembly is intended to take place. A selection of alternatives s provided in an enumerated list.

+1685;PredefinedType; +1689;OperationType;" +Type defining the general layout and operation of the door style. +
+
" +1690;ConstructionType;" +Type defining the basic construction and material type of the door. +
+
" +1691;ParameterTakesPrecedence;" +The Boolean value reflects, whether the parameter given in the attached lining and panel properties exactly define the geometry (TRUE), or whether the attached style shape take precedence (FALSE). In the last case the parameter have only informative value. +
+
" +1692;Sizeable;" +The Boolean indicates, whether the attached IfcMappedRepresentation (if given) can be sized (using scale factor of transformation), or not (FALSE). If not, the IfcMappedRepresentation should be IfcShapeRepresentation of the IfcDoor (using IfcMappedItem as the Item) with the scale factor = 1. +
+
" +1723;ConstructionType;Type defining the basic construction and material type of the window. +1724;OperationType;Type defining the general layout and operation of the window style. +1725;ParameterTakesPrecedence;The Boolean value reflects, whether the parameter given in the attached lining and panel properties exactly define the geometry (TRUE), or whether the attached style shape take precedence (FALSE). In the last case the parameter have only informative value. +1726;Sizeable;The Boolean indicates, whether the attached ShapeStyle can be sized (using scale factor of transformation), or not (FALSE). If not, the ShapeStyle should be inserted by the IfcWindow (using IfcMappedItem) with the scale factor = 1. +1749;LiningDepth;Depth of the door lining, measured perpendicular to the plane of the door lining. If omitted (and with a given value to lining thickness) it indicates an adjustable depth (i.e. a depth that adjusts to the thickness of the wall into which the occurrence of this door style is inserted). +1750;LiningThickness;Thickness (width in plane parallel to door leaf) of the door lining. +1751;ThresholdDepth;Depth (dimension in plane perpendicular to door leaf) of the door threshold. Only given if the door lining includes a threshold. If omitted (and with a given value to threshold thickness) it indicates an adjustable depth (i.e. a depth that adjusts to the thickness of the wall into which the occurrence of this door style is inserted). +1752;ThresholdThickness;Thickness (width in plane parallel to door leaf) of the door threshold. Only given if the door lining includes a threshold and the parameter is known. +1753;TransomThickness;Thickness (width in plane parallel to door leaf) of the transom (if given) which divides the door leaf from a glazing (or window) above. +1754;TransomOffset;Offset of the transom (if given) which divides the door leaf from a glazing (or window) above. The offset is given from the bottom of the door opening. +1755;LiningOffset;Offset (dimension in plane perpendicular to door leaf) of the door lining. The offset is given as distance to the x axis of the local placement. +1756;ThresholdOffset;Offset (dimension in plane perpendicular to door leaf) of the door threshold. The offset is given as distance to the x axis of the local placement. Only given if the door lining includes a threshold and the parameter is known. +1757;CasingThickness;Thickness of the casing (dimension in plane of the door leaf). If given it is applied equally to all four sides of the adjacent wall. +1758;CasingDepth;Depth of the casing (dimension in plane perpendicular to door leaf). If given it is applied equally to all four sides of the adjacent wall. +1759;ShapeAspectStyle;" +Pointer to the shape aspect, if given. The shape aspect reflects the part of the door shape, which represents the door lining. +
+IFC2x4 CHANGE The attribute is deprecated and shall no longer be used, i.e. the value shall be NIL ($). +
+
" +1760;LiningToPanelOffsetX;" +Offset between the lining and the window panel measured along the x-axis of the local placement. +
+IFC2x4 CHANGE: New attribute added at the end of the entity definition. +
+
" +1761;LiningToPanelOffsetY;" +Offset between the lining and the door panel measured along the y-axis of the local placement. +
+IFC2x4 CHANGE: New attribute added at the end of the entity definition. +
+
" +1768;PanelDepth;" +Depth of the door panel, measured perpendicular to the plane of the door leaf. +" +1769;PanelOperation;" +The PanelOperation defines the way of operation of that panel. The PanelOperation of the door panel has to correspond with the OperationType of the IfcDoorStyle by which it is referenced. +" +1770;PanelWidth;" +Width of this panel, given as ratio relative to the total clear opening width of the door. If omited, it defaults to 1. A value has to be provided for all doors with OperationType's at IfcDoorStyle defining a door with more then one panel. +" +1771;PanelPosition;" +Position of this panel within the door. The PanelPosition of the door panel has to correspond with the OperationType of the IfcDoorStyle by which it is referenced. +" +1772;ShapeAspectStyle;" +Pointer to the shape aspect, if given. The shape aspect reflects the part of the door shape, which represents the door panel. +
+IFC2x4 CHANGE The attribute is deprecated and shall no longer be used, i.e. the value shall be NIL ($). +
+
" +1790;OperationType;"Types of window panel operations. Also used to assign standard symbolic presentations according to national building standards. " +1791;PanelPosition;Position of this panel within the overall window style. +1792;FrameDepth;Depth of panel frame, measured from front face to back face horizontally (i.e. perpendicular to the window (elevation) plane. +1793;FrameThickness;Width of panel frame, measured from inside of panel (at glazing) to outside of panel (at lining), i.e. parallel to the window (elevation) plane. +1794;ShapeAspectStyle;" +Optional link to a shape aspect definition, which points to the part of the geometric representation of the window style, which is used to represent the panel. +
+IFC2x4 CHANGE The attribute is deprecated and shall no longer be used, i.e. the value shall be NIL ($). +
+
" +1818;LiningDepth;Depth of the window lining (dimension measured perpendicular to window elevation plane). +1819;LiningThickness;Thickness of the window lining (measured parallel to the window elevation plane). +1820;TransomThickness;Thickness of the transom (horizontal separator of window panels within a window), measured parallel to the window elevation plane. The transom is part of the lining and the transom depth is assumed to be identical to the lining depth. +1821;MullionThickness;Thickness of the mullion (vertical separator of window panels within a window), measured parallel to the window elevation plane. The mullion is part of the lining and the mullion depth is assumed to be identical to the lining depth. +1822;FirstTransomOffset;Offset of the transom centerline, measured along the z-axis of the window placement co-ordinate system. An offset value = 0.5 indicates that the transom is positioned in the middle of the window. +1823;SecondTransomOffset;Offset of the transom centerline for the second transom, measured along the x-axis of the window placement co-ordinate system. An offset value = 0.666 indicates that the second transom is positioned at two/third of the window. +1824;FirstMullionOffset;Offset of the mullion centerline, measured along the x-axis of the window placement co-ordinate system. An offset value = 0.5 indicates that the mullion is positioned in the middle of the window. +1825;SecondMullionOffset;Offset of the mullion centerline for the second mullion, measured along the x-axis of the window placement co-ordinate system. An offset value = 0.666 indicates that the second mullion is positioned at two/third of the window. +1826;ShapeAspectStyle;" +Optional link to a shape aspect definition, which points to the part of the geometric representation of the window style, which is used to represent the lining. +
+IFC2x4 CHANGE The attribute is deprecated and shall no longer be used, i.e. the value shall be NIL ($). +
+
" +1827;LiningOffset;" +Offset of the window lining. The offset is given as distance along the y axis of the local placement (perpendicular to the window plane). +
+IFC2x4 CHANGE: New attribute added at the end of the entity definition. +
+
" +1828;LiningToPanelOffsetX;" +Offset between the lining and the window panel measured along the x-axis of the local placement. Should be smaller or equal to the LiningThickness. +
+IFC2x4 CHANGE: New attribute added at the end of the entity definition. +
+
" +1829;LiningToPanelOffsetY;" +Offset between the lining and the window panel measured along the y-axis of the local placement. Should be smaller or equal to the IfcWindowPanelProperties.PanelThickness. +
+IFC2x4 CHANGE: New attribute added at the end of the entity definition. +
+
" +1835;OperationType;"Types of permeable covering operations. Also used to assign standard symbolic presentations according to national building standards. " +1836;PanelPosition;Position of this permeable covering panel within the overall window or door type. +1837;FrameDepth;Depth of panel frame (used to include the permeable covering), measured from front face to back face horizontally (i.e. perpendicular to the window or door (elevation) plane. +1838;FrameThickness;Width of panel frame (used to include the permeable covering), measured from inside of panel (at permeable covering) to outside of panel (at lining), i.e. parallel to the window or door (elevation) plane. +1839;ShapeAspectStyle;Optional link to a shape aspect definition, which points to the part of the geometric representation of the window style, which is used to represent the permeable covering. +1848;PredefinedType; +1863;PredefinedType; +1875;PredefinedType; +1887;PredefinedType; +1914;PredefinedType; +1927;PredefinedType; +1942;PredefinedType;

Identifies the predefined types of sensor from which the type required may be set.

+1945;PredefinedType;

Identifies the predefined types of controller from which the type required may be set.

+1948;PredefinedType;

Identifies the predefined types of actuator from which the type required may be set.

+1951;PredefinedType;

Identifies the predefined types of flow instrument from which the type required may be set.

+1954;PredefinedType;

Identifies the predefined types of alarm from which the type required may be set.

+1957;PredefinedType;

Identifies the predefined types of unitary control element from which the type required may be set.

+1963;AssignedStructuralActivity;Inverse relationship to all structural activities (i.e. to actions or reactions) which are assigned to this structural member. +1967;ConnectedBy;Inverse relationship to all structural connections (i.e. to supports or connecting elements) which are defined for this structural member. +1970;PredefinedType;Type of member with respect to its load carrying behavior in this analysis idealization. +1971;Axis;" + +Direction which is used in the definition of the local z axis. Axis is specified relative to the so-called global coordinate system, i.e. the SELF\IfcProduct.ObjectPlacement. + +
NOTE  It is desirable and usually possible that many instances of IfcStructuralCurveConnection and IfcStructuralCurveMember share a common instance of IfcDirection as their Axis attribute.
+ +
" +1984;PredefinedType;Type of member with respect to its load carrying behavior in this analysis idealization. +1985;Thickness;Defines the typically understood thickness of the structural surface member, measured normal to its reference surface. +1996;RelatingStructuralMember;Reference to an instance of IfcStructuralMember (or its subclasses) which is connected to the specified structural connection. +1997;RelatedStructuralConnection;Reference to an instance of IfcStructuralConnection (or its subclasses) which is connected to the specified structural member. +1998;AppliedCondition;"Conditions which define the connections properties. Connection conditions are often called "release" but are not only used to define mechanisms like hinges but also rigid, elastic, and other conditions." +1999;AdditionalConditions;Describes additional connection properties. +2000;SupportedLength;Defines the 'supported length' of this structural connection. See Fig. for more detail. +2001;ConditionCoordinateSystem;" + +Defines a coordinate system used for the description of the connection properties in ConnectionCondition relative to the local coordinate system of RelatingStructuralMember. If left unspecified, the placement IfcAxis2Placement3D((x,y,z), ?, ?) is implied with x,y,z being the local member coordinates where the connection is made and the default axes directions being in parallel with the local axes of RelatingStructuralMember. + +" +2003;RelatingElement;Reference to a structural item or element to which the specified activity is applied. +2004;RelatedStructuralActivity;Reference to a structural activity which is acting upon the specified structural item or element. +2009;PredefinedType;Defines the type of the structural analysis model. +2010;OrientationOf2DPlane;" + +If the selected model type (PredefinedType) describes a 2D system, the orientation defines +the analysis plane (P[1], P[2]) and the normal to the analysis plane (P[3]). This is needed because +structural items and activities are always defined in three-dimensional space even if they are +meant to be analysed in a two-dimensional manner. + +
    +
  • In case of predefined type IN_PLANE_LOADING_2D, the analysis is to be performed within the +projection into the P[1], P[2] plane.
  • +
  • In case of predefined type OUT_PLANE_LOADING_2D, only the P[3] component of loads and their +effects is meant to be analyzed. This is used for beam grids and for typical slab analyses.
  • +
  • In case of predefined type LOADING_3D, OrientationOf2DPlane shall be omitted.
  • +
+ +
" +2011;LoadedBy;References to all load groups to be analyzed. +2012;HasResults;References to all result groups available for this structural analysis model. +2013;SharedPlacement;" + +Object placement which shall be common to all items and activities which are grouped into this instance of IfcStructuralAnalysisModel. This placement establishes a coordinate system which is referred to as 'global coordinate system' in use definitions of various classes of structural items and activities. + +
NOTE  Most commonly, but not necessarily, the SharedPlacement is an IfcLocalPlacement whose z axis is parallel with the z axis of the IfcProject's world coordinate system and directed like the WCS z axis (i.e. pointing "upwards") or directed against the WCS z axis (i.e. points "downwards").
+ +
NOTE  Per informal proposition, this attribute is not optional as soon as at least one IfcStructuralItem is grouped into the instance of IfcStructuralAnalysisModel.
+ +
" +2023;PredefinedType;"Selects a predefined type for the load group. It can be differentiated between load groups, load cases, load combinations, or userdefined grouping levels. " +2024;ActionType;Type of actions in the group. Normally needed if 'PredefinedType' specifies a LOAD_CASE. +2025;ActionSource;Source of actions in the group. Normally needed if 'PredefinedType' specifies a LOAD_CASE. +2026;Coefficient;Load factor. If omitted, a factor is not yet known or not specified. A load factor of 1.0 shall be explicitly exported as Coefficient = 1.0. +2027;Purpose;Description of the purpose of this instance. Among else, possible values of the Purpose of load combinations are 'SLS', 'ULS', 'ALS' to indicate serviceability, ultimate, or accidental limit state. +2028;SourceOfResultGroup;Results which were computed using this load group. +2029;LoadGroupFor;Analysis models in which this load group is used. +2032;TheoryType;Specifies the analysis theory used to obtain the respective results. +2033;ResultForLoadGroup;Reference to an instance of IfcStructuralLoadGroup for which this instance represents the result. +2034;IsLinear;This value allows to easily recognize whether a linear analysis has been applied (allowing the superposition of analysis results). +2035;ResultGroupFor;Reference to an instance of IfcStructuralAnalysisModel for which this instance captures a result. +2045;SelfWeightCoefficients;" + +The self weight coefficients specify ratios at which loads due to weight of members shall be included in the load case. These loads are not explicitly modeled as instances of IfcStructuralAction. Instead they shall be calculated according to geometry, section, and material of each member. + +

The three components of the self weight vector correspond with the x,y,z directions of the so-called global coordinates, i.e. the directions of the shared ObjectPlacement of all items in an IfcStructuralAnalysisModel. For example, if the object placement defines a z axis which is upright like the IfcProject's world coordinate system, then the self weight coefficients would typically be [0.,0.,-1.] in a load case of dead loads with self weight.

+ +

The overall coefficient in the inherited attribute Coefficient shall not be applied to SelfWeightCoefficients of the same instance of IfcStructuralLoadCase. It only applies to actions and load groups which are grouped below the load case, not to the load case's computed self weight. + +" +2046;PredefinedType;" + +An IfcStructuralLoadCase is a load group of type LOAD_CASE. + +" +2090;AppliedLoad;" + +Load or result resource object which defines the load type, direction, and load values. + +

In case of activities which are variably distributed over curves or surfaces, IfcStructuralLoadConfiguration is used which provides a list of load samples and their locations within the load distribution, measured in local coordinates of the curve or surface on which this activity acts. The contents of this load or result distribution may be further restricted by definitions at subtypes of IfcStructuralActivity.

+ +
" +2091;GlobalOrLocal;" + +Indicates whether the load directions refer to the global coordinate system (global to +the analysis model, i.e. as established by IfcStructuralAnalysisModel.SharedPlacement) +or to the local coordinate system (local to the activity or connected item, as established by +an explicit or implied representation and its parameter space). + +
NOTE, the informal definition of +IfcRepresentationResource.IfcGlobalOrLocalEnum doe s not distinguish between +"global coordinate system" and "world coordinate system". +On the other hand, this distinction is necessary in the IfcStructuralAnalysisDomain +where the shared "global" coordinate system of an analysis model may very well +not be the same as the project-wide world coordinate system.
+ +
In the scope of IfcStructuralActivity.GlobalOrLocal, +the meaning of GLOBAL_COORDS is therefore not to be taken as world coordinate system +but as the analysis model specific shared coordinate system. In contrast, LOCAL_COORDS +is to be taken as coordinates which are local to individual structural items and activities, +as established by subclass-specific geometry use definitions.
+ +
" +2092;AssignedToStructuralItem;" + +Reference to the IfcRelConnectsStructuralActivity relationship by which activities are connected with structural items. + +" +2097;DestabilizingLoad;Indicates if this action may cause a stability problem. If it is 'FALSE', no further investigations regarding stability problems are necessary. +2101;ProjectedOrTrue;Defines whether load values are given per true length of the curve on which they act, or per length of the projection of the curve in load direction. The latter is only applicable to loads which act in global coordinate directions. +2102;PredefinedType;Type of action according to its distribution of load values. +2107;PredefinedType;The load is uniformly distributed over the curve. +2123;ProjectedOrTrue;Defines whether load values are given per true lengths of the surface on which they act, or per lengths of the projection of the surface in load direction. The latter is only applicable to loads which act in global coordinate directions. +2124;PredefinedType;Type of action according to its distribution of load values. +2128;PredefinedType;The load is uniformly distributed over the surface. +2142;PredefinedType;Type of reaction according to its distribution of load values. +2146;PredefinedType;Type of reaction according to its distribution of load values. +2149;ConnectionConstraint;The connection constraint explicitly states the eccentricity between a structural member and a structural connection by means of two topological objects (vertex and vertex, or edge and edge, or face and face). +2154;AppliedCondition;Optional boundary conditions which define support conditions of this connection object, given in local coordinate directions of the connection object. If left unspecified, the connection object is assumed to have no supports besides being connected with members. +2155;ConnectsStructuralMembers;References to the IfcRelConnectsStructuralMembers relationship by which structural members can be associated to structural connections. +2157;Axis;" + +Direction which is used in the definition of the local z axis. Axis is specified relative to the so-called global coordinate system, i.e. the SELF\IfcProduct.ObjectPlacement. + +
NOTE  It is desirable and usually possible that many instances of IfcStructuralCurveConnection and IfcStructuralCurveMember share a common instance of IfcDirection as their Axis attribute.
+ +
" +2159;ConditionCoordinateSystem;" + +Defines a coordinate system used for the description of the support condition properties in SELF\IfcStructuralConnection.SupportCondition, specified relative to the global coordinate system (global to the structural analysis model) established by SELF.\IfcProduct.ObjectPlacement. If left unspecified, the placement IfcAxis2Placement3D((x,y,z), ?, ?) is implied with x,y,z being the coordinates of the reference point of this IfcStructuralPointConnection and the default axes directions being in parallel with the global axes. + +" +2168;CoordinateSpaceDimension;"The integer dimension count of the coordinate space modeled in a geometric representation context. +
+" +2169;Precision;"Value of the model precision for geometric models. It is a double value (REAL), typically in 1E-5 to 1E-8 range, that indicates the tolerance under which two given points are still assumed to be identical. The value can be used e.g. to sets the maximum distance from an edge curve to the underlying face surface in brep models. +" +2170;WorldCoordinateSystem;" +Establishment of the engineering coordinate system (often referred to as the world coordinate system in CAD) for all representation contexts used by the project. +
+Note  it can be used to provide better numeric stability if the placement of the building(s) is far away from the origin. In most cases however it would be set to origin: (0.,0.,0.) and directions x(1.,0.,0.), y(0.,1.,0.), z(0.,0.,1.). +
+
" +2171;TrueNorth;" +Direction of the true north, or geographic northing direction, relative to the underlying project coordinate system. It is given by a 2 dimensional direction within the xy-plane of the project coordinate system. If not resent, it defaults to 0. 1. - i.e. the positive Y axis of the project coordinate system equals the geographic northing direction. +
+
" +2172;HasSubContexts;" +The set of IfcGeometricRepresentationSubContexts that refer to this IfcGeometricRepresentationContext. +
+ IFC2x Edition 3 CHANGE  New inverse attribute. +
+
" +2176;ContextIdentifier;The optional identifier of the representation context as used within a project. +2177;ContextType;The description of the type of a representation context. The supported values for context type are to be specified by implementers agreements. +2178;RepresentationsInContext;All shape representations that are defined in the same representation context. +2182;ContextOfItems;Definition of the representation context for which the different subtypes of representation are valid. +2183;RepresentationIdentifier;The optional identifier of the representation as used within a project. +2184;RepresentationType;" +The description of the type of a representation context. The representation type defines the type of geometry or topology used for representing the product representation. More information is given at the subtypes IfcShapeRepresentation and IfcTopologyRepresentation.
+The supported values for context type are to be specified by implementers agreements. +
" +2185;Items;Set of geometric representation items that are defined for this representation. +2186;RepresentationMap;" +Use of the representation within an IfcRepresentationMap. If used, this IfcRepresentation may be assigned to many representations as one of its Items using an IfcMappedItem. Using IfcRepresentationMap is the way to share one representation (often of type IfcShapeRepresentation) by many products. +
+IFC2x Edition 3 CHANGE  The inverse attribute LayerAssignments has been added. +
+
" +2187;LayerAssignments;"Assignment of the whole representation to a single or multiple layer(s). The LayerAssigments can be overridden by LayerAssigments of the IfcRepresentationItem's within the list of Items. +
NOTE  Implementation agreements can restrict the maximum number of layer assignments to 1.
+IFC2x Edition 3 CHANGE  The inverse attribute LayerAssignments has been added. +
+
" +2188;OfProductRepresentation;" +Reference to the product representations to which this individual representation applies. In most cases it is the reference to one or many product shapes, to which this shape representation is applicable. +
+IFC2x4 CHANGE Inverse relationship cardinality relaxed to be 0:N. +
+
" +2196;OfShapeAspect;Reference to the shape aspect, for which it is the shape representation. +2208;ShapeRepresentations;"List of shape representations. Each member defines a valid representation of a particular type within a particular representation context as being an aspect (or part) of a product definition. +
IFC2x Edition 3 CHANGE  The data type has been changed from IfcShapeRepresentation to IfcShapeModel with upward compatibility
+
" +2209;Name;"The word or group of words by which the shape aspect is known. It is a tag to indicate the particular semantic of a component within the product definition shape, used to provide meaning. Example: use the tag ""Glazing"" to define which component of a window shape defines the glazing area." +2210;Description;The word or group of words that characterize the shape aspect. It can be used to add additional meaning to the name of the aspect. +2211;ProductDefinitional;"An indication that the shape aspect is on the physical boundary of the product definition shape. If the value of this attribute is TRUE, it shall be asserted that the shape aspect being identified is on such a boundary. If the value is FALSE, it shall be asserted that the shape aspect being identified is not on such a boundary. If the value is UNKNOWN, it shall be asserted that it is not known whether or not the shape aspect being identified is on such a boundary. +--- +EXAMPLE: Would be FALSE for a center line, identified as shape aspect; would be TRUE for a cantilever. +---" +2212;PartOfProductDefinitionShape;Reference to the product definition shape of which this class is an aspect. +2214;ShapeOfProduct;" +The IfcProductDefinitionShape shall be used to provide a representation for a single instance of IfcProduct. +
+ IFC2x3 CHANGE New inverse attribute.
+IFC2x4 CHANGE Inverse relationship cardinality relaxed to be 1:N. +
+
" +2215;HasShapeAspects;Reference to the shape aspect that represents part of the shape or its feature distinctively. +2220;Name;The word or group of words by which the product representation is known. +2221;Description;The word or group of words that characterize the product representation. It can be used to add additional meaning to the name of the product representation. +2222;Representations;Contained list of representations (including shape representations). Each member defines a valid representation of a particular type within a particular representation context. +2224;RepresentedMaterial;Reference to the material to which the representation applies. +2227;ParentContext;Parent context from which the sub context derives its world coordinate system, precision, space coordinate dimension and true north. +2228;TargetScale;" +The target plot scale of the representation +to which this representation context applies. +
Scale indicates the target plot scale for +the representation sub context, all annotation styles are given in plot +dimensions according to this target plot scale.
+If multiple instances of IfcGeometricRepresentationSubContext +are given having the same TargetView value, the target plot scale +applies up to the next smaller scale, or up to unlimited small scale. +
+
+Note: Scale 1:100 (given as 0.01 within TargetScale) +is bigger then 1:200 (given as 0.005 within TargetScale). +
+
" +2229;TargetView;Target view of the representation to which this representation context applies. +2230;UserDefinedTargetView;User defined target view, this attribute value shall be given, if the TargetView attribute is set to USERDEFINED. +2231;WorldCoordinateSystem; +2232;CoordinateSpaceDimension; +2233;TrueNorth; +2234;Precision; +2260;Name;"Name by which the coordinate reference system is identified. +
Note  The name shall be taken from the list recognized by the European Petroleum Survey Group EPSG. +
+
" +2261;Description;"Informal description of this coordinate reference system.
" +2262;GeodeticDatum;" +Name by which this datum is identified. The geodetic datum is associated with the coordinate reference system and indicates the shape and size of the rotation ellipsoid and this ellipsoid's connection and orientation to the actual globe/earth. Examples for geodetic datums include: +
    +
  • ED50
  • +
  • EUREF89
  • +
  • WSG84
  • +
      + " +2263;VerticalDatum;"Name by which the vertical datum is identified. The vertical datum is associated with the height axis of the coordinate reference system and indicates the reference plane and fundamental point defining the origin of a height system. Examples for vertical datums include: +
        +
      • height above mean sea level at Dover in 1952
      • +
      • other sea levels
      • +
          +" +2265;MapProjection;"Name by which the map projection is identified. +
            +
          • UTM
          • +
          • Gaus-Krueger
          • +
              +" +2266;MapZone;"Name by which the map zone, relating to the MapProjection, is identified. Examples are +
                +
              • for UTM, the zone number, like 32 for UTM32
              • +
              • for Gaus-Krueger, the zones of longitudinal width, like 3'
              • +
                  +" +2267;MapUnit;"Unit of the coordinate axes composing the map coordinate system. +
                  NOTE  Only length measures are in scope and all two or three axes of the map coordinate system shall have the same length unit. + +" +2271;SourceCRS;Source coordinate reference system for the operation. +2272;TargetCRS;Target coordinate reference system for the operation. +2274;Eastings;"Specifies the location along the easting of the coordinate system of the target map coordinate reference system. +
                  NOTE  for right-handed Cartesian coordinate systems this would establish the location along the x axis
                  +
                  " +2275;Northings;"Specifies the location along the northing of the coordinate system of the target map coordinate reference system. +
                  NOTE  for right-handed Cartesian coordinate systems this would establish the location along the y axis
                  +
                  " +2276;OrthogonalHeight;"Orthogonal height relativ to the vertical datum specified. +
                  NOTE  for right-handed Cartesian coordinate systems this would establish the location along the z axis
                  +" +2277;XAxisAbscissa;" Specifies the value along the easing axis of the end point of a vector indicating the position of the local x axis of the engineering coordinate reference system. +
                  NOTE  for right-handed Cartesian coordinate systems this would establish the location along the x axis
                  +NOTE  together with the XAxisOrdinate it provides the direction of the local x axis within the horizontal plane of the map coordinate system
                  +
                  " +2278;XAxisOrdinate;" Specifies the value along the northing axis of the end point of a vector indicating the position of the local x axis of the engineering coordinate reference system. +
                  NOTE  for right-handed Cartesian coordinate systems this would establish the location along the y axis
                  +NOTE  together with the XAxisAbscissa it provides the direction of the local x axis within the horizontal plane of the map coordinate system
                  +
                  " +2279;Scale;"Scale to be used, when the units of the CRS are not identical to the units of the engineering coordinate system. If omited, the value of 1.0 is assumed. +" +2287;Name;Optionally defines a name for this load. +2289;Values;List of load or result values. +2290;Locations;Locations of the load samples or result samples, given within the local coordinate system defined by the instance which uses this resource object. Each item in the list of locations pertains to the values list item at the same list index. This attribute is optional for configurations in which the locations are implicitly known from higher-level definitions. +2301;ForceX;Force value in x-direction. +2302;ForceY;Force value in y-direction. +2303;ForceZ;Force value in z-direction. +2304;MomentX;Moment about the x-axis. +2305;MomentY;Moment about the y-axis. +2306;MomentZ;Moment about the z-axis. +2308;WarpingMoment;The warping moment at the point load. +2310;LinearForceX;Linear force value in x-direction. +2311;LinearForceY;Linear force value in y-direction. +2312;LinearForceZ;Linear force value in z-direction. +2313;LinearMomentX;Linear moment about the x-axis. +2314;LinearMomentY;Linear moment about the y-axis. +2315;LinearMomentZ;Linear moment about the z-axis. +2317;PlanarForceX;Planar force value in x-direction. +2318;PlanarForceY;Planar force value in y-direction. +2319;PlanarForceZ;Planar force value in z-direction. +2322;DisplacementX;Displacement in x-direction. +2323;DisplacementY;Displacement in y-direction. +2324;DisplacementZ;Displacement in z-direction. +2325;RotationalDisplacementRX;Rotation about the x-axis. +2326;RotationalDisplacementRY;Rotation about the y-axis. +2327;RotationalDisplacementRZ;Rotation about the z-axis. +2329;Distortion;The distortion curvature (warping, i.e. a cross-sectional deplanation) given to the displacement load. +2331;DeltaTConstant;" + +Temperature change which affects the complete section of the structural member, or the uniform portion of a non-uniform temperature change. + +
                  A positive value describes an increase in temperature. I.e. a positive constant temperature change causes elongation of a member, or compression in the member if there are respective restraints.
                  + +
                  " +2332;DeltaTY;" + +Non-uniform temperature change, specified as the difference of the temperature change at the outer fibre of the positive y direction minus the temperature change at the outer fibre of the negative y direction of the analysis member. + +
                  I.e. a positive non-uniform temperature change in y induces a negative curvature of the member about z, or a positive bending moment about z if there are respective restraints. y and z are local member axes.
                  + +
                  " +2333;DeltaTZ;" + +Non-uniform temperature change, specified as the difference of the temperature change at the outer fibre of the positive z direction minus the temperature change at the outer fibre of the negative z direction of the analysis member. + +
                  I.e. a positive non-uniform temperature change in z induces a positive curvature of the member about y, or a negative bending moment about y if there are respective restraints. y and z are local member axes.
                  + +
                  " +2335;SurfaceReinforcement1;Reinforcement at the face of the member which is located at the side of the positive local z direction of the surface member. Specified as area per length, e.g. square metre per metre (hence length measure, e.g. metre). The reinforcement area may be specified for two or three directions of reinforcement bars. +2336;SurfaceReinforcement2;Reinforcement at the face of the member which is located at the side of the negative local z direction of the surface member. Specified as area per length, e.g. square metre per metre (hence length measure, e.g. metre). The reinforcement area may be specified for two or three directions of reinforcement bars. +2337;ShearReinforcement;Shear reinforcement. Specified as area per area, e.g. square metre per square metre (hence ratio measure, i.e. unitless). +2346;Name;Optionally defines a name for this boundary condition. +2349;TranslationalStiffnessX;Translational stiffness value in x-direction of the coordinate system defined by the instance which uses this resource object. +2350;TranslationalStiffnessY;Translational stiffness value in y-direction of the coordinate system defined by the instance which uses this resource object. +2351;TranslationalStiffnessZ;Translational stiffness value in z-direction of the coordinate system defined by the instance which uses this resource object. +2352;RotationalStiffnessX;Rotational stiffness value about the x-axis of the coordinate system defined by the instance which uses this resource object. +2353;RotationalStiffnessY;Rotational stiffness value about the y-axis of the coordinate system defined by the instance which uses this resource object. +2354;RotationalStiffnessZ;Rotational stiffness value about the z-axis of the coordinate system defined by the instance which uses this resource object. +2356;WarpingStiffness;Defines the warping stiffness value. +2367;TranslationalStiffnessByLengthX;Translational stiffness value in x-direction of the coordinate system defined by the instance which uses this resource object. +2368;TranslationalStiffnessByLengthY;Translational stiffness value in y-direction of the coordinate system defined by the instance which uses this resource object. +2369;TranslationalStiffnessByLengthZ;Translational stiffness value in z-direction of the coordinate system defined by the instance which uses this resource object. +2370;RotationalStiffnessByLengthX;Rotational stiffness value about the x-axis of the coordinate system defined by the instance which uses this resource object. +2371;RotationalStiffnessByLengthY;Rotational stiffness value about the y-axis of the coordinate system defined by the instance which uses this resource object. +2372;RotationalStiffnessByLengthZ;Rotational stiffness value about the z-axis of the coordinate system defined by the instance which uses this resource object. +2380;TranslationalStiffnessByAreaX;Translational stiffness value in x-direction of the coordinate system defined by the instance which uses this resource object. +2381;TranslationalStiffnessByAreaY;Translational stiffness value in y-direction of the coordinate system defined by the instance which uses this resource object. +2382;TranslationalStiffnessByAreaZ;Translational stiffness value in z-direction of the coordinate system defined by the instance which uses this resource object. +2387;SlippageX;Slippage in x-direction of the coordinate system defined by the instance which uses this resource object. +2388;SlippageY;Slippage in y-direction of the coordinate system defined by the instance which uses this resource object. +2389;SlippageZ;Slippage in z-direction of the coordinate system defined by the instance which uses this resource object. +2393;Name;Optionally defines a name for this connection condition. +2395;TensionFailureX;Tension force in x-direction leading to failure of the connection. +2396;TensionFailureY;Tension force in y-direction leading to failure of the connection. +2397;TensionFailureZ;Tension force in z-direction leading to failure of the connection. +2398;CompressionFailureX;Compression force in x-direction leading to failure of the connection. +2399;CompressionFailureY;Compression force in y-direction leading to failure of the connection. +2400;CompressionFailureZ;Compression force in z-direction leading to failure of the connection. +2406;CfsFaces;The set of faces arcwise connected along common edges or vertices. +2419;EdgeStart;"Start point (vertex) of the edge. " +2420;EdgeEnd;"End point (vertex) of the edge. The same vertex can be used for both EdgeStart and EdgeEnd. " +2422;EdgeElement;"Edge entity used to construct this oriented edge. " +2423;Orientation;"BOOLEAN, If TRUE the topological orientation as used coincides with the orientation from start vertex to end vertex of the edge element. If FALSE otherwise. " +2424;EdgeStart;"The start vertex of the oriented edge. It derives from the vertices of the edge element after taking account of the orientation. " +2425;EdgeEnd;"The end vertex of the oriented edge. It derives from the vertices of the edge element after taking account of the orientation. " +2430;VertexGeometry;The geometric point, which defines the position in geometric space of the vertex. +2432;EdgeGeometry;"The curve which defines the shape and spatial location of the edge. This curve may be unbounded and is implicitly trimmed by the vertices of the edge; this defines the edge domain. Multiple edges can reference the same curve." +2433;SameSense;"This logical flag indicates whether (TRUE), or not (FALSE) the senses of the edge and the curve defining the edge geometry are the same. The sense of an edge is from the edge start vertex to the edge end vertex; the sense of a curve is in the direction of increasing parameter." +2435;ParentEdge;The Edge, or Subedge, which contains the Subedge. +2438;Bounds;"Boundaries of the face. " +2442;FaceSurface;The surface which defines the internal shape of the face. This surface may be unbounded. The domain of the face is defined by this surface and the bounding loops in the inherited attribute SELF\FaceBounds. +2443;SameSense;This flag indicates whether the sense of the surface normal agrees with (TRUE), or opposes (FALSE), the sense of the topological normal to the face. +2450;Bound;"The loop which will be used as a face boundary. " +2451;Orientation;"This indicated whether (TRUE) or not (FALSE) the loop has the same sense when used to bound the face as when first defined. If sense is FALSE the senses of all its component oriented edges are implicitly reversed when used in the face. " +2458;Polygon;List of points defining the loop. There are no repeated points in the list. +2461;LoopVertex;The vertex which defines the entire loop. +2463;EdgeList;A list of oriented edge entities which are concatenated together to form this path. +2464;Ne;The number of elements in the edge list. +2468;EdgeList;The list of oriented edges which are concatenated together to form this path. +2479;Status;" + Current status of the task. +
                  + NOTE: Particular values for status are not + specified, these should be determined and agreed by local + usage. Examples of possible status values include 'Not Yet + Started', 'Started', 'Completed'. +
                  +
                  " +2480;WorkMethod;" + The method of work used in carrying out a task. +
                  + NOTE: This attribute should + not be used if the work method is specified for the + IfcTaskType +
                  +
                  " +2481;IsMilestone;" + Identifies whether a task is a milestone task (=TRUE) or not + (= FALSE). +
                  + NOTE: In small project planning applications, + a milestone task may be understood to be a task having no + duration. As such, it represents a singular point in + time. +
                  +
                  " +2482;Priority;" + A value that indicates the relative priority of the task (in + comparison to the priorities of other tasks). +" +2483;TaskTime;" + Time related information for the task. +
                  +

                  + Added in IFC 2x4 +

                  +
                  +
                  " +2484;PredefinedType;" + Identifies the predefined types of a task from which + the type required may be set. +
                  +

                  + Added in IFC 2x4 +

                  +
                  +
                  " +2503;PredefinedType;" + Identifies the predefined types of a procedure from which + the type required may be set. +" +2517;PredefinedType;" + Identifies the predefined types of an event from which + the type required may be set. +" +2518;EventTriggerType;" + Identifies the predefined types of event trigger from which + the type required may be set. +" +2519;UserDefinedEventTriggerType;" + A user defined event trigger type, the value of which is + asserted when the value of an event trigger type is declared + as USERDEFINED. +" +2520;EventOccurenceTime;" + The date and/or time at which an event occurs. +" +2539;CreationDate;" + The date that the plan is created. +" +2540;Creators;" + The authors of the work plan. +" +2541;Purpose;" + A description of the purpose of the work schedule. +" +2542;Duration;" + The total duration of the entire work schedule. +" +2543;TotalFloat;" + The total time float of the entire work schedule. +" +2544;StartTime;" + The start time of the schedule. +" +2545;FinishTime;" + The finish time of the schedule. +" +2547;PredefinedType;" + Identifies the predefined types of a work plan from which + the type required may be set. +" +2556;PredefinedType;" + Identifies the predefined types of a work schedule from which + the type required may be set. +" +2565;WorkingTimes;" + Set of times periods that are regarded as an initial set-up + of working times. Exception times can then further restrict + these working times. + " +2566;ExceptionTimes;" + Set of times periods that define exceptions (non-working + times) for the given working times including the base + calendar, if provided. +" +2567;PredefinedType;" + Identifies the predefined types of a work calendar from which + the type required may be set. +
                  +

                  + Added in IFC 2x4 +

                  +
                  +
                  " +2576;RelatingProcess;" + Reference to the process, that is the predecessor. + " +2577;RelatedProcess;" + Reference to the process, that is the successor. + " +2578;TimeLag;" + Time duration of the sequence, it is the time lag between the + predecessor and the successor as specified by the + SequenceType. + " +2579;SequenceType;" + The way in which the time lag applies to the sequence. + " +2580;UserDefinedSequenceType;" + Allows for specification of user defined type of the sequence + beyond the enumeration values (START_START, START_FINISH, + FINISH_START, FINISH_FINISH) provided by SequenceType + attribute of type IfcSequenceEnum. When a value is + provided for attribute UserDefinedSequenceType in + parallel the attribute SequenceType shall have + enumeration value USERDEFINED. +
                  +

                  + Added in IFC 2x4 +

                  +
                  +
                  " +2591;PredefinedType;" + Identifies the predefined types of a task type from which + the type required may be set. +" +2592;WorkMethod;" + The method of work used in carrying out a task. +" +2595;PredefinedType;" + Identifies the predefined types of a procedure from which + the type required may be set. +" +2598;PredefinedType;" + Identifies the predefined types of an event from which + the type required may be set. +" +2599;EventTriggerType;" + Identifies the predefined types of event trigger from which + the type required may be set. +" +2600;UserDefinedEventTriggerType;" + A user defined event trigger type, the value of which + is asserted when the value of an event trigger type is + declared as USERDEFINED. +" +2605;PredefinedType;" +Predefined generic type for a cost schedule that is specified in an enumeration. There may be a property set given specifically for the predefined types. + +
                  +IFC2x4 CHANGE The attribute has been made optional. +
                  + +
                  " +2606;Status;" +The current status of a cost schedule. Examples of status values that might be used for a cost schedule status include: +
                    +
                  • PLANNED
                  • +
                  • APPROVED
                  • +
                  • AGREED
                  • +
                  • ISSUED
                  • +
                  • STARTED
                  • +
                  + +
                  " +2607;SubmittedOn;" +The date and time on which the cost schedule was submitted. +
                  + + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
                  +
                  " +2608;UpdateDate;" +The date and time that this cost schedule is updated; this allows tracking the schedule history. +
                  + + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
                  +
                  " +2620;PredefinedType;" +Predefined generic type for a project order that is specified in an enumeration. There may be a property set given specificly for the predefined types. + +
                  +IFC2x4 CHANGE The attribute has been made optional. +
                  + +
                  " +2621;Status;"The current status of a project order.Examples of status values that might be used for a project order status include: +
                    +
                  • PLANNED
                  • +
                  • REQUESTED
                  • +
                  • APPROVED
                  • +
                  • ISSUED
                  • +
                  • STARTED
                  • +
                  • DELAYED
                  • +
                  • DONE
                  • +
                  +
                  " +2622;LongDescription;" +A detailed description of the project order describing the work to be completed. +" +2632;PredefinedType;" +Predefined generic type for a cost item that is specified in an enumeration. There may be a property set given specificly for the predefined types. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2633;CostValues;" +Component costs for which the total cost for the cost item is calculated, and then multiplied by the total CostQuantities if provided. + +If CostQuantities is provided then values indicate unit costs, otherwise values indicate total costs. + +For calculation purposes, the cost values may be directly added unless they have qualifications. Cost values with qualifications (e.g. IfcCostValue.ApplicableDate, IfcCostValue.FixedUntilDate) should be excluded from such calculation if they do not apply. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2634;CostQuantities;" +Component quantities of the same type for which the total quantity for the cost item is calculated as the sum. +
                  +IFC2x4 CHANGE The attribute has been added. +
                  +
                  + + + " +2639;PredefinedType;" +Identifies the predefined types of permit that can be granted. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2640;Status;" +The status currently assigned to the permit. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2641;LongDescription;" +Detailed description of the request. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2649;PredefinedType;" +Identifies the predefined type of sources through which a request can be made. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2650;Status;" +The status currently assigned to the request. Possible values include:
                  +Hold: wait to see if further requests are received before deciding on action
                  +NoAction: no action is required on this request
                  +Schedule: plan action to take place as part of maintenance or other task planning/scheduling
                  +Urgent: take action immediately
                  + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2651;LongDescription;" +Detailed description of the permit. + +
                  +IFC2x4 CHANGE The attribute has been added. +
                  + +
                  " +2668;ResourceConsumption;" +Indicates how the resource is consumed or occupied during its use in a process. Production-based consumption is indicated by CONSUMED, PARTIALLYCONSUMED, or NOTCONSUMED, where QuantityProduced refers to a quantity on the IfcProduct to which the assigned IfcProcess is assigned. Duration-based occupation is indicated by OCCUPIED, PARTIALLYOCCUPIED, or NOTOCCUPIED, where QuantityProduced refers to a quantity on the IfcProcess to which the resource is assigned. +

                  +
                  " +2669;BaseQuantityConsumed;" +The basic (i.e. default, or recommended) unit that should be used for measuring the amount of the resource and the relative quantity of the resource fully or partially consumed. For labor and equipment resources, this always refers to an IfcDuration quantity, typically 1 hour. For material resources, this always refers to a spatial quantity (e.g. IfcVolumeMeasure). + +
                  +IFC2x4 NOTE: The attribute BaseQuantityConsumed has been renamed from BaseQuantity. +
                  + +

                  +
                  " +2670;BaseQuantityProduced;" +The basic (i.e. default, or recommended) unit that should be used for measuring the amount of the output (e.g. product volume) and the relative quantity of the output produced per input BaseQuantityConsumed. If the resource is not assigned to a task, then this value should be null. For production-based resources (e.g. carpentry labor), this value refers to a product-based spatial quantity (e.g. volume). For duration-based resources (e.g. safety inspector, fuel for equipment), this value refers to a task-based time quantity (IfcDuration). + +
                  IFC2x4 New attribute +
                  + +

                  + +
                  " +2671;CostRatesConsumed;" +Indicates the unit costs for which accrued cost amounts should be calculated. Such unit costs may be split into Name designations (e.g. 'Standard', 'Overtime'), and may contain a hierarchy of cost values that apply at different dates (using IfcCostValue.ApplicableDate and IfcCostValue.FixedUntilDate). The order of cost rates is significant; time series that break out Costs and Work will list such values in corresponding sequence - see the Time Series Use Definition for detail. + +
                  IFC2x4 New attribute +
                  + +

                  +
                  " +2672;QuantityProduced;" +Identifies the quantity for which the BaseQuantityProduced applies. The Name of the IfcPhysicalQuantity identifies the quantity definition being measured, e.g. ""GrossVolume"". For work-based resources (e.g. carpentry labor), this value refers to a quantity on IfcProduct(s) to which the assigned IfcTask is assigned. For duration-based resources (e.g. safety inspector, fuel for equipment), this value refers to a quantity on the assigned IfcTask. + +
                  NOTE: The referenced instance may or may not be the same instance as that on the assigned product or process, as references to non-IfcRoot entities do not imply any semantic relationship, just value sharing (interning). +
                  + +
                  IFC2x4 New attribute +
                  + +

                  +
                  " +2673;ResourceTime;" +Indicates the work, usage, and times scheduled and completed. Some attributes on this object may have associated constraints or time series; see documentation of IfcResourceTime for specific usage. If the resource is nested, then certain values may be calculated based on the component resources as indicated at IfcResourceTime. + +
                  IFC2x4 New attribute +
                  + +

                  +
                  " +2674;ResourceCost;" +Indicates the costs budgeted and realized. Some attributes on this object may have associated time series; see documentation of IfcResourceCost for specific usage. If the resource is nested, then certain values may be calculated based on the component resources as indicated at IfcResourceCost. + +
                  IFC2x4 New attribute +
                  + +

                  +
                  " +2676;PredefinedType;" +Defines types of construction equipment resources. +
                  IFC2x4 New attribute +
                  +

                  +
                  " +2690;PredefinedType;" +Defines types of labor resources. +
                  IFC2x4 New attribute +

                  +
                  " +2715;PredefinedType;" +Defines types of crew resources. +
                  IFC2x4 New attribute +
                  +

                  +
                  " +2723;PredefinedType;" +Defines types of subcontract resources. +
                  IFC2x4 New attribute +
                  +

                  +
                  " +2731;PredefinedType;" +Defines types of construction product resources. +
                  IFC2x4 New attribute +
                  +

                  +
                  " +2739;PredefinedType;" +Defines types of construction material resources. +
                  IFC2x4 New attribute +
                  +

                  +
                  " +2769;ResourceConsumption;" +Indicates how the resource is consumed or occupied during its use in a process. Production-based consumption is indicated by CONSUMED, PARTIALLYCONSUMED, or NOTCONSUMED, where QuantityProduced refers to a quantity applicable to the IfcTypeProduct to which the assigned IfcTypeProcess is assigned. Duration-based occupation is indicated by OCCUPIED, PARTIALLYOCCUPIED, or NOTOCCUPIED, where QuantityProduced refers to a quantity applicable to the the IfcTypeProcess to which the resource is assigned.

                  +
                  " +2770;BaseQuantityConsumed;" +The basic (i.e. default, or recommended) unit that should be used for measuring the amount of the resource and the relative quantity of the resource fully or partially consumed. For labor and equipment resources, this always refers to an IfcDuration quantity, typically 1 hour. For material resources, this always refers to a spatial quantity (e.g. IfcVolumeMeasure). + +

                  +
                  " +2771;BaseQuantityProduced;" +The basic (i.e. default, or recommended) unit that should be used for measuring the amount of the output (e.g. product volume) and the relative quantity of the output produced per input BaseQuantityConsumed. If the resource type is not assigned to a task type, then this value should be null. For production-based resources (e.g. carpentry labor), this value refers to a product-based spatial quantity (e.g. volume). For duration-based resources (e.g. safety inspector, fuel for equipment), this value refers to a task-based time quantity (IfcDuration). + +

                  + +
                  " +2772;CostRatesConsumed;" +Indicates the unit costs for which accrued cost amounts should be calculated. Such unit costs may be split into Name designations (e.g. 'Standard', 'Overtime'), and may contain a hierarchy of cost values that apply at different dates (using IfcCostValue.ApplicableDate and IfcCostValue.FixedUntilDate). The order of cost rates is significant; resource occurrences having time series that break out Costs and Work will list such values in corresponding sequence - see the Time Series Use Definition at IfcConstructionResource for detail. + +

                  +
                  " +2773;QuantityProduced;" +Identifies the quantity for which the BaseQuantityProduced applies. The Name of the IfcPhysicalQuantity identifies the quantity definition being measured, e.g. ""GrossVolume"". For production-based resources (e.g. carpentry labor), this value refers to quantities on IfcProduct(s) to which the assigned IfcTask is assigned. For duration-based resources (e.g. safety inspector, fuel for equipment), this value refers to quantities that may be assigned to occurrences of the assigned IfcTaskType. + +

                  +
                  " +2775;PredefinedType;" +Defines types of crew resources. +

                  +
                  " +2778;PredefinedType;" +Defines types of labor resources. +

                  +
                  " +2781;PredefinedType;" +Defines types of subcontract resources. +

                  +
                  " +2784;PredefinedType;" +Defines types of construction material resources. +

                  +
                  " +2787;PredefinedType;" +Defines types of construction equipment resources. +

                  +
                  " +2790;PredefinedType;" +Defines types of construction product resources. +

                  +
                  " +2794;PredefinedType;

                  Identifies the predefined types of motor connection from which the type required may be set.

                  +2797;PredefinedType;

                  Identifies the predefined types of outlet from which the type required may be set.

                  +2808;PredefinedType;

                  Identifies the predefined types of electrical appliance from which the type required may be set.

                  +2830;PredefinedType;

                  Identifies the predefined types of light fixture from which the type required may be set.

                  +2839;PredefinedType;

                  Identifies the predefined types of lamp from which the type required may be set.

                  +2854;PredefinedType;

                  Identifies the predefined types of audio-visual appliance from which the type required may be set.

                  +2871;PredefinedType;

                  Identifies the predefined types of communications appliance from which the type required may be set.

                  +2889;PredefinedType;

                  Identifies the predefined types of switch from which the type required may be set.

                  +2904;PredefinedType;

                  Identifies the predefined types of electrical time control from which the type required may be set.

                  +2913;PredefinedType;

                  Identifies the predefined types of protective device from which the type required may be set.

                  +2926;PredefinedType;

                  Identifies the predefined types of electric distribution type from which the type required may be set.

                  +2936;PredefinedType;

                  Identifies the predefined types of cable carrier fitting from which the type required may be set.

                  +2946;PredefinedType;

                  Identifies the predefined types of junction boxes from which the type required may be set.

                  +2954;PredefinedType;

                  Identifies the predefined types of cable fitting from which the type required may be set.

                  +2965;PredefinedType;

                  Identifies the predefined types of electric flow storage devices from which the type required may be set.

                  +2976;PredefinedType;

                  Identifies the predefined types of cable segment from which the type required may be set.

                  +2986;PredefinedType;

                  Identifies the predefined types of cable carrier segment from which the type required may be set.

                  +2996;PredefinedType;

                  Identifies the predefined types of protective device tripping unit types from which the type required may be set.

                  +3006;PredefinedType;

                  Identifies the predefined types of cable segment from which the type required may be set.

                  +3010;PredefinedType;

                  Identifies the predefined types of cable carrier segment from which the type required may be set.

                  +3014;PredefinedType;

                  Identifies the predefined types of cable carrier fitting from which the type required may be set.

                  +3018;PredefinedType;

                  Identifies the predefined types of cable fitting from which the type required may be set.

                  +3022;PredefinedType; +3026;PredefinedType; +3030;PredefinedType; +3034;PredefinedType; +3038;PredefinedType; +3042;PredefinedType; +3046;PredefinedType; +3050;PredefinedType; +3054;PredefinedType; +3058;PredefinedType; +3062;PredefinedType; +3066;PredefinedType; +3070;PredefinedType; +3082;PredefinedType; +3092;PredefinedType; +3104;PredefinedType; +3114;PredefinedType; +3123;PredefinedType; +3127;PredefinedType;

                  Identifies the predefined types of electric generators from which the type required may be set.

                  +3130;PredefinedType;

                  Identifies the predefined types of transformer from which the type required may be set.

                  +3133;PredefinedType;

                  Identifies the predefined types of electric motor from which the type required may be set.

                  +3136;PredefinedType; +3140;PredefinedType;"Defines the type of air to air heat recovery device. " +3155;PredefinedType;Defines types of boilers. +3163;PredefinedType; +3169;PredefinedType;Defines the typical types of chillers (e.g., air-cooled, water-cooled, etc.). +3178;PredefinedType;"Defines typical types of coils (e.g., Cooling, Heating, etc.) " +3191;PredefinedType;Defines the type of condenser. +3204;PredefinedType;Defines the type of cooled beam. +3212;PredefinedType;Defines the typical types of cooling towers (e.g., OpenTower, ClosedTower, CrossFlow, etc.). +3221;PredefinedType;Defines the type of evaporative cooler. +3236;PredefinedType;Defines the type of evaporator. +3248;PredefinedType;Defines the basic types of heat exchanger (e.g., plate, shell and tube, etc.). +3256;PredefinedType;Defines the type of humidifier. +3275;PredefinedType;Defines the type of tube bundle. +3282;PredefinedType;The type of unitary equipment. +3293;PredefinedType; +3301;PredefinedType;Defines the type of fan typically used in building services. +3314;PredefinedType;Defines the type of compressor (e.g., hermetic, reciprocating, etc.). +3335;PredefinedType;Defines the type of pump typically used in building services. +3348;PredefinedType;Type of damper. +3365;PredefinedType;The air terminal box type. +3374;PredefinedType;The type of valve. +3401;PredefinedType;Defines the type of flow meter. +3411;PredefinedType;The type of duct fitting. +3424;PredefinedType;The type of pipe fitting. +3437;PredefinedType;Defines the type of tank. +3450;PredefinedType;The type of duct silencer. +3459;PredefinedType;The type of air filter. +3471;PredefinedType;The type of pipe segment. +3482;PredefinedType;The type of duct segment. +3490;PredefinedType; +3494;PredefinedType; +3498;PredefinedType; +3502;PredefinedType; +3506;PredefinedType; +3510;PredefinedType; +3514;PredefinedType; +3518;PredefinedType; +3522;PredefinedType; +3526;PredefinedType; +3537;PredefinedType; +3546;PredefinedType; +3558;PredefinedType; +3562;PredefinedType; +3566;PredefinedType; +3570;PredefinedType; +3574;PredefinedType; +3578;PredefinedType; +3582;PredefinedType; +3586;PredefinedType; +3590;PredefinedType; +3594;PredefinedType; +3598;PredefinedType; +3602;PredefinedType; +3606;PredefinedType; +3610;PredefinedType; +3614;PredefinedType; +3618;PredefinedType; +3622;PredefinedType; +3626;PredefinedType; +3630;PredefinedType; +3634;PredefinedType; +3638;PredefinedType; +3641;PredefinedType;Enumeration of possible types of space heater (e.g., baseboard heater, convector, radiator, etc.). +3644;PredefinedType; +3647;PredefinedType; +3656;PredefinedType;Defines the type of vibration isolator. +3660;PredefinedType;

                  Identifies the predefined types of waste terminal from which the type required may be set.

                  +3673;PredefinedType;

                  Identifies the predefined types of stack terminal from which the type required may be set.

                  +3682;PredefinedType;

                  Identifies the predefined types of sanitary terminal from which the type required may be set.

                  +3698;PredefinedType;

                  Identifies the predefined types of fire suppression terminal from which the type required may be set.

                  +3709;PredefinedType; +3713;PredefinedType; +3717;PredefinedType; +3721;PredefinedType; +3725;PredefinedType; +3735;PredefinedType; +3743;Source;" +Source (or publisher) for this classification. +
                  + +NOTE that the source of the classification means the person or organization that was the original author or the person or organization currently acting as the publisher. + +
                  +
                  " +3744;Edition;" +The edition or version of the classification system from which the classification notation is derived. +
                  + + NOTE the version labeling system is specific to the classification system. +
                  + + + IFC2x4 CHANGE The attribute has been changed to be optional. + + +
                  +
                  " +3745;EditionDate;"The date on which the edition of the classification used became valid. +
                  + +NOTE The indication of edition may be sufficient to identify the classification source uniquely but the edition date is provided as an optional attribute to enable more precise identification where required. + +
                  +
                  + + +IFC2x4 CHANGE The data type has been changed to IfcDate, the date string according to ISO8601. + + +
                  +
                  " +3746;Name;" +The name or label by which the classification used is normally known. +
                  + + NOTE Examples of names include CI/SfB, Masterformat, BSAB, Uniclass, STABU, DIN276, DIN277 etc. + +
                  +
                  " +3747;Description;" +Additional description provided for the classification. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3748;Location;"Resource identifier or locator, provided as URI, URN or URL, of the classification. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +" +3749;ReferenceTokens;" +The delimiter tokens that are used to mark the boundaries of individual facets (substrings) in a classification reference. +

                  +This typically applies then the IfcClassification is used in +conjuction with IfcClassificationReference's. If only one ReferenceToken is provided, it applies to all boundaries of individual facets, if more than one ReferenceToken are provided, the first token applies to the first boundary, the second token to the second boundary, and the nth token to the nth and any additional boundary. +
                  + +NOTE  Tokens are typically recommended within the classification itself and each token will have a particular role. +
                  + +EXAMPLE 1  To indicate that the facet delimiter used for DIN277-2 reference key ""2.1"" (""Office rooms"") is ""."", a single ReferenceToken ['.'] is provided. To indicate that the facet delimiter used for Omniclass Table 13 (space by function) reference key ""13-15 11 34 11"" (""Office"") are ""-"" and "" "", two ReferenceToken's ['-', ' '] are provided. +
                  + +EXAMPLE 2  The use of ReferenceTokens can also be extended to include masks. The use need to be agreed in view definitions or implementer agreements that stipulates a ""mask syntax"" that should be used. + +
                  +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3750;ClassificationForObjects;" +The classification with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3751;HasReferences;" +The classification references to which the classification applies. It can either be the final classification notation, or an intermediate classification item. +" +3757;Name;The name which is used to identify the library. +3758;Version;Identifier for the library version used for reference. +3759;Publisher;Information of the organization that acts as the library publisher. +3760;VersionDate;" +Date of the referenced version of the library. +
                  + + +IFC2x4 CHANGE  The data type has been changed to IfcDate, the date string according to ISO8601. + + +
                  +
                  " +3761;Location;" +Resource identifier or locator, provided as URI, URN or URL, of the library information for online references. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3762;LibraryInfoForObjects;" +The library information with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3763;HasLibraryReferences;The library references to which the library information applies. +3766;Description;" +Additional description provided for the library reference. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3767;Language;"The language in which a library reference is expressed. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3768;ReferencedLibrary;The library information that is being referenced. +3769;LibraryRefForObjects;" +The library reference with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3774;Location;" +Location, where the external source (classification, document or library) can be accessed by electronic means. The electronic location is provided as an URI, and would normally be given as an URL location string. +

                  + + IFC2x4 CHANGE  The data type has been changed from IfcLabel to IfcURIReference. + +

                  + " +3775;Identification;" +The Identification provides a unique identifier of the referenced item within the external source (classification, document or library). It may be provided as +
                    +
                  • a key, e.g. a classification notation, like NF2.3
                  • +
                  • a handle
                  • +
                  • a uuid or guid
                  • +
                  +It may be human readable (such as a key) or not (such as a handle or uuid) depending on the context of its usage (which has to be determined by local agreement). +
                  + + IFC2x4 CHANGE Attribute renamed from ItemReference for consistency. + + +
                  +
                  " +3776;Name;Optional name to further specify the reference. It can provide a human readable identifier (which does not necessarily need to have a counterpart in the internal structure of the document). +3777;ExternalReferenceForResources;" +Reference to all associations between this external reference and objects within the IfcResourceObjectSelect that are tagged by the external reference. +
                  + + +IFC2x4 CHANGE  New inverse attribute added with upward compatibility. + + +
                  +
                  " +3780;ReferencedSource;The classification system or source that is referenced. +3781;Description;" +Description of the classification reference for informational purposes. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3782;ClassificationRefForObjects;" +The classification reference with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3783;HasReferences;" +The parent classification references to which this child classification reference applies. It can either be the final classification item leaf node, or an intermediate classification item. +
                  + + + IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +3788;Description;" +Description of the document reference for informational purposes. +

                  + + IFC2x4 CHANGE  New attribute added at the end of the attribute list. + +

                  +
                  " +3789;ReferencedDocument;The document that is referenced. +3790;DocumentRefForObjects;" +The document reference with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3793;DocumentId;Identifier that uniquely identifies a document. +3794;Name;File name or document name assigned by owner. +3795;Description;Description of document and its content. +3796;Purpose;Purpose for this document. +3797;IntendedUse;Intended use for this document. +3798;Scope;Scope for this document. +3799;Revision;Document revision designation. +3800;DocumentOwner;Information about the person and/or organization acknowledged as the 'owner' of this document. In some contexts, the document owner determines who has access to or editing right to the document. +3801;Editors;The persons and/or organizations who have created this document or contributed to it. +3802;CreationTime;" +Date and time stamp when the document was originally created. +
                  + + +IFC2x4 CHANGE The data type has been changed to IfcDateTime, the date time string according to ISO8601. + + +
                  +
                  " +3803;LastRevisionTime;" +Date and time stamp when this document version was created. +
                  + + +IFC2x4 CHANGE The data type has been changed to IfcDateTime, the date time string according to ISO8601. + + +
                  +
                  " +3804;ElectronicFormat;Describes the electronic format of the document being referenced, providing the file extension and the manner in which the content is provided. +3805;ValidFrom;" +Date when the document becomes valid. +
                  + + +IFC2x4 CHANGE The data type has been changed to IfcDate, the date string according to ISO8601. + + +
                  +
                  " +3806;ValidUntil;" +Date until which the document remains valid. +
                  + + +IFC2x4 CHANGE The data type has been changed to IfcDate, the date string according to ISO8601. + + +
                  +
                  " +3807;Confidentiality;The level of confidentiality of the document. +3808;Status;"The current status of the document. Examples of status values that might be used for a document information status include:
                  +- DRAFT
                  +- FINAL DRAFT
                  +- FINAL
                  +- REVISION
                  " +3809;Location;"Resource identifier or locator, provided as URI, URN or URL, of the document information for online references. +
                  + + IFC2x4 CHANGE  New attribute added at end of attribute list. + +
                  +
                  " +3810;DocumentInfoForObjects;" +The document information with which objects are associated. +
                  + + IFC2x4 CHANGE  New inverse attribute. + +
                  +
                  " +3811;HasDocumentReferences;The document references to which the document applies +3812;IsPointedTo;An inverse relationship from the IfcDocumentInformationRelationship to the related documents./EPM-HTML> +3813;IsPointer;An inverse relationship from the IfcDocumentInformationRelationship to the relating document. +3815;FileExtension;File extension of electronic document used by computer operating system. +3816;MimeContentType;Main Mime type (as published by W3C or as user defined application type). +3817;MimeSubtype;Mime subtype information. +3833;RelatingDocument;The document that acts as the parent, referencing or original document in a relationship. +3834;RelatedDocuments;The document that acts as the child, referenced or replacing document in a relationship. +3835;RelationshipType;Describes the type of relationship between documents. This could be sub-document, replacement etc. The interpretation has to be established in an application context. +3847;Name;

                  A name used to identify or qualify the relationship.

                  +3848;Description;

                  A description that may apply additional information about the relationship.

                  +3850;RelatingReference;" +An external reference that can be used to tag an object within the range of IfcResourceObjectSelect. +
                  +

                  + +NOTE  External references can be a library reference (for example a dictionary or a catalogue reference), a classification reference, or a documentation reference. + +

                  +
                  +
                  " +3851;RelatedResourceObjects;

                  Objects within the list of IfcResourceObjectSelect that can be tagged by an external reference to a dictionary, library, catalogue, classification or documentation.

                  +3880;Name;A name to be used for the constraint (e.g., ChillerCoefficientOfPerformance). +3881;Description;A description that may apply additional information about a constraint. +3882;ConstraintGrade;Enumeration that qualifies the type of constraint. +3883;ConstraintSource;Any source material, such as a code or standard, from which the constraint originated. +3884;CreatingActor;Person and/or organization that has created the constraint. +3885;CreationTime;" +Time when information specifying the constraint instance was created. +
                  + Note IFC2x4 CHANGE: Attribute data type changed to IfcDateTime using ISO 8601 representation + +
                  +
                  " +3886;UserDefinedGrade;"Allows for specification of user defined grade of the constraint beyond the enumeration values (hard, soft, advisory) provided by ConstraintGrade attribute of type IfcConstraintEnum. +When a value is provided for attribute UserDefinedGrade in parallel the attribute ConstraintGrade shall have enumeration value USERDEFINED." +3887;HasExternalReferences;" +Reference to an external references, e.g. library, classification, or document information, that are associated to the constraint. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +3888;IsRelatedWith;References to the objectified relationships that relate this constraint with other constraints. +3889;RelatesConstraints;" +References to the objectified relationships that relate other constraints with this constraint. + +
                  +NOTE   For an aggregated constraint, only one instance of IfcConstraintAggregationRelationship shall be set of RelatesConstraints. +
                  + +
                  " +3890;PropertiesForConstraint;Reference to the properties to which the constraint is applied. +3894;BenchmarkValues;A list of any benchmark values used for comparison purposes. +3895;ResultValues;A list of any resultant values used for comparison purposes. +3896;ObjectiveQualifier;"Enumeration that qualifies the type of objective constraint. " +3897;UserDefinedQualifier;A user defined value that qualifies the type of objective constraint when ObjectiveQualifier attribute of type IfcObjectiveEnum has value USERDEFINED. +3900;Benchmark;"Enumeration that identifies the type of benchmark data. " +3901;ValueSource;"Reference source for data values. " +3902;DataValue;"The value with data type defined by the underlying type accesses via IfcMetricValueSelect. " +3938;RelatingConstraint;The constraint that is to be related. +3939;RelatedResourceObjects;The properties to which a constraint is to be related. +3942;RelatingConstraint;Constraint with which the other Constraints referenced by attribute RelatedConstraints are related. +3943;RelatedConstraints;Constraints that are related with the one referenced as RelatingConstraint. +3946;LogicalAggregator;"Enumeration that identifies the logical type of aggregation. " +3955;CostType;"Specification of the type of cost type used. + +
                  NOTE: There are many possible types of cost value that may be identified. Whilst there is a broad understanding of the meaning of names that may be assigned to different types of costs, there is no general standard for naming cost types nor are there any broadly defined classifications. To allow for any type of cost value, the IfcLabel datatype is assigned.
                  + +In the absence of any well defined standard, it is recommended that local agreements should be made to define allowable and understandable cost value types within a project or region. +
                  + " +3956;Condition;The condition under which a cost value applies. +3959;Name;A name or additional clarification given to a cost value. +3960;Description;The description that may apply additional information about a cost value. +3961;AppliedValue;The extent or quantity or amount of an applied value. +3962;UnitBasis;"The number and unit of measure on which the unit cost is based. + +Note: As well as the normally expected units of measure such as length, area, volume etc., costs may be based on units of measure which need to be defined e.g. sack, drum, pallet, item etc. Unit costs may be based on quantities greater (or lesser) than a unitary value of the basis measure. For instance, timber may have a unit cost rate per X meters where X > 1; similarly for cable, piping and many other items. The basis number may be either an integer or a real value. + +Note: This attribute should be asserted for all circumstances where the cost to be applied is per unit quantity. It may be asserted even for circumstances where an item price is used, in which case the unit cost basis should be by item (or equivalent definition). " +3963;ApplicableDate;" +The date on or from which an applied value is applicable. +
                  + + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
                  +
                  " +3964;FixedUntilDate;" +The date until which applied value is applicable. +
                  + + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. + + +
                  +
                  " +3965;HasExternalReference;" +Reference to an external reference, e.g. library, classification, or document information, that is associated to the IfcAppliedValue. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +3966;ValueOfComponents;The total (or subtotal) value of the components within the applied value relationship expressed as a single applied value. +3967;IsComponentIn;The value of the single applied value which is used by the applied value relationship to express a complex applied value. +3974;RelatingMonetaryUnit;The monetary unit from which an exchange is derived. For instance, in the case of a conversion from GBP to USD, the relating monetary unit is GBP. +3975;RelatedMonetaryUnit;The monetary unit to which an exchange results. For instance, in the case of a conversion from GBP to USD, the related monetary unit is USD. +3976;ExchangeRate;The currently agreed ratio of the amount of a related monetary unit that is equivalent to a unit amount of the relating monetary unit in a currency relationship. For instance, in the case of a conversion from GBP to USD, the value of the exchange rate may be 1.486 (USD) : 1 (GBP). +3977;RateDateTime;" +The date and time at which an exchange rate applies. +
                  + + +IFC2x4 CHANGE Type changed from IfcDateTimeSelect. Attribute made optional. + + +
                  +
                  " +3978;RateSource;The source from which an exchange rate is obtained. +3980;ComponentOfTotal;The applied value (total or subtotal) of which the value being considered is a component. +3981;Components;Applied values that are components of another applied value and from which that applied value may be deduced. +3982;ArithmeticOperator;The arithmetic operator applied in an applied value relationship. +3990;Name;" +Optional name to indicate rate table designation, e.g. ""A"", ""B"". If provided, then the amounts are based upon IfcCostValue rates having the same Name, where such rates are defined on the referencing IfcConstructionResource. +

                  +
                  " +3991;DataOrigin;" +Indicates the origin of cost data:
                  +MEASURED indicates firm values considered final;
                  +PREDICTED indicates estimated values considered tentative;
                  +SIMULATED indicates calculated values based on effective rates and the scheduled work times.
                  +

                  +
                  " +3992;UserDefinedDataOrigin;" +Indicates a custom data origin if DataOrigin is set to USERDEFINED.
                  +

                  +
                  " +3993;StatusDate;" +Indicates the date for which the information is applicable, particularly earned value calculations (PlannedValue, EarnedValue, ActualValue) which rely on the status date and associated time series at the referencing IfcConstructionResource. +

                  +
                  " +3994;ScheduleCost;" +Indicates the total budgeted cost on behalf of the resource, optionally for a particular task. +This attribute may be time-phased using IfcRelAssociatesTimeSeries on IfcConstructionResource having Name 'ResourceCost.ScheduleCost'. +

                  +
                  " +3995;ActualCost;" +Indicates the total actual cost incurred on behalf of the resource, optionally for a particular task. +This attribute may be time-phased using IfcRelAssociatesTimeSeries on IfcConstructionResource having Name 'ResourceCost.ActualCost'. +

                  +
                  " +3996;RemainingCost;" +Indicates the total remaining cost on behalf of the resource, optionally for a particular task. +This attribute may be time-phased using IfcRelAssociatesTimeSeries on IfcConstructionResource having Name 'ResourceCost.RemainingCost'. +

                  +
                  " +3997;PlannedValue;" +Indicates the Planned Value (PV) which is the sum of the ScheduleCost time series of work scheduled to be completed as of the StatusDate. Also referred to as Budgeted Cost of Work Scheduled (BCWS). +

                  +
                  " +3998;EarnedValue;" +Indicates the Earned Value (EV) which is the sum of the ScheduleCost time series of work actually completed as of the StatusDate. Also referred to as Budgeted Cost of Work Performed (BCWP). +

                  +
                  " +3999;ActualValue;" +Indicates the Actual Cost of Work Performed (ACWP) which is the sum of the ActualCost time series of work actually completed as of the StatusDate. Note that this is not necessarily the same as ActualCost which is the sum of all actual work recorded regardless of status date (i.e. actual work may be recorded after the status date which would not be included). +

                  +
                  " +4008;Name;An unique name for the time series. +4009;Description;A text description of the data that the series represents. +4010;StartTime;The start time of a time series. +4011;EndTime;The end time of a time series. +4012;TimeSeriesDataType;The time series data type. +4013;DataOrigin;The orgin of a time series data. +4014;UserDefinedDataOrigin;Value of the data origin if DataOrigin attribute is USERDEFINED. +4015;Unit;" +The unit to be assigned to all values within the time series. Note that mixing units is not allowed. If the value is not given, the global unit for the type of IfcValue, as defined at IfcProject.UnitsInContext is used. +" +4016;HasExternalReference;" +Reference to an external reference, e.g. library, classification, or document information, that is associated to the IfcTimeSeries. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +4018;TimeStep;A duration of time intervals between values. +4019;Values;The collection of time series values. +4021;ListValues;A list of time-series values. At least one value is required. +4023;Values;The collection of time series values. +4025;TimeStamp;The specification of the time point. +4026;ListValues;A list of time-series values. At least one value is required. +4043;DurationType;" + Enables to specify the type of duration values for ScheduleDuration, ActualDuration and RemainingTime. The duration type is either + work time or elapsed time. +" +4044;ScheduleDuration;" + The amount of time which is scheduled for completion of a + task. + The value might be measured or somehow calculated, which is defined by + ScheduleDataOrigin. + The value is either given as elapsed time or work time, which is defined by + DurationType. +

                  + NOTE: Scheduled Duration may be calculated as the + time from scheduled start date to scheduled finish date. +

                  + +
                  " +4045;ScheduleStart;" + The date on which a task is scheduled to be started. + The value might be measured or somehow calculated, which is defined by + ScheduleDataOrigin. +

                  + NOTE: The scheduled start date must be greater than + or equal to the earliest start date. +

                  +
                  " +4046;ScheduleFinish;" + The date on which a task is scheduled to be finished. + The value might be measured or somehow calculated, which is defined by + ScheduleDataOrigin. +

                  + NOTE: The scheduled finish date must be greater than + or equal to the earliest finish date. +

                  +
                  " +4047;EarlyStart;" + The earliest date on which a task can be started. It is a calculated value. +" +4048;EarlyFinish;" + The earliest date on which a task can be finished. It is a calculated value. +" +4049;LateStart;" + The latest date on which a task can be started. It is a calculated value. +" +4050;LateFinish;" + The latest date on which a task can be finished. It is a calculated value. +" +4051;FreeFloat;" + The amount of time during which the start or finish of a + task may be varied without any effect on the overall + programme of work. It is a calculated elapsed time value. +" +4052;TotalFloat;" + The difference between the duration available to carry out + a task and the scheduled duration of the task. It is a calculated + elapsed time value. +

                  + NOTE: Total Float time may be calculated as being + the difference between the scheduled duration of a task and + the available duration from earliest start to latest + finish. Float time may be either positive, zero or + negative. Where it is zero or negative, the task becomes + critical. +

                  +
                  " +4053;IsCritical;" + A flag which identifies whether a scheduled task is a + critical item within the programme. +

                  + NOTE: A task becomes critical when the float time + becomes zero or negative. +

                  +
                  " +4054;StatusTime;" + The date or time at which the status of the tasks within + the schedule is analyzed. +" +4055;ActualDuration;" + The actual duration of the task. It is a measured value. + The value is either given as elapsed time or work time, which is defined by + DurationType. +" +4056;ActualStart;" + The date on which a task is actually started. It is a measured value. +

                  + NOTE: The scheduled start date must be greater than + or equal to the earliest start date. No constraint is + applied to the actual start date with respect to the + scheduled start date since a task may be started earlier + than had originally been scheduled if circumstances allow. +

                  +
                  " +4057;ActualFinish;" + The date on which a task is actually finished. +" +4058;RemainingTime;" + The amount of time remaining to complete a task. It is a predicted value. + The value is either given as elapsed time or work time, which is defined by + DurationType. +

                  + NOTE: The time remaining in which to complete a task + may be determined both for tasks which have not yet started + and those which have. Remaining time for a task not yet + started has the same value as the scheduled duration. For a + task already started, remaining time is calculated as the + difference between the scheduled finish and the point of + analysis. +

                  +
                  " +4059;Completion;" + The extent of completion expressed as a ratio or percentage. + It is a measured value. +" +4066;Name;" + Optional name for the time definition. +" +4067;DataOrigin;" + Specifies the origin of the scheduling time entity. It currently + differentiates between predicted, simulated, measured, and user defined values. +" +4068;UserDefinedDataOrigin;Value of the data origin if DataOrigin attribute is USERDEFINED. +4070;LagValue;" + Value of the time lag selected as being either a ratio or a + time measure. +" +4071;DurationType;" + The allowed types of task duration that specify the lag time + measurement (work time or elapsed time). +" +4080;ScheduleWork;"Indicates the total work (e.g. person-hours) allocated to the task on behalf of the resource. +Note: this is not necessarily the same as the task duration (IfcTaskTime.ScheduleDuration); it may vary according to the resource usage ratio and other resources assigned to the task." +4081;ScheduleUsage;Indicates the amount of the resource used concurrently. For example, 100% means 1 worker, 300% means 3 workers, 50% means half of 1 worker's time for scenarios where multitasking is feasible. If not provided, then the usage ratio is considered to be 100%. +4082;ScheduleStart;Indicates the time when the resource is scheduled to start working. +4083;ScheduleFinish;Indicates the time when the resource is scheduled to finish working. +4084;ScheduleContour;Indicates how a resource should be leveled over time by adjusting the resource usage according to a specified curve. Standard values include: 'Flat', 'BackLoaded', 'FrontLoaded', 'DoublePeak', 'EarlyPeak', 'LatePeak', 'Bell', and 'Turtle'. Custom values may specify a custom name or formula. +4085;LevelingDelay;Indicates a delay in the ScheduleStart caused by leveling. +4086;IsOverAllocated;Indicates that the resource is scheduled in excess of its capacity. +4087;StatusTime;"Indicates the date and time for which status values are applicable; particularly completion, actual, and remaining values. If values are time-phased (the referencing IfcConstructionResource has associated time series values for attributes), then the status values may be determined from such time-phased data as of the StatusTime." +4088;ActualWork;Indicates the actual work performed by the resource as of the StatusTime. +4089;ActualUsage;Indicates the actual amount of the resource used concurrently. +4090;ActualStart;Indicates the time when the resource actually started working. +4091;ActualFinish;Indicates the time when the resource actually finished working. +4092;RemainingWork;Indicates the work remaining to be completed by the resource. +4093;RemainingUsage; +4094;Completion;"Indicates the percent completion of this resource. If the resource is assigned to a task, then indicates completion of the task on behalf of the resource; if the resource is partitioned into sub-allocations, then indicates overall completion of sub-allocations." +4096;ActualDate;" + The date on which an event actually occurs. It is a measured value. + " +4097;EarlyDate;" + The earliest date on which an event can occur. It is a calculated value. +" +4098;LateDate;" + The latest date on which an event can occur. It is a calculated value. +" +4099;ScheduleDate;" + The date on which an event is scheduled to occur. + The value might be measured or somehow calculated, which is defined by + ScheduleDataOrigin. + +" +4101;RecurrencePattern;" + Recurrence pattern that defines a time period, which, if given, is + valid within the time period defined by + IfcWorkTime.Start and IfcWorkTime.Finish. +" +4102;Start;" + Start date of the work time (0:00), that might be further + restricted by a recurrence pattern. +" +4103;Finish;" + End date of the work time (24:00), that might be further + restricted by a recurrence pattern. +" +4105;RecurrenceType;" + Defines the recurrence type that gives meaning to the used + attributes and decides about possible attribute + combinations, i.e. what attributes are needed to fully + describe the pattern type. +" +4106;DayComponent;" + The position of the specified day in a month. + " +4107;WeekdayComponent;" + The weekday name of the specified day in a week. +" +4108;MonthComponent;" + The position of the specified month in a year. + " +4109;Position;" + The position of the specified component, e.g. the 3rd + (position=3) Tuesday (weekday component) in a month. A + negative position value is used to define the last position + of the component (-1), the next to last position (-2) etc. + " +4110;Interval;" + An interval can be given according to the pattern type. An + interval value of 2 can for instance every two days, weeks, + months, years. An empty interval value is regarded as 1. The + used interval values should be in a reasonable range, e.g. + not 0 or <0. +" +4111;Occurrences;" + Defines the number of occurrences of this pattern, e.g. a weekly + event might be defined to occur 5 times before it stops. +" +4112;TimePeriods;" + List of time periods that are defined by a start and end time + of the recurring element (day). The order of the list should + reflect the sequence of the time periods. +" +4129;StartTime;" + Start time of the time period. +" +4130;EndTime;" + End time of the time period. +" +4132;Recurrance; +4141;PointOnRelatingElement;Point at which the connected object is aligned at the relating element, given in the LCS of the relating element. +4184;PlacementRefDirection;" +Reference to either an explicit direction, or a second grid axis intersection, which defines the orientation of the grid placement. +
                  +IFC2x4 CHANGE The select of an explict direction has been added. + +
                  +
                  " +4188;PlacesObject;" +The IfcObjectPlacement shall be used to provide a placement and +an object coordinate system for a single +one or many instances of IfcProduct. If an IfcObjectPlacement is +shared by many instances of IfcProduct it does not apply a semantic +meaning of being a shared property that needs to be maintained. Using +the same instance of IfcObjectPlacement could simply be used to +reduce exchange file size. +
                  + + IFC2x3 CHANGE  New inverse attribute. +
                  + + IFC2x4 CHANGE  The cardinality has changed to 1..n to allow reuse of instances of IfcObjectPlacement as placement object in one to many products. + +
                  +
                  " +4189;ReferencedByPlacements;Placements that are given relative to this placement of an object. +4191;PlacementRelTo;"Reference to Object that provides the relative placement by its local coordinate system. If it is omitted, then the local placement is given to the WCS, established by the geometric representation context. " +4192;RelativePlacement;Geometric placement that defines the transformation from the related coordinate system into the relating. The placement can be either 2D or 3D, depending on the dimension count of the coordinate system. +4200;Name;" +Name of the material. +
                  + +EXAMPLE A view definition may require Material.Name to uniquely specify e.g. concrete or steel grade, in which case the attribute Material.Category could take the value 'Concrete' or 'Steel'.
                  +
                  + +NOTE Material grade may have diffenrent meaning in different view definitions, e.g. strength grade for structural design and analysis, or visible appearance grade in architectural application. Also, more elaborate material grade definition may be associated as classification via inverse attribute HasExternalReferences. + +
                  +
                  " +4201;Description;" +Definition of the material in more descriptive terms than given by attributes Name or Category. +

                  + + IFC2x4 CHANGE  The attribute has been added at the end of attribute list. + + +

                  +
                  " +4202;Category;" +Definition of the category (group or type) of material, in more general terms than given by attribute Name. +
                  + +EXAMPLE A view definition may require each Material.Name to be unique, e.g. for each concrete or steel grade used in a project, in which case Material.Category could take the values 'Concrete' or 'Steel'.
                  +
                  + + IFC2x4 CHANGE  The attribute has been added at the end of attribute list. + + +
                  +
                  " +4203;HasRepresentation;" +Reference to the IfcMaterialDefinitionRepresentation that provides presentation information to a representation common to this material in style definitions. +
                  +IFC2x Edition 3 CHANGE  The inverse attribute HasRepresentation has been added. +
                  +
                  " +4204;IsRelatedWith;" +Reference to a material relationship indicating that this material is a part (or constituent) in a material composite. +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4205;RelatesTo;" +Reference to a material relationship indicating that this material composite has parts (or contituents). +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4214;AssociatedTo;" +Use of the IfcMaterialDefinition subtypes within the material association of an element occurrence or element type. The association is established by the IfcRelAssociatesMaterial relationship. +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4215;HasExternalReferences;" +Reference to external references, e.g. library, classification, or document information, that are associated to the material. +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4216;HasProperties;" +Material properties assigned to instances of subtypes of IfcMaterialDefinition. +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4219;Material;Optional reference to the material from which the layer is constructed. Note that if this value is not given, it does not denote a layer with no material (an air gap), it only means that the material is not specified at that point. +4220;LayerThickness;" +The thickness of the material layer. The dimension is measured along the positive MlsDirection as specified in IfcMaterialLayerSet (that is mapped to AXIS-2, as specified in IfcMaterialLayerSetUsage for element occurrences supporting IfcMaterialLayerSetUsage. +

                  + + NOTE  The attribute value can be 0. for material thicknesses very close to zero, such as for a membrane. Material layers with thickess 0. shall not be rendered in the geometric representation.

                  +
                  +
                  + + IFC2x4 CHANGE  The attribute datatype has been changed to IfcNonNegativeLengthMeasure allowing for 0. as thickness. + + +

                  + +
                  " +4221;IsVentilated;" +Indication of whether the material layer represents an air layer (or cavity). +
                    +
                  • set to TRUE if the material layer is an air gap and provides air exchange from the layer to the outside air.
                  • +
                  • set to UNKNOWN if the material layer is an air gap and does not provide air exchange (or when this information about air exchange of the air gap is not available).
                  • +
                  • set to FALSE if the material layer is a solid material layer (the default).
                  • +
                  +
                  " +4222;Name;The name by which the material layer is known. +4223;Description;Definition of the material layer in more descriptive terms than given by attributes Name or Category. +4224;Category;Category of the material layer, e.g. the role it has in the layer set it belongs to (such as 'load bearing', 'thermal insulation' etc.). +4225;Priority;" +The relative priority of the layer, expressed as ratio measure, normalised to 0..1. Controls how layers intersect in connections and corners of building elements: a layer from one element protrudes into (i.e. displaces) a layer from another element in a joint of these elements if the former element's layer has higher priority than the latter. The priorty value for a material layer in an element has to be set and maintained by software applications, in relation to the material layers in connected elements. The usage has to be further specified for each element, especially to avoid simultanious use with IfcLayerOffset. +" +4226;ToMaterialLayerSet;Reference to the material layer set in which the material layer is included. +4228;OffsetDirection;" +Orientation of the offset; shall be perpendicular to the parent layer set direction. + " +4229;OffsetValues;" +The numerical value of layer offset, in the direction of the axis assigned by the attribute OffsetDirection. The OffsetValues[1] identifies the offset from the lower position along the axis direction (normally the start of the standard extrusion), the OffsetValues[2] identifies the offset from the upper position along the axis direction (normally the end of the standard extrusion), +" +4235;MaterialLayers;Identification of the layers from which the material layer set is composed. +4236;LayerSetName;The name by which the material layer set is known. +4237;Description;" +Definition of the material layer set in descriptive terms. +
                  + + IFC2x4 CHANGE  The attribute has been added at the end of attribute list. + + +
                  +
                  " +4238;TotalThickness;Total thickness of the material layer set is derived from the function IfcMlsTotalThickness. +4240;Name;" +The name by which the material profile set is known. +" +4241;Description;Definition of the material profile set in descriptive terms. +4242;MaterialProfiles;" +Identification of the profiles from which the material profile set is composed. +" +4243;CompositeProfile;" +Reference to the composite profile definition for which this material profile set associates material to each of its individual profile. + +
                  NOTE   +The referenced IfcCompositeProfileDef instance shall be composed of all of the IfcProfileDef instances which are used via the MaterialProfiles list in the current IfcMaterialProfileSet . + +
                  + +
                  " +4246;Name;The name by which the material profile is known. +4247;Description;Definition of the material profile in descriptive terms. +4248;Material;Optional reference to the material from which the profile is constructed. +4249;Profile;Identification of the profile for which this material profile is associating material. +4250;Priority;" +The relative priority of the profile, expressed as ratio measure, normalised to 0..1. Controls how profiles intersect in connections and corners of building elements: a profile from one element protrudes into (i.e. displaces) a profile from another element in a joint of these elements if the former element's profile has higher priority than the latter. The priorty value for a material profile in an element has to be set and maintained by software applications, in relation to the material profiles in connected elements. +" +4251;Category;Category of the material profile, e.g. the role it has in the profile set it belongs to. +4252;ToMaterialProfileSet;Material profile set in which this material profile is included. +4254;OffsetValues;" +The numerical value of profile offset, in the direction of the axis direction - always AXIS1 i.e. the axis along the extrusion path. The OffsetValues[1] identifies the offset from the lower position along the axis direction (normally the start of the standard extrusion), the OffsetValues[2] identifies the offset from the upper position along the axis direction (normally the end of the standard extrusion), +" +4256;Name;" +The name by which the constituent set is known. +" +4257;Description;" +Definition of the material constituent set in descriptive terms. +" +4258;MaterialConstituents;" +Identification of the constituents from which the material constituent set is composed. +" +4260;Name;" +The name by which the material constituent is known. +" +4261;Description;" +Definition of the material constituent in descriptive terms. +" +4262;Material;" +Reference to the material from which the constituent is constructed. +" +4263;Fraction;" +Optional provision of a fraction of the total amount (volume or weight) that applies to the IfcMaterialConstituentSet that is contributed by this IfcMaterialConstituent. +" +4264;Category;" +Category of the material constituent, e.g. the role it has in the constituent set it belongs to. +" +4265;ToMaterialConstituentSet;" +Material constituent set in which this material constituent is included. +" +4267;RelatingMaterial;Reference to the relating material (the composite). +4268;RelatedMaterials;Reference to related materials (as constituents of composite material). +4269;Expression;The amount of related material in the whole (composite material or material set). Expressed as proportion (percentage) of weight or volume, or as any other appropriate value. +4272;Name;" +The name given to the set of extended properties. +" +4273;Description;" +Description for the set of material properties. +" +4274;Material;" +Reference to the material definition to which the set of properties is assigned. +
                  + + + IFC2x4 CHANGE The datatype has been changed to supertype IfcMaterialDefinition. + + +
                  +
                  " +4276;Properties;" +The set of material properties provided for this material definition. +" +4278;MaterialClassifications;The material classifications identifying the type of material. +4279;ClassifiedMaterial;Material being classified. +4281;ForLayerSet;" +The IfcMaterialLayerSet set to which the usage is applied. +" +4282;LayerSetDirection;" +Orientation of the material layer set relative to element reference geometry. The meaning of the value of this attribute shall be specified in the geometry use section for each element. For extruded shape representation, direction can be given along the extrusion path (e.g. for slabs) or perpendicular to it (e.g. for walls). + +
                  + NOTE  the LayerSetDirection for IfcWallStandardCase shall be AXIS2 (i.e. the y-axis) and for IfcSlabStandardCase and IfcPlateStandardCase it shall be AXIS3 (i.e. the z-axis). + +
                  + +Whether the material layers of the set being used shall 'grow' into the positive or negative direction of the given axis, shall be deifned by DirectionSense attribute. +
                  " +4283;DirectionSense;" +Denotion whether the material layer set is oriented in positive or negative sense along the specified axis (defined by LayerSetDirection). ""Positive"" means that the consecutive layers (the IfcMaterialLayer instances in the list of IfcMaterialLayerSet.MaterialLayers) are placed face-by-face in the direction of the positive axis as established by LayerSetDirection: for AXIS2 it would be in +y, for AXIS3 it would be +z. ""Negative"" means that the layers are placed face-by-face in the direction of the negative LayerSetDirection. In both cases, starting at the material layer set base line. +
                  NOTE  the material layer set base line (MlsBase) is located by OffsetFromReferenceLine, and may be on the positive or negative side of the element reference line (or plane); positive or negative for MlsBase placement does not depend on the DirectionSense attribute, but on the relevant element axis.
                  +
                  " +4284;OffsetFromReferenceLine;" +Offset of the material layer set base line (MlsBase) from reference geometry (line or plane) of element. The offset can be positive or negative, unless restricted for a particular building element type in its use definition or by implementer agreement. A positive value means, that the MlsBase is placed on the positive side of the reference line or plane, on the axis established by LayerSetDirection (in case of AXIS2 into the direction of +y, or in case of AXIS2 into the direction of +z). A negative value means that the MlsBase is placed on the negative side, as established by LayerSetDirection (in case of AXIS2 into the direction of -y).
                  NOTE  the positive or negative sign in the offset only affects the MlsBase placement, it does not have any effect on the application of DirectionSense for orientation of the material layers; also DirectionSense does not change the MlsBase placement. +
                  +
                  " +4285;ReferenceExtent;"EPM-HTML> +Extent of the extrusion of the elements body shape representation to which the IfcMaterialLayerSetUsage applies. It is used as the reference value for the upper OffsetValues[2] provided by the IfcMaterialLayerSetWithOffsets subtype for included material layers. + +
                  +

                  + + IFC2x4 CHANGE  New attribute added to the end of attribute list. + +

                  +

                  + + NOTE 1  The attribute ReferenceExtent shall be asserted, if an IfcMaterialLayerSetWithOffsets is included in the ForLayerSet.MaterialLayers list of maerial layers. +
                  + + NOTE 2  The ReferenceExtent for IfcWallStandardCase is the reference height starting at z=0 being the XY plane of the object coordinate system. + +

                  +
                  + +
                  " +4289;AssociatedTo;" +Use of the IfcMaterialUsageDefinition subtypes within the material association of an element occurrence. The association is established by the IfcRelAssociatesMaterial relationship. +
                  + + IFC2x4 CHANGE  The inverse attribute has been added. + + +
                  +
                  " +4292;ForProfileSet;" +The IfcMaterialProfileSet set to which the usage is applied. +" +4293;CardinalPoint;" +Index reference to a significant point in the section profile. Describes how the section is aligned relative to the (longitudinal) axis of the member it is associated with. This parametric specification of profile alignment can be provided redundantly to the explicit alignment defined by ForProfileSet.MaterialProfiles[*].Profile. +" +4294;ReferenceExtent;"EPM-HTML> +Extent of the extrusion of the elements body shape representation to which the IfcMaterialProfileSetUsage applies. It is used as the reference value for the upper OffsetValues[2] provided by the IfcMaterialProfileSetWithOffsets subtype for included material profiles. + +
                  +

                  + + NOTE 1  The attribute ReferenceExtent shall be asserted, if an IfcMaterialProfileSetWithOffsets is included in the ForProfileSet.MaterialProfiles list of maerial layers. +
                  + + NOTE 2  The ReferenceExtent for IfcBeamStandardCase, IfcColumnStandardCase, and IfcMemberStandardCase is the reference length starting at z=0 being the XY plane of the object coordinate system. + +

                  +
                  + +
                  " +4296;ForProfileEndSet;" +The second IfcMaterialProfileSet set to which the usage is applied. +" +4297;CardinalEndPoint;" +Index reference to a significant point in the second section profile. Describes how this section is aligned relative to the axis of the member it is associated with. This parametric specification of profile alignment can be provided redundantly to the explicit alignment defined by ForProfileSet.MaterialProfiles[*].Profile. +" +4305;Materials;Materials used in a composition of substances. +4368;Elements;The group of units and their exponents that define the derived unit. +4369;UnitType;Name of the derived unit chosen from an enumeration of derived unit types for use in IFC models. +4370;UserDefinedType; +4371;Dimensions;"Dimensional exponents derived using the function IfcDerivedDimensionalExponents using (SELF) as the input value. " +4375;Unit;The fixed quantity which is used as the mathematical factor. +4376;Exponent;The power that is applied to the unit attribute. +4381;Dimensions;The dimensional exponents of the SI base units by which the named unit is defined. +4382;UnitType;The type of the unit. +4385;Name;The word, or group of words, by which the context dependent unit is referred to. +4386;HasExternalReference;" +Reference to external information, e.g. library, classification, or document information, which is associated with the context dependent unit. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +4390;Name;The word, or group of words, by which the conversion based unit is referred to. +4391;ConversionFactor;The physical quantity from which the converted unit is derived. +4392;HasExternalReference;" +Reference to external information, e.g. library, classification, or document information, which is associated with the conversion-based unit. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +4394;ConversionOffset;" + +A positive or negative offset to add after the inherited ConversionFactor was applied. + + " +4396;ValueComponent;The value of the physical quantity when expressed in the specified units. +4397;UnitComponent;The unit in which the physical quantity is expressed. +4568;Prefix;The SI Prefix for defining decimal multiples and submultiples of the unit. +4569;Name;" + +The word, or group of words, by which the SI unit is referred to. + +
                  NOTE  Even though the SI system's base unit for mass is kilogram, the IfcSIUnit for mass is gram if no Prefix is asserted.
                  + +
                  " +4570;Dimensions;" +The dimensional exponents of SI units are derived by function IfcDimensionsForSiUnit. +" +4620;LengthExponent;The power of the length base quantity. +4621;MassExponent;The power of the mass base quantity. +4622;TimeExponent;The power of the time base quantity. +4623;ElectricCurrentExponent;The power of the electric current base quantity. +4624;ThermodynamicTemperatureExponent;The power of the thermodynamic temperature base quantity. +4625;AmountOfSubstanceExponent;The power of the amount of substance base quantity. +4626;LuminousIntensityExponent;The power of the luminous intensity base quantity. +4710;Currency;" + +Code or name of the currency. Permissible values are the three-letter alphabetic currency codes as per ISO 4217, for example CNY, EUR, GBP, JPY, USD. + +" +4712;Units;Units to be included within a unit assignment. +4720;HatchLineAppearance;The curve style of the hatching lines. Any curve style pattern shall start at the origin of each hatch line. +4721;StartOfNextHatchLine;"A repetition factor that determines the distance between adjacent hatch lines. +
                  +IFC2x Edition 3 CHANGE  The attribute type of StartOfNextHatchLine has changed to a SELECT of IfcPositiveLengthMeasure (new) and IfcOneDirectionRepeatFactor.
                  +
                  " +4722;PointOfReferenceHatchLine;" +A Cartesian point which defines the offset of the reference hatch line from the origin of the (virtual) hatching coordinate system. The origin is used for mapping the fill area style hatching onto an annotation fill area or surface. The reference hatch line would then appear with this offset from the fill style target point.
                  +If not given the reference hatch lines goes through the origin of the (virtual) hatching coordinate system. +
                  +IFC2x Edition 3 CHANGE  The usage of the attribute PointOfReferenceHatchLine has changed to not provide the Cartesian point which is the origin for mapping, but to provide an offset to the origin for the mapping. The attribute has been made OPTIONAL. +
                  +
                  " +4723;PatternStart;" +A distance along the reference hatch line which is the start point for the curve style font pattern of the reference hatch line.
                  +If not given, the start point of the curve style font pattern is at the (virtual) hatching coordinate system. +
                  +IFC2x Edition 2 Addendum 2 CHANGE The attribute PatternStart has been made OPTIONAL.
                  +
                  " +4724;HatchLineAngle;A plane angle measure determining the direction of the parallel hatching lines. +4729;CurveFont;A curve style font which is used to present a curve. It can either be a predefined curve font, or an explicitly defined curve font. Both may be scaled. If not given, then the curve font should be taken from the layer assignment with style, if that is not given either, then the default curve font applies. +4730;CurveWidth;A positive length measure in units of the presentation area for the width of a presented curve. If not given, then the style should be taken from the layer assignment with style, if that is not given either, then the default style applies. +4731;CurveColour;The colour of the visible part of the curve. If not given, then the colour should be taken from the layer assignment with style, if that is not given either, then the default colour applies. +4739;Name;" +Name of the presentation style. +" +4741;TextCharacterAppearance;" +A character style to be used for presented text. +" +4742;TextStyle;" +The style applied to the text block for its visual appearance.
                  +It defines the text block characteristics, either for vector based or monospace text fonts (see select item IfcTextStyleWithBoxCharacteristics), or for true type text fonts (see select item IfcTextStyleTextModel. +
                  +IFC2x Edition 3 CHANGE  The attribute TextBlockStyle has been changed from SET[1:?] to a non-aggregated optional, it has been renamed from TextStyles. +
                  +
                  " +4743;TextFontStyle;" +The style applied to the text font for its visual appearance.
                  +It defines the font family, font style, weight and size. +
                  +IFC2x Edition 2 Addendum 2 CHANGE The attribute TextFontStyle is a new attribute attached to IfcTextStyle. +
                  +
                  " +4747;Colour;" +This property describes the text color of an element (often referred to as the foreground color). +" +4748;BackgroundColour;" +This property sets the background color of an element. +" +4757;BoxHeight;It is the height scaling factor in the definition of a character glyph. +4758;BoxWidth;It is the width scaling factor in the definition of a character glyph. +4759;BoxSlantAngle;It indicated that the box of a character glyph shall be represented as a parallelogram, with the angle being between the character up line and an axis perpendicular to the character base line. +4760;BoxRotateAngle;It indicated that the box of a character glyph shall be presented at an angle to the base line of a text string within which the glyph occurs, the angle being that between the base line of the glyph and an axis perpendicular to the baseline of the text string. +4761;CharacterSpacing;The distance between the character boxes of adjacent characters. +4770;TextIndent;" +The property specifies the indentation that appears before the first formatted line. +
                  NOTE  It has been introduced for later compliance to full CSS1 support.
                  +
                  " +4771;TextAlign;" +This property describes how text is aligned horizontally within the element. The actual justification algorithm used is dependent on the rendering algorithm. +" +4772;TextDecoration;" +This property describes decorations that are added to the text of an element. +" +4773;LetterSpacing;" +The length unit indicates an addition to the default space between characters. Values can be negative, but there may be implementation-specific limits. The user agent is free to select the exact spacing algorithm. The letter spacing may also be influenced by justification (which is a value of the 'align' property). +
                  NOTE  The following values are allowed, IfcDescriptiveMeasure with value='normal', or IfcLengthMeasure, the length unit is globally defined at IfcUnitAssignment.
                  +
                  " +4774;WordSpacing;" +The length unit indicates an addition to the default space between words. Values can be negative, but there may be implementation-specific limits. The user agent is free to select the exact spacing algorithm. The word spacing may also be influenced by justification (which is a value of the 'text-align' property). +
                  NOTE  It has been introduced for later compliance to full CSS1 support.
                  +
                  " +4775;TextTransform;" +This property describes how text characters may transform to upper case, lower case, or capitalized case, independent of the character case used in the text literal. +
                  NOTE  It has been introduced for later compliance to full CSS1 support.
                  +
                  " +4776;LineHeight;" +The property sets the distance between two adjacent lines' baselines.
                  +When a ratio value is specified, the line height is given by the font size of the current element multiplied with the numerical value. A value of 'normal' sets the line height to a reasonable value for the element's font. It is suggested that user agents set the 'normal' value to be a ratio number in the range of 1.0 to 1.2. +
                  NOTE  The following values are allowed:
                  IfcDescriptiveMeasure with value='normal', or
                  +IfcLengthMeasure, with non-negative values, the length unit is globally defined at IfcUnitAssignment, or
                  IfcRatioMeasure.
                  +
                  " +4784;FillStyles;The set of fill area styles to use in presenting visible curve segments, annotation fill areas or surfaces. +4794;TilingPattern;A two direction repeat factor defining the shape and relative positioning of the tiles. +4795;Tiles;A set of constituents of the tile. +4796;TilingScale;The scale factor applied to each tile as it is placed in the annotation fill area. +4799;RepeatFactor;A vector which specifies the relative positioning of hatch lines. +4801;SecondRepeatFactor;A vector which specifies the relative positioning of tiles in the second direction. +4805;Symbol;" +A styled item that is used as the annotation symbol for tiling the filled area. +
                  + + IFC2x4 CHANGE The data type has been changed to IfcStyleItem.
                  +
                  + + NOTE Only IfcStyleItem's that refer to a compatible geometric representation item and presentation style shall be used. + +
                  +
                  " +4807;Item;" +A geometric representation item to which the style is assigned. +
                  +IFC2x Edition 2 Addendum 2 CHANGE The attribute Item has been made optional. Upward compatibility for file based exchange is guaranteed. +
                  +
                  " +4808;Styles;" +Representation styles which are assigned, either to an geometric representation item, or to a material definition. +
                  + + IFC2x4 CHANGE The data type has been changed to IfcStyleAssignmentSelect with upward compatibility +for file based exchange.
                  +
                  + + NOTE Only the select item IfcPresentationStyle shall be used from IFC2x4 onwards, the IfcPresentationStyleAssignment has been deprecated. + +
                  +
                  " +4809;Name;The word, or group of words, by which the styled item is referred to. +4815;Styles;A set of presentation styles that are assigned to styled items. +4826;StyleOfSymbol;The style applied to the symbol for its visual appearance. +4830;Side;An indication of which side of the surface to apply the style. +4831;Styles;A collection of different surface styles. +4849;SurfaceColour;"The colour used to render the surface. The surface colour for visualisation is defined by specifying the intensity of red, green and blue. " +4851;Transparency;"Definition from ISO/CD 10303-46: The degree of transparency is indicated by the percentage of light traversing the surface. +Definition from VRML97 - ISO/IEC 14772-1:1997: The transparency field specifies how ""clear"" an object is, with 1.0 being completely transparent, and 0.0 completely opaque. If not given, the value 0.0 (opaque) is assumed. " +4852;DiffuseColour;"The diffuse part of the reflectance equation can be given as either a colour or a scalar factor. +The diffuse colour field reflects all light sources depending on the angle of the surface with respect to the light source. The more directly the surface faces the light, the more diffuse light reflects. +The diffuse factor field specifies how much diffuse light from light sources this surface shall reflect. Diffuse light depends on the angle of the surface with respect to the light source. The more directly the surface faces the light, the more diffuse light reflects. The diffuse colour is then defined by surface colour * diffuse factor. " +4853;TransmissionColour;"The transmissive part of the reflectance equation can be given as either a colour or a scalar factor. It only applies to materials which Transparency field is greater than zero. +The transmissive colour field specifies the colour that passes through a transparant material (like the colour that shines through a glass). +The transmissive factor defines the transmissive part, the transmissive colour is then defined by surface colour * transmissive factor. " +4854;DiffuseTransmissionColour;"The diffuse transmission part of the reflectance equation can be given as either a colour or a scalar factor. It only applies to materials whose Transparency field is greater than zero. +The diffuse transmission colour specifies how much diffuse light is reflected at the opposite side of the material surface. +The diffuse transmission factor field specifies how much diffuse light from light sources this surface shall reflect on the opposite side of the material surface. The diffuse transmissive colour is then defined by surface colour * diffuse transmissive factor. " +4855;ReflectionColour;"The reflection (or mirror) part of the reflectance equation can be given as either a colour or a scalar factor. Applies to ""glass"" and ""mirror"" reflection models. +The reflection colour specifies the contribution made by light from the mirror direction, i.e. light being reflected from the surface. +The reflection factor specifies the amount of contribution made by light from the mirror direction. The reflection colour is then defined by surface colour * reflection factor. " +4856;SpecularColour;"The specular part of the reflectance equation can be given as either a colour or a scalar factor. +The specular colour determine the specular highlights (e.g., the shiny spots on an apple). When the angle from the light to the surface is close to the angle from the surface to the viewer, the specular colour is added to the diffuse and ambient colour calculations. +The specular factor defines the specular part, the specular colour is then defined by surface colour * specular factor. + " +4857;SpecularHighlight;"The exponent or roughness part of the specular reflectance. " +4858;ReflectanceMethod;"Identifies the predefined types of reflectance method from which the method required may be set. " +4880;DiffuseTransmissionColour;" +The degree of diffusion of the transmitted light. In the case of completely transparent materials there is no diffusion. The greater the diffusing power, the smaller the direct component of the transmitted light, up to the point where only diffuse light is produced.A value of 1 means totally diffuse for that colour part of the light. +
                  The factor can be measured physically and has three ratios for the red, green and blue part of the light. +
                  +
                  " +4881;DiffuseReflectionColour;" +The degree of diffusion of the reflected light. In the case of specular surfaces there is no diffusion. The greater the diffusing power of the reflecting surface, the smaller the specular component of the reflected light, up to the point where only diffuse light is produced. A value of 1 means totally diffuse for that colour part of the light. +
                  The factor can be measured physically and has three ratios for the red, green and blue part of the light. +
                  +
                  " +4882;TransmissionColour;" +Describes how the light falling on a body is totally or partially transmitted. +
                  The factor can be measured physically and has three ratios for the red, green and blue part of the light. +
                  +
                  " +4883;ReflectanceColour;" +A coefficient that determines the extent that the light falling onto a surface is fully or partially reflected. +
                  The factor can be measured physically and has three ratios for the red, green and blue part of the light. +
                  +
                  " +4885;Textures;" +The textures applied to the surface. In case of more than one surface texture is included, the IfcSurfaceStyleWithTexture defines a multi texture. +" +4890;RepeatS;" +The RepeatS field specifies how the texture wraps in the S direction. If RepeatS is TRUE (the default), the texture map is repeated outside the [0.0, 1.0] texture coordinate range in the S direction so that it fills the shape. If RepeatS is FALSE, the texture coordinates are clamped in the S direction to lie within the [0.0, 1.0] range. +
                  +
                  " +4891;RepeatT;" +The RepeatT field specifies how the texture wraps in the T direction. If RepeatT is TRUE (the default), the texture map is repeated outside the [0.0, 1.0] texture coordinate range in the T direction so that it fills the shape. If RepeatT is FALSE, the texture coordinates are clamped in the T direction to lie within the [0.0, 1.0] range. +
                  +
                  " +4892;Mode;" +The Mode attribute is provided to control the appearance of a multi textures. The mode then controls the type of blending operation. The mode includes a MODULATE for a lit appearance, a REPLACE for a unlit appearance, and variations of the two. +
                  +

                  + NOTE  The applicable values for the Mode attribute are determined by view definitions or implementer agreements. It is recommended to use the modes described in ISO/IES 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1. See 18.4.3 MultiTexture for recommended values. +

                  +

                  + IFC2x4 CHANGE  New attribute replacing previous TextureType. +

                  +
                  +
                  " +4893;TextureTransform;" +The TextureTransform
                  defines a 2D transformation that is applied to the texture coordinates. It affects the way texture coordinates are applied to the surfaces of geometric representation itesm. The 2D transformation supports changes to the size, orientation, and position of textures on shapes. +
                  +

                  + Mirroring is not allowed to be used in the IfcCarteesianTransformationOperator +

                  +
                  +
                  " +4894;Parameter;" +The Parameter attribute is provided to control the appearance of a multi textures. The applicable parameters depend on the value of the Mode attribute. +
                  +

                  + NOTE  The applicable values for the list of Parameter attributes are determined by view definitions or implementer agreements. It is recommended to use the source and the function fields described in ISO/IES 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1. See 18.4.3 MultiTexture for recommended values.
                  +By convention, Parameter[1] shall then hold the source value, Parameter[2] the function value, Parameter[3] the base RGB color for select operations, and Parameter[4] the alpha value for select operations.
                  +

                  +

                  + IFC2x4 CHANGE  New attribute added at the end of the attribute list. +

                  +
                  +
                  " +4895;MappedBy;" +Texture coordinates, either provided by a corresponding list of texture vertices to vertex-based geometric items or by a texture coordinate generator, that applies the surface texture to the surfaces of the geometric items. + +

                  + IFC2x4 CHANGE  New attribute added at the end of the attribute list. +

                  +
                  +
                  " +4896;UsedInStyles; +4898;Width;" +The number of pixels in width (S) direction. +" +4899;Height;" +The number of pixels in height (T) direction. +" +4900;ColourComponents;"Indication whether the pixel values contain a 1, 2, 3, or 4 colour component. +" +4901;Pixel;" +Flat list of hexadecimal values, each describing one pixel by 1, 2, 3, or 4 components. +
                  +IFC2x Edition 3 CHANGE  The data type has been changed from STRING to BINARY. +
                  +
                  " +4908;URLReference;" +Location, provided as an URI, at which the image texture is electronically published. +" +4912;RasterFormat;" +The format of the RasterCode often using a compression. +" +4913;RasterCode;" +Blob, given as a single binary, to capture the texture within one popular file (compression) format. The file format is provided by the RasterFormat attribute. +" +4917;RefractionIndex;The index of refraction for all wave lengths of light. The refraction index is the ratio between the speed of light in a vacuum and the speed of light in the medium. E.g. glass has a refraction index of 1.5, whereas water has an index of 1.33 +4918;DispersionFactor;The Abbe constant given as a fixed ratio between the refractive indices of the material at different wavelengths. A low Abbe number means a high dispersive power. In general this translates to a greater angular spread of the emergent spectrum. +4926;Name;Name that may be assigned with the curve font. +4927;PatternList;A list of curve font pattern entities, that contains the simple patterns used for drawing curves. The patterns are applied in the order they occur in the list. +4929;VisibleSegmentLength;" +The length of the visible segment in the pattern definition. +
                  + NOTE  For a visible segment representing a point, the value 0. should be assigned.
                  + + IFC2x Edition 3 CHANGE  The datatype has been changed to IfcLengthMeasure with upward compatibility for file-based exchange. +
                  +
                  " +4930;InvisibleSegmentLength;The length of the invisible segment in the pattern definition. +4933;Name;Name that may be assigned with the scaling of a curve font. +4934;CurveFont;The curve font to be scaled. +4935;CurveFontScaling;The scale factor. +4943;Literal;" +The text literal to be presented. +" +4944;Placement;" +An IfcAxis2Placement that determines the placement and orientation of the presented string. +
                  When used with a text style based on IfcTextStyleWithBoxCharacteristics then the y-axis is taken as the reference direction for the box rotation angle and the box slant angle. +
                  +
                  " +4945;Path;" +The writing direction of the text literal. +" +4947;OuterBoundary;" +A closed curve that defines the outer boundary of the fill area. The areas defined by the outer boundary (minus potentially defined inner boundaries) is filled by the fill area style. +
                  + IFC2x Edition 3 CHANGE  The two new attributes OuterBoundary and InnerBoundaries replace the old single attribute Boundaries. +
                  +
                  " +4948;InnerBoundaries;" +A set of inner curves that define the inner boundaries of the fill area. The areas defined by the inner boundaries are excluded from applying the fill area style. +
                  + IFC2x Edition 3 CHANGE  The two new attributes OuterBoundary and InnerBoundaries replace the old single attribute Boundaries. +
                  +
                  " +4950;Definition;An implicit description of the symbol, either predefined or externally defined. +5003;SpreadAngle;"Definition from ISO/CD 10303-46:1992: This planar angle measure is the angle between the line that starts at the position of the spot light source and is in the direction of the spot light source and any line on the boundary of the cone of influence. +Definition from VRML97 - ISO/IEC 14772-1:1997: The cutOffAngle (name of spread angle in VRML) field specifies the outer bound of the solid angle. The light source does not emit light outside of this solid angle. " +5004;BeamWidthAngle;"Definition from VRML97 - ISO/IEC 14772-1:1997: The beamWidth field specifies an inner solid angle in which the light source emits light at uniform full intensity. The light source's emission intensity drops off from the inner solid angle (beamWidthAngle) to the outer solid angle (spreadAngle). " +5006;Position;"The position of the light source. It is used to orientate the light distribution curves. " +5007;ColourAppearance;"Artificial light sources are classified in terms of their color appearance. To the human eye they all appear to be white; the difference can only be detected by direct comparison. Visual performance is not directly affected by differences in color appearance. " +5008;ColourTemperature;"The color temperature of any source of radiation is defined as the temperature (in Kelvin) of a black-body or Planckian radiator whose radiation has the same chromaticity as the source of radiation. Often the values are only approximate color temperatures as the black-body radiator cannot emit radiation of every chromaticity value. The color temperatures of the commonest artificial light sources range from less than 3000K (warm white) to 4000K (intermediate) and over 5000K (daylight). " +5009;LuminousFlux;"Luminous flux is a photometric measure of radiant flux, i.e. the volume of light emitted from a light source. Luminous flux is measured either for the interior as a whole or for a part of the interior (partial luminous flux for a solid angle). All other photometric parameters are derivatives of luminous flux. Luminous flux is measured in lumens (lm). The luminous flux is given as a nominal value for each lamp. " +5010;LightEmissionSource;"Identifies the types of light emitter from which the type required may be set. " +5011;LightDistributionDataSource;"The data source from which light distribution data is obtained. " +5028;LightDistributionCurve;Standardized light distribution curve used to define the luminous intensity of the light in all directions. +5029;DistributionData;" +

                  Light distribution data applied to the light source. It is defined by a list of main plane angles (B or C according to the light distribution curve chosen) that includes (for each B or C angle) a second list of secondary plane angles (the β or γ angles) and the according luminous intensity distribution measures. +

                  +
                  " +5036;MainPlaneAngle;The main plane angle (A, B or C angles, according to the light distribution curve chosen). +5037;SecondaryPlaneAngle;" +

                  The list of secondary plane angles (the α, β or γ angles) according to the light distribution curve chosen. +

                  +
                  NOTE: The SecondaryPlaneAngle and LuminousIntensity lists are corresponding lists. +
                  +
                  " +5038;LuminousIntensity;The luminous intensity distribution measure for this pair of main and secondary plane angles according to the light distribution curve chosen. +5041;Name;Name of the layer. +5042;Description;Additional description of the layer. +5043;AssignedItems;The set of layered items, which are assigned to this layer. +5044;Identifier;An (internal) identifier assigned to the layer. +5047;LayerOn;A logical setting, TRUE indicates that the layer is set to 'On', FALSE that the layer is set to 'Off', UNKNOWN that such information is not available. +5048;LayerFrozen;A logical setting, TRUE indicates that the layer is set to 'Frozen', FALSE that the layer is set to 'Not frozen', UNKNOWN that such information is not available. +5049;LayerBlocked;A logical setting, TRUE indicates that the layer is set to 'Blocked', FALSE that the layer is set to 'Not blocked', UNKNOWN that such information is not available. +5050;LayerStyles;" +Assignment of presentation styles to the layer to provide a default style for representation items. +
                  + +NOTE  In most cases the assignment of styles to a layer is restricted to an IfcCurveStyle representing the layer curve colour, layer curve thickness, and layer curve type. + + +IFC2x4 CHANGE  The data type has been changed from IfcPresentationStyleSelect (now deprecated) to IfcPresentationStyle. + +
                  +
                  " +5067;Position;"Position coordinate system of the parameterized profile definition. If unspecified, no translation and no rotation is applied. " +5074;ProfileType;Defines the type of geometry into which this profile definition shall be resolved, either a curve or a surface area. In case of curve the profile should be referenced by a swept surface, in case of area the profile should be referenced by a swept area solid. +5075;ProfileName;" + +Human-readable name of the profile, for example according to a standard profile table. As noted above, machine-readable standardized profile designations should be provided in IfcExternalReference.ItemReference. + + " +5076;HasExternalReference;" +Reference to external information, e.g. library, classification, or document information, which is associated with the profile. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +5077;HasProperties;" +Additional properties of the profile, for example mechanical properties. +
                  + + +IFC2x4 CHANGE New inverse attribute. + + +
                  +
                  " +5080;Curve;Open bounded curve defining the profile. +5084;Thickness;" +Constant thickness applied along the center line. +" +5087;OuterCurve;Bounded curve, defining the outer boundaries of the arbitrary profile. +5092;InnerCurves;Set of bounded curves, defining the inner boundaries of the arbitrary profile. +5097;Profiles;The profiles which are used to define the composite profile. +5098;Label;The name by which the composition may be referred to. The actual meaning of the name has to be defined in the context of applications. +5103;ParentProfile;The parent profile provides the origin of the transformation. +5104;Operator;Transformation operator applied to the parent profile. +5105;Label;The name by which the transformation may be referred to. The actual meaning of the name has to be defined in the context of applications. +5108;Operator; +5113;ProfileDefinition;Profile definition which is qualified by these properties. +5114;Name;The name given to the set of properties +5115;Description;Description of the set of properties +5116;HasProperties;Properties of the profile +5119;OverallWidth;Total extent of the width, defined parallel to the x axis of the position coordinate system. +5120;OverallDepth;Total extent of the depth, defined parallel to the y axis of the position coordinate system. +5121;WebThickness;Thickness of the web of the I-shape. The web is centred on the x-axis and the y-axis of the position coordinate system. +5122;FlangeThickness;Flange thickness of the I-shape. Both, the upper and the lower flanges have the same thickness and they are centred on the y-axis of the position coordinate system. +5123;FilletRadius;The fillet between the web and the flange. +5128;TopFlangeWidth;Extent of the top flange, defined parallel to the x axis of the position coordinate system. +5129;TopFlangeThickness;Flange thickness of the top flange of the I-shape. +5130;TopFlangeFilletRadius;The fillet between the web and the top flange of the I-shape. +5132;Depth;Leg length, see illustration above (= h). Same as the overall depth. +5133;Width;Leg length, see illustration above (= b). Same as the overall width. +5134;Thickness;Constant wall thickness of profile, see illustration above (= ts). +5135;FilletRadius;Fillet radius according the above illustration (= r1). +5136;EdgeRadius;Edge radius according the above illustration (= r2). +5137;LegSlope;Slope of the inner face of each leg of the profile. +5140;Depth;Web lengths, see illustration above (= h). +5141;FlangeWidth;Flange lengths, see illustration above (= b). +5142;WebThickness;Constant wall thickness of web (= ts). +5143;FlangeThickness;Constant wall thickness of flange (= tg). +5144;FilletRadius;Fillet radius according the above illustration (= r1). +5145;EdgeRadius;Edge radius according the above illustration (= r2). +5146;FlangeSlope;Slope of flange of the profile. +5150;Depth;Profile depth, see illustration above (= h). +5151;Width;Profile width, see illustration above (= b). +5152;WallThickness;Constant wall thickness of profile (= ts). +5153;Girth;Lengths of girth, see illustration above (= c). +5154;InternalFilletRadius;Internal fillet radius according the above illustration (= r1). +5159;Depth;Web length, see illustration above (= h). +5160;FlangeWidth;Flange length, see illustration above (= b). +5161;WebThickness;Constant wall thickness of web, see illustration above (= ts). +5162;FlangeThickness;Constant wall thickness of flange, see illustration above (= tg). +5163;FilletRadius;Fillet radius according the above illustration (= r1). +5164;EdgeRadius;Edge radius according the above illustration (= r2). +5167;Depth;Web lengths, see illustration above (= h). +5168;FlangeWidth;Flange lengths, see illustration above (= b). +5169;WebThickness;Constant wall thickness of web (= ts). +5170;FlangeThickness;Constant wall thickness of flange (= tg). +5171;FilletRadius;Fillet radius according the above illustration (= r1). +5172;FlangeEdgeRadius;Edge radius according the above illustration (= r2). +5173;WebEdgeRadius;Edge radius according the above illustration (= r3). +5174;WebSlope;Slope of flange of the profile. +5175;FlangeSlope;Slope of web of the profile. +5180;Radius;The radius of the circle. +5182;WallThickness;Thickness of the material, it is the difference between the outer and inner radius. +5185;SemiAxis1;The first radius of the ellipse. It is measured along the direction of Position.P[1]. +5186;SemiAxis2;The second radius of the ellipse. It is measured along the direction of Position.P[2]. +5190;XDim;The extent of the rectangle in the direction of the x-axis. +5191;YDim;The extent of the rectangle in the direction of the y-axis. +5193;WallThickness;Thickness of the material. +5194;InnerFilletRadius;Inner corner radius. +5195;OuterFilletRadius;Outer corner radius. +5200;RoundingRadius;Radius of the circular arcs by which all four corners of the rectangle are equally rounded. +5203;BottomXDim;The extent of the bottom line measured along the implicit x-axis. +5204;TopXDim;The extent of the top line measured along the implicit x-axis. +5205;YDim;The extent of the distance between the parallel bottom and top lines measured along the implicit y-axis. +5206;TopXOffset;Offset from the beginning of the top line to the bottom line, measured along the implicit x-axis. +5208;TotalCrossSectionArea;The total effective cross-section area of the reinforcement of a specific steel grade. +5209;SteelGrade;The nominal steel grade defined according to local standards. +5210;BarSurface;Indicator for whether the bar surface is plain or textured. +5211;EffectiveDepth;The effective depth, i.e. the distance of the specific reinforcement cross section area or reinforcement configuration in a row, counted from a common specific reference point. Usually the reference point is the upper surface (for beams and slabs) or a similar projection in a plane (for columns). +5212;NominalBarDiameter;The nominal diameter defining the cross-section size of the reinforcing bar. The bar diameter should be identical for all bars included in the specific reinforcement configuration. +5213;BarCount;The number of bars with identical nominal diameter and steel grade included in the specific reinforcement configuration. +5218;SectionType;An indicator whether a specific piece of a cross section is uniform or tapered in longitudinal direction. +5219;StartProfile;The cross section profile at the start point of the longitudinal section. +5220;EndProfile;The cross section profile at the end point of the longitudinal section. +5225;LongitudinalStartPosition;The start position in longitudinal direction for the section reinforcement properties. +5226;LongitudinalEndPosition;The end position in longitudinal direction for the section reinforcement properties. +5227;TransversePosition;The position for the section reinforcement properties in transverse direction. +5228;ReinforcementRole;The role, purpose or usage of the reinforcement, i.e. the kind of loads and stresses it is intended to carry, defined for the section reinforcement properties. +5229;SectionDefinition;Definition of the cross section profile and longitudinal section type. +5230;CrossSectionReinforcementDefinitions;The set of reinforcment properties attached to a section reinforcement properties definition. +5244;ApplicationDeveloper;"Name of the application developer, being requested to be member of the IAI. " +5245;Version;The version number of this software as specified by the developer of the application. +5246;ApplicationFullName;The full name of the application as specified by the application developer. +5247;ApplicationIdentifier;Short identifying name for the application. +5254;OwningUser;"Direct reference to the end user who currently ""owns"" this object. Note that IFC includes the concept of ownership transfer from one user to another and therefore distinguishes between the Owning User and Creating User." +5255;OwningApplication;"Direct reference to the application which currently ""Owns"" this object on behalf of the owning user, who uses this application. Note that IFC includes the concept of ownership transfer from one application to another and therefore distinguishes between the Owning Application and Creating Application." +5256;State;Enumeration that defines the current access state of the object. +5257;ChangeAction;Enumeration that defines the actions associated with changes made to the object. +5258;LastModifiedDate;Date and Time expressed in UTC (Universal Time Coordinated, formerly Greenwich Mean Time or GMT) at which the last modification was made by LastModifyingUser and LastModifyingApplication. +5259;LastModifyingUser;User who carried out the last modification using LastModifyingApplication. +5260;LastModifyingApplication;Application used to make the last modification. +5261;CreationDate;The date and time expressed in UTC (Universal Time Coordinated, formerly Greenwich Mean Time or GMT) when first created by the original OwningApplication. Once defined this value remains unchanged through the lifetime of the entity. +5276;Name;A unique name which is intended to describe the usage of the Table. +5277;Rows;Reference to information content of rows. +5278;Columns;The column information associated with this table. +5279;NumberOfCellsInRow;The number of cells in each row, this complies to the number of columns in a table. See WR2 that ensures that each row has the same number of cells. The actual value is derived from the first member of the Rows list. +5280;NumberOfHeadings;The number of headings in a table. This is restricted by WR3 to max. one. +5281;NumberOfDataRows;The number of rows in a table that contains data, i.e. total number of rows minus number of heading rows in table. +5285;RowCells;The data value of the table cell.. +5286;IsHeading;Flag which identifies if the row is a heading row or a row which contains row values. NOTE - If the row is a heading, the flag takes the value = TRUE. +5287;OfTable;Reference to the IfcTable, in which the IfcTableRow is defined (or contained). +5289;Name;The table column display name. +5290;Description;Descriptive text for the table column. +5291;Identifier;Table column identifier. +5292;Unit;The unit of measure to be used for this column's data. +5297;Operator;" +The Boolean operator used in the operation to create the result. +" +5298;FirstOperand;" +The first operand to be operated upon by the Boolean operation. +" +5299;SecondOperand;" +The second operand specified for the operation. +" +5300;Dim;The space dimensionality of this entity. It is identical with the space dimensionality of the first operand. A where rule ensures that both operands have the same space dimensionality. +5307;BaseSurface;Surface defining side of half space. +5308;AgreementFlag;The agreement flag is TRUE if the normal to the BaseSurface points away from the material of the IfcHalfSpaceSolid. Otherwise it is FALSE. +5309;Dim;The space dimensionality of this class, it is always 3 +5311;Enclosure;" +The box which bounds the resulting solid of the Boolean operation involving the half space solid for computational purposes only. + " +5314;Corner;Location of the bottom left corner (having the minimum values). +5315;XDim;Length attribute (measured along the edge parallel to the X Axis) +5316;YDim;Width attribute (measured along the edge parallel to the Y Axis) +5317;ZDim;Height attribute (measured along the edge parallel to the Z Axis). +5318;Dim;The space dimensionality of this class, it is always 3. +5320;Position;" +

                  Definition of the position coordinate system for the bounding polyline and the base surface.

                  +
                  " +5321;PolygonalBoundary;" +Two-dimensional polyline bounded curve, defined in the xy plane of the position coordinate system. +
                  +IFC2x Edition 3 CHANGE  The attribute type has been changed from IfcPolyline to its supertype IfcBoundedCurve with upward compatibility for file based exchange. +
                  +
                  " +5329;Dim;The space dimensionality of this class, it is always 3. +5333;Outer;A closed shell defining the exterior boundary of the solid. The shell normal shall point away from the interior of the solid. +5337;Voids;Set of closed shells defining voids within the solid. +5342;Voids; +5349;SweptArea;" +The surface defining the area to be swept. It is given as a profile definition within the xy plane of the position coordinate system. +" +5350;Position;" +Position coordinate system for the swept area, provided by a profile definition within the XY plane of the Position. +" +5354;ExtrudedDirection;" +The direction in which the surface, provided by SweptArea is to be swept. +" +5355;Depth;" +The distance the surface is to be swept along the ExtrudedDirection +." +5358;EndSweptArea;" +The surface defining the end of the swept area. It is given as a profile definition. The position coordinate system of the EndSwptArea is generated by translating the SELF\IfcSweptAreaSolid.Position along the SELF\IfcExtrudedAreaSolid.ExtrudedDirection by the distance of SELF\IfcExtrudedAreaSolid.Depth. +" +5362;Axis;" +Axis about which revolution will take place. +" +5363;Angle;" +The angle through which the sweep will be made. This angle is measured from the plane of the swept area provided by the XY plane of the position coordinate system. +" +5364;AxisLine;" +The line of the axis of revolution. +" +5368;EndSweptArea; +5371;Directrix;" +The curve used to define the sweeping operation. The solid is generated by sweeping the SELF\IfcSweptAreaSolid.SweptArea along the Directrix. +" +5372;StartParam;" +The parameter value on the Directrix at which the sweeping operation commences. If no value is provided the start of the sweeping operation is at the start of the Directrix.. +
                  +IFC2x4 CHANGE  The attribute has been changed to OPTIONAL with upward compatibility for file-based exchange. +
                  +
                  " +5373;EndParam;" +The parameter value on the Directrix at which the sweeping operation ends. If no value is provided the end of the sweeping operation is at the end of the Directrix.. +
                  +IFC2x4 CHANGE  The attribute has been changed to OPTIONAL with upward compatibility for file-based exchange. +
                  +
                  " +5374;ReferenceSurface;" +The surface containing the Directrix. +" +5376;Directrix;" +The curve used to define the sweeping operation. The solid is generated by sweeping the SELF\IfcSweptAreaSolid.SweptArea along the Directrix. +" +5377;StartParam;" +The parameter value on the Directrix at which the sweeping operation commences. If no value is provided the start of the sweeping operation is at the start of the Directrix. +" +5378;EndParam;" +The parameter value on the Directrix at which the sweeping operation ends. < style=""color:blue"">If no value is provided the end of the sweeping operation is at the end of the Directrix. +" +5379;FixedReference;" +The direction providing the fixed axis1 (x-axis) direction for orienting the swept area during the sweeping operation along the Directrix. +" +5381;TreeRootExpression;" +Boolean expression of primitives and regularized operators describing the solid. The root of the tree of Boolean expressions is given explicitly as an IfcBooleanResult entitiy or as a primitive (subtypes of IfcCsgPrimitive3D). +" +5391;Position;" +The placement coordinate system to which the parameters of each individual CSG primitive apply. +" +5392;Dim;" +The space dimensionality of this geometric representation item, it is always 3. +" +5394;XLength;" +The size of the block along the placement X axis. It is provided by the inherited axis placement through SELF\IfcCsgPrimitive3D.Position.P[1]. +" +5395;YLength;" +The size of the block along the placement Y axis. It is provided by the inherited axis placement through SELF\IfcCsgPrimitive3D.Position.P[2]. +" +5396;ZLength;" +The size of the block along the placement Z axis. It is provided by the inherited axis placement through SELF\IfcCsgPrimitive3D.Position.P[3]. +" +5398;XLength;" +The length of the base measured along the placement X axis. It is provided by the inherited axis placement through SELF\IfcCsgPrimitive3D.Position.P[1]. +" +5399;YLength;" +The length of the base measured along the placement Y axis. It is provided by the inherited axis placement through SELF\IfcCsgPrimitive3D.Position.P[2]. +" +5400;Height;" +The height of the apex above the plane of the base, measured in the direction of the placement Z axis, the SELF\IfcCsgPrimitive3D.Position.P[2]. +" +5402;Height;" +The distance between the planar circular faces of the cylinder. +" +5403;Radius;" +The radius of the cylinder. +" +5405;Height;" +The distance between the base of the cone and the apex. +" +5406;BottomRadius;" +The radius of the cone at the base. +" +5408;Radius;" +The radius of the sphere. +" +5411;Directrix;" +The curve used to define the sweeping operation. The solid is generated by sweeping a circular disk along the Directrix. +" +5412;Radius;" +The Radius of the circular disk to be swept along the directrix. Denotes the outer radius, if an InnerRadius is applied. +" +5413;InnerRadius;" +This attribute is optional, if present it defines the radius of a circular hole in the centre of the disk. +" +5414;StartParam;" +The parameter value on the Directrix at which the sweeping operation commences. If no value is provided the start of the sweeping operation is at the start of the Directrix.. +
                  +IFC2x4 CHANGE  The attribute has been changed to OPTIONAL with upward compatibility for file-based exchange. +
                  +
                  " +5415;EndParam;" +The parameter value on the Directrix at which the sweeping operation ends. If no value is provided the end of the sweeping operation is at the end of the Directrix.. +
                  +IFC2x4 CHANGE  The attribute has been changed to OPTIONAL with upward compatibility for file-based exchange. +
                  +
                  " +5420;FilletRadius;" +The fillet that is equally applied to all transitions between the segments of the IfcPolyline, providing the geometric representation for the Directrix. If omited, no fillet is applied to the segments. +" +5424;SpineCurve;A single composite curve, that defines the spine curve. Each of the composite curve segments correspond to the part between two cross-sections. +5425;CrossSections;A list of at least two cross sections, each defined within the xy plane of the position coordinate system of the cross section. The position coordinate system is given by the corresponding list CrossSectionPositions. +5426;CrossSectionPositions;Position coordinate systems for the cross sections that form the sectioned spine. The profiles defining the cross sections are positioned within the xy plane of the corresponding position coordinate system. +5427;Dim;The dimensionality of the spine curve is always 3. +5433;Elements;"The geometric elements which make up the geometric set, these may be points, curves or surfaces; but are required to be of the same coordinate space dimensionality." +5434;Dim;The space dimensionality of this class, it is identical to the first element in the set. A where rule ensures that all elements have the same dimensionality. +5443;FbsmFaces;The set of connected face sets comprising the face based surface model. +5444;Dim;The space dimensionality of this class, it is always 3. +5446;SbsmBoundary; +5447;Dim;The space dimensionality of this class, it is always 3. +5469;RefDirection;" +The direction used to determine the direction of the local X axis. If a value is omited that it defaults to [1.0, 0.0.]. +" +5470;P;" +P[1]: The normalized direction of the placement X Axis. This is [1.0,0.0] if RefDirection is omitted.
                  +P[2]: The normalized direction of the placement Y Axis. This is a derived attribute and is orthogonal to P[1]. If RefDirection is omitted, it defaults to [0.0,1.0] +
                  " +5477;Location;The geometric position of a reference point, such as the center of a circle, of the item to be located. +5478;Dim;The space dimensionality of this class, derived from the dimensionality of the location. +5501;LayerAssignment;"Assignment of the representation item to a single or multiple layer(s). The LayerAssignments can override a LayerAssignments of the IfcRepresentation it is used within the list of Items. +
                  + + IFC2x3 CHANGE  The inverse attribute LayerAssignments has been added. +
                  + + IFC2x4 CHANGE  The inverse attribute LayerAssignment has +been restricted to max 1. Upward compatibility for file based exchange is guaranteed. + +
                  +
                  " +5502;StyledByItem;" +Reference to the IfcStyledItem that provides presentation information to the representation, e.g. a curve style, including colour and thickness to a geometric curve. +
                  +IFC2x Edition 3 CHANGE  The inverse attribute StyledByItem has been added. +
                  +
                  " +5504;MappingSource;A representation map that is the source of the mapped item. It can be seen as a block (or cell or marco) definition. +5505;MappingTarget;A representation item that is the target onto which the mapping source is mapped. It is constraint to be a Cartesian transformation operator. +5507;MappingOrigin;"An axis2 placement that defines the position about which the mapped +representation is mapped." +5508;MappedRepresentation;A representation that is mapped to at least one mapped item. +5509;MapUsage; +5514;Axis1;The direction used to determine U[1], the derived X axis direction. +5515;Axis2;The direction used to determine U[2], the derived Y axis direction. +5516;LocalOrigin;The required translation, specified as a cartesian point. The actual translation included in the transformation is from the geometric origin to the local origin. +5517;Scale;The scaling value specified for the transformation. +5518;Scl;The derived scale S of the transformation, equal to scale if that exists, or 1.0 otherwise. +5519;Dim;"The space dimensionality of this class, determined by the space dimensionality of the local origin. " +5523;U;The list of mutually orthogonal, normalized vectors defining the transformation matrix T. They are derived from the explicit attributes Axis1 and Axis2 in that order. +5528;Scale2;The scaling value specified for the transformation along the axis 2. This is normally the y scale factor. +5529;Scl2;The derived scale S(2) of the transformation along the axis 2 (normally the y axis), equal to Scale2 if that exists, or equal to the derived Scl1 (normally the x axis scale factor) otherwise. +5532;DirectionRatios;"The components in the direction of X axis (DirectionRatios[1]), of Y axis (DirectionRatios[2]), and of Z axis (DirectionRatios[3]) " +5533;Dim;The space dimensionality of this class, defined by the number of real in the list of DirectionRatios. +5536;Axis3;The exact direction of U[3], the derived Z axis direction. +5537;U;The list of mutually orthogonal, normalized vectors defining the transformation matrix T. They are derived from the explicit attributes Axis3, Axis1, and Axis2 in that order. +5543;Scale2;The scaling value specified for the transformation along the axis 2. This is normally the y scale factor. +5544;Scale3;The scaling value specified for the transformation along the axis 3. This is normally the z scale factor. +5545;Scl2;The derived scale S(2) of the transformation along the axis 2 (normally the y axis), equal to Scale2 if that exists, or equal to the derived Scl1 (normally the x axis scale factor) otherwise. +5546;Scl3;The derived scale S(3) of the transformation along the axis 3 (normally the z axis), equal to Scale3 if that exists, or equal to the derived Scl1 (normally the x axis scale factor) otherwise. +5550;Coordinates;"The first, second, and third coordinate of the point location. If placed in a two or three dimensional rectangular Cartesian coordinate system, Coordinates[1] is the X coordinate, Coordinates[2] is the Y coordinate, and Coordinates[3] is the Z coordinate. " +5551;Dim;"The space dimensionality of this class, determined by the number of coordinates in the List of Coordinates. " +5558;BasisCurve;The curve to which point parameter relates. +5559;PointParameter;The parameter value of the point location. +5560;Dim;The space dimensionality of this class, determined by the space dimensionality of the basis curve. +5568;Dim;The space dimensionality of this abstract class, defined differently for all subtypes, i.e. for IfcLine, IfcConic and IfcBoundedCurve. +5576;Segments;"The component bounded curves, their transitions and senses. The transition attribute for the last segment defines the transition between the end of the last segment and the start of the first; this transition attribute may take the value discontinuous, which indicates an open curve." +5577;SelfIntersect;"Indication of whether the curve intersects itself or not; this is for information only. " +5578;NSegments;The number of component curves. +5579;ClosedCurve;"Indication whether the curve is closed or not; this is derived from the transition code of the last segment." +5584;BasisSurface;" +The surface on which the composite curve is defined. +" +5594;Dim;" +The space dimensionality of IfcSurface. It is always a three-dimensional geometric representation item. +
                  + + IFC2x4 CHANGE Derived attribute promoted from subtypes. + + +
                  +
                  " +5598;Position;"The position and orientation of the surface. This attribute is used in the definition of the parameterization of the surface. " +5601;Radius;" +The radius of the cylindrical surface. +" +5603;Axis;The exact direction of the local Z Axis. +5604;RefDirection;The direction used to determine the direction of the local X Axis. If necessary an adjustment is made to maintain orthogonality to the Axis direction. If Axis and/or RefDirection is omitted, these directions are taken from the geometric coordinate system. +5605;P;The normalized directions of the placement X Axis (P[1]) and the placement Y Axis (P[2]) and the placement Z Axis (P[3]). +5614;SweptCurve;The curve to be swept in defining the surface. The curve is defined as a profile within the position coordinate system. +5615;Position;Position coordinate system for the placement of the profile within the xy plane of the axis placement. +5619;AxisPosition;A point on the axis of revolution and the direction of the axis of revolution. +5620;AxisLine;The line coinciding with the axis of revolution. +5622;Axis;The direction of the local Z axis. +5623;Z;The normalized direction of the local Z axis. It is either identical with the Axis value, if given, or it defaults to [0.,0.,1.] +5627;Pnt;The location of the line. +5628;Dir;The direction of the line, the magnitude and units of Dir affect the parameterization of the line. +5631;Orientation;The direction of the vector. +5632;Magnitude;The magnitude of the vector. All vectors of Magnitude 0.0 are regarded as equal in value regardless of the orientation attribute. +5633;Dim;The space dimensionality of this class, it is derived from Orientation +5636;ExtrudedDirection;The direction of the extrusion. +5637;Depth;The depth of the extrusion, it determines the parameterization. +5638;ExtrusionAxis;The extrusion axis defined as vector. +5646;BasisSurface;The surface to be bound. +5647;OuterBoundary;The outer boundary of the surface. +5648;InnerBoundaries;An optional set of inner boundaries. They shall not intersect each other or the outer boundary. +5650;BasisSurface;Surface being trimmed. +5651;U1;First u parametric value. +5652;V1;First v parametric value. +5653;U2;Second u parametric value. +5685;KnotSpec;" +The description of the knot type. +" +5686;KnotVUpper;" +The number of distinct knots in the v parameter direction. +" +5687;KnotUUpper;" +The number of distinct knots in the u parameter direction. +" +5693;WeightsData;" +The weights associated with the control points in the rational case. +" +5695;Weights;" +Array (two-dimensional) of weight values constructed from the WeightsData. +" +5718;Transition;The state of transition (i.e., geometric continuity from the last point of this segment to the first point of the next segment) in a composite curve. +5719;SameSense;" +An indicator of whether or not the sense of the segment agrees with, or opposes, that of the parent curve. If SameSense is false, the point with highest parameter value is taken as the first point of the segment. +
                  + NOTE  If the datatype of ParentCurve is IfcTrimmedCurve, the value of SameSense overrides the value of IfcTrimmedCurve.SenseAgreement +
                  +
                  " +5720;ParentCurve;The bounded curve which defines the geometry of the segment. +5721;Dim;The space dimensionality of this class, defined by the dimensionality of the first ParentCurve. +5722;UsingCurves;The set of composite curves which use this composite curve segment as a segment. This set shall not be empty. +5725;ParamLength; +5733;Points;The points defining the polyline. +5736;BasisCurve;The curve to be trimmed. For curves with multiple representations any parameter values given as Trim1 or Trim2 refer to the master representation of the BasisCurve only. +5737;Trim1;The first trimming point which may be specified as a Cartesian point, as a real parameter or both. +5738;Trim2;The second trimming point which may be specified as a Cartesian point, as a real parameter or both. +5739;SenseAgreement;Flag to indicate whether the direction of the trimmed curve agrees with or is opposed to the direction of the basis curve. +5740;MasterRepresentation;Where both parameter and point are present at either end of the curve this indicates the preferred form. +5753;Degree;The algebraic degree of the basis functions. +5754;ControlPointsList;The list of control points for the curve. +5755;CurveForm;"Used to identify particular types of curve; it is for information only." +5756;ClosedCurve;"Indication of whether the curve is closed; it is for information only." +5757;SelfIntersect;"Indication whether the curve self-intersects or not; it is for information only." +5758;ControlPoints;The array of control points used to define the geometry of the curve. This is derived from the list of control points. +5759;UpperIndexOnControlPoints;"The upper index on the array of control points; the lower index is 0. +This value is derived from the control points list." +5763;KnotMultiplicities;" +The multiplicities of the knots. This list defines the number of times each knot in the knots list is to be repeated in constructing the knot array. +" +5764;Knots;" +The list of distinct knots used to define the B-spline basis functions. +" +5765;KnotSpec;" +The description of the knot type. This is for information only. +" +5766;UpperIndexOnKnots;" +The upper index on the knot arrays; the lower index is 1. +" +5770;WeightsData;" +The supplied values of the weights. +" +5771;Weights;" +The array of weights associated with the control points. This is derived from the weights data. +" +5784;Position;"The location and orientation of the conic. Further details of the interpretation of this attribute are given for the individual subtypes."" " +5786;Radius;The radius of the circle, which shall be greater than zero. +5788;SemiAxis1;The first radius of the ellipse which shall be positive. Placement.Axes[1] gives the direction of the SemiAxis1. +5789;SemiAxis2;The second radius of the ellipse which shall be positive. +5791;BasisCurve;The curve that is being offset. +5792;Distance;The distance of the offset curve from the basis curve. distance may be positive, negative or zero. A positive value of distance defines an offset in the direction which is normal to the curve in the sense of an anti-clockwise rotation through 90 degrees from the tangent vector T at the given point. (This is in the direction of orthogonal complement(T).) +5793;SelfIntersect;"An indication of whether the offset curve self-intersects; this is for information only." +5796;BasisCurve;The curve that is being offset. +5797;Distance;The distance of the offset curve from the basis curve. The distance may be positive, negative or zero. +5798;SelfIntersect;An indication of whether the offset curve self-intersects, this is for information only. +5799;RefDirection;The direction used to define the direction of the offset curve 3d from the basis curve. +5802;BasisSurface; +5803;ReferenceCurve; +5806;BasisSurface;The surface to which the parameter values relate. +5807;PointParameterU;The first parameter value of the point location. +5808;PointParameterV;The second parameter value of the point location. +5809;Dim;The space dimensionality of this class, determined by the space dimensionality of the basis surface. diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocDefined.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocDefined.csv new file mode 100644 index 0000000000000000000000000000000000000000..be57e315e9818fe28d08e22bab3bf6a759782563 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocDefined.csv @@ -0,0 +1,1860 @@ +275;IfcPresentableText;" + +

                  IfcPresentableText is a text string used to capture the content of a text literal for the purpose of presentation. The IfcPresentableText can include multiple lines of text, for which the line feed character LF, 0x0A, should be used to separate lines.

                  + +
                  +NOTE  The non printable characters are converted within the standard exchange format ISO 10303-21 (STEP physical file format), commonly the \X\09 represents the TAB, and \X\0A the LF character. +
                  + +
                  +NOTE  The IfcPresentableText is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation.

                  +
                  + +
                  +NOTE  Corresponding ISO 10303 name: presentable_text. Please refer to ISO/IS 10303-46:1994, p. 133 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New type in IFC2x2. +
                  + +
                  " +299;IfcTextFontName;" + +

                  Definition from CSS1 (W3C Recommendation): The value is a font family name and/or generic family name. Values are:

                  +
                  +
                  <family-name>
                  +
                  The name of a font family of choice. For example, ""gill"" and ""helvetica"" are font families.
                  +
                  <generic-family>
                  +
                  In the example above, the last value is a generic family name. The following generic families are defined: +
                    +
                  • 'serif' (Example: Times)
                  • +
                  • 'sans-serif' (Example: Helvetica)
                  • +
                  • 'cursive' (Example: Zapf-Chancery)
                  • +
                  • 'fantasy' (Example: Western)
                  • +
                  • 'monospace' (Example: Courier)
                  • +
                  +
                  +
                  +

                  It is encouraged to offer a generic font family as a last alternative.

                  + +
                  +NOTE  Corresponding CSS1 definitions are font-family. +
                  + +
                  +HISTORY  New type in IFC2x2 Addendum 2. +
                  + +
                  +IFC2x2 Addendum 2 CHANGE: The IfcFontFamily has been added. +
                  + +
                  " +300;IfcFontStyle;" + +

                  Definition from CSS1 (W3C Recommendation): The font-style property selects between normal (sometimes +referred to as ""roman"" or ""upright""), italic and oblique faces within a font family. Values are:

                  +
                    +
                  • normal
                  • +
                  • italic
                  • +
                  • oblique
                  • +
                  + +

                  A value of 'normal' selects a font that is classified as 'normal' in the user agents font database, while 'oblique' selects a font that is labeled 'oblique'. A value of 'italic' selects a font that is labeled 'italic', or, if that is not available, one labeled 'oblique'. The font that is labeled 'oblique' in the user agents font database may actually have been generated by electronically slanting a normal font. +

                  + +

                  Fonts with Oblique, Slanted or Incline in their names will typically be labeled 'oblique' in the user agents font database. Fonts with Italic, Cursive or Kursiv in their names will typically be labeled 'italic'. +

                  + +
                  +NOTE  Corresponding CSS1 definitions is font-style. +
                  + +
                  +HISTORY  New type in IFC2x3. +
                  + +" +302;IfcFontVariant;" + +

                  Definition from CSS1 (W3C Recommendation): The font-style property selects between normal and small-caps within a font family. Values are:

                  +
                    +
                  • normal
                  • +
                  • small-caps
                  • +
                  + +

                  Another type of variation within a font family is the small-caps. In a small-caps font the lower case letters look similar to the uppercase ones, but in a smaller size and with slightly different proportions. The 'font-variant' property selects that font.

                  + +

                  A value of 'normal' selects a font that is not a small-caps font, 'small-caps' selects a small-caps font. It is acceptable (but not required) in CSS1 if the small-caps font is a created by taking a normal font and replacing the lower case letters by scaled uppercase characters. As a last resort, uppercase letters will be used as replacement for a small-caps font. +

                  + +
                  +NOTE  Corresponding CSS1 definitions is font-variant. +
                  + +
                  +HISTORY  New type in IFC2x3. +
                  + +" +304;IfcFontWeight;" + +

                  Definition from CSS1 (W3C Recommendation): The 'font-weight' property selects the weight of the font. The values '100' to '900' form an ordered sequence, where each number indicates a weight that is at least as dark as its predecessor. The keyword 'normal' is synonymous with '400', and 'bold' is synonymous with '700'. Keywords other than 'normal' and 'bold' have been shown to be often confused with font names and a numerical scale was therefore chosen for the 9-value list. Values are:

                  + +
                    +
                  • normal
                  • +
                  • bold
                  • +
                  • 100 | 200 | 300 | 400 | 500 | 600 | 700 | 800 | 900
                  • +
                  + +

                  Fonts (the font data) typically have one or more properties whose values are names that are descriptive of the ""weight"" of a font. There is no accepted, universal meaning to these weight names. Their primary role is to distinguish faces of differing darkness within a single font family. Usage across font families is quite variant; for example a font that you might think of as being bold might be described as being Regular, Roman, Book, Medium, Semi- or DemiBold, Bold, or Black, depending on how black the ""normal"" face of the font is within the design. Because there is no standard usage of names, the weight property values in CSS1 are given on a numerical scale in which the value '400' (or 'normal') corresponds to the ""normal"" text face for that family. The weight name associated with that face will typically be Book, Regular, Roman, Normal or sometimes Medium.

                  + +

                  The association of other weights within a family to the numerical weight values is intended only to preserve the ordering of darkness within that family. However, the following heuristics tell how the assignment is done in typical cases:

                  +
                    +
                  • If the font family already uses a numerical scale with nine values (such as with OpenType), the font weights should be mapped directly.
                  • +
                  • If there is both a face labeled Medium and one labeled Book, Regular, Roman or Normal, then the Medium is normally assigned to the '500'.
                  • +
                  • The font labeled ""Bold"" will often correspond to the weight value '700'.
                  • +
                  • If there are fewer then 9 weights in the family, the default algorithm for filling the ""holes"" is as follows. If '500' is unassigned, it will be assigned the same font as '400'. If any of the values '600', '700', '800' or '900' remains unassigned, they are assigned to the same face as the next darker assigned keyword, if any, or the next lighter one otherwise. If any of '300', '200' or '100' remains unassigned, it is assigned to the next lighter assigned keyword, if any, or the next darker otherwise.
                  • +
                  + +

                  The following two examples illustrate the process. Assume four weights in the ""Example1"" family, from lightest to darkest: Regular, Medium, Bold, Heavy. And assume six weights in the ""Example2"" family: Book, Medium, Bold, Heavy, Black, ExtraBlack. Note how in the second example it has been decided not to assign ""Example2 ExtraBlack"" to anything. +

                  + +
                  Available faces       | Assignments   | Filling the holes
                  ----------------------+---------------+-------------------
                  ""Example1 Regular"" | 400 | 100, 200, 300
                  ""Example1 Medium"" | 500 |
                  ""Example1 Bold"" | 700 | 600
                  ""Example1 Heavy"" | 800 | 900
                  +
                  Available faces       | Assignments   | Filling the holes
                  ----------------------+---------------+-------------------
                  ""Example2 Book"" | 400 | 100, 200, 300
                  ""Example2 Medium"" | 500 |
                  ""Example2 Bold"" | 700 | 600
                  ""Example2 Heavy"" | 800 |
                  ""Example2 Black"" | 900 |
                  ""Example2 ExtraBlack"" | (none) |
                  +
                  + +
                  +NOTE  Corresponding CSS1 definitions is font-weight. +
                  + +
                  +HISTORY  New type in IFC2x2 Addendum 2. +
                  + +
                  " +3764;IfcURIReference;" + +

                  IfcURIReference provides for identifying a Uniform Resource Identifier, URI, as defined by the RFC3986 of the Network Working Group. A URI can be classified as a locator or a name or both, that is it may comprise a Uniform Resource Locator (URL) and/or a Uniform Resource Name (URN).

                  +
                    +
                  • A Uniform Resource Locator, URL, is a string conforming to a standardized format, which refers to a resource on the internet (such as a document or an image) by its location.
                  • +
                  • A Uniform Resource Name, URN, is intended to serve as persistent, location-independent resource identifier and is +designed to make it easy to map other namespaces (that share the properties of URNs) into URN-space.
                  • +
                  + +
                  +HISTORY New defined datatype in IFC 2x4. +
                  + +
                  " +3869;IfcLanguageId;" +

                  IfcLanguageId identifies the language in which a natural language text is expressed. It uses a language tag to identify the language.

                  +

                  The tag shall comply to the Internet Engineering Task Force (IETF) language tag as expressed in RFC 5646. A conforming program shall support the ""simple language"" subtag and the ""language-region"" tag format.

                  + +
                  +EXAMPLE  for simple language tags en (English), de (German), fr (France), or ja (Japanese), and for language-region tags en-US (English as used in United States), de-CH (German as used in German speaking part of Switzerland). +
                  + +

                  Type: IfcIdentifier

                  + +
                  +NOTE  The use of IfcLanguageId should conform to the use of language tags in HTML and XML as published by the W3C consortium. +
                  +
                  +HISTORY  New defined datatype in IFC2x4. +
                  + +
                  " +4001;IfcDateTime;" +

                  + This lexical representation is the [ISO 8601] extended + format CCYY-MM-DDThh:mm:ss where ""CC"" represents the + century, ""YY"" the year, ""MM"" the month and ""DD"" the day, + preceded by an optional leading ""-"" sign to indicate a + negative number. If the sign is omitted, ""+"" is assumed. + The letter ""T"" is the date/time separator and ""hh"", ""mm"", + ""ss"" represent hour, minute and second respectively. + Additional digits can be used to increase the precision of + fractional seconds if desired i.e the format ss.ss... with + any number of digits after the decimal point is supported. + The fractional seconds part is optional; other parts of the + lexical form are not optional. To accommodate year values + greater than 9999 additional digits can be added to the + left of this representation. Leading zeros are required if + the year value would otherwise have fewer than four digits; + otherwise they are forbidden. The year 0000 is prohibited. +

                  +
                  HISTORY: New type in IFC2x4
                  +
                  " +4002;IfcDate;" + +

                  The lexical representation for date is the reduced (right truncated) lexical representation for dateTime: CCYY-MM-DD. No left truncation is allowed. An optional following time zone qualifier is allowed as for dateTime. To accommodate year values outside the range from 0001 to 9999, additional digits can be added to the left of this representation and a preceding ""-"" sign is allowed.

                  + +
                  HISTORY: New type in IFC2x4
                  + +

                  Use definitions

                  +

                  All given values should be provided in context and converted into a Gregorian date context and be shall be processable by a receiving application.

                  + +
                  " +4003;IfcTime;" +

                  + The lexical representation for time is the left truncated + lexical representation for dateTime: hh:mm:ss.sss with + optional following time zone indicator. For example, to + indicate 1:20 pm for Eastern Standard Time which is 5 hours + behind Coordinated Universal Time (UTC), one would write: + 13:20:00-05:00. +

                  +
                  HISTORY: New type in IFC2x4
                  +
                  " +4004;IfcDuration;" + +

                  String representation of a time duration according to ISO8601:2000 ""Data elements and interchange formats - Information interchange - Representation of dates and times"" as defined in section 5.5.3 ""Representation of duration"".
                  +It is recommended to use the alternative format (section 5.5.4.2.2) in its extended version: PYYYY-MM-DDThh:mm:ss.
                  +EXAMPLE: P0002-10-15T10:30:20 (duration of two years, 10 months, 15 days, 10 hours, 30 minutes and 20 seconds).

                  + +
                  HISTORY: New type in IFC2x4
                  + +
                  " +4122;IfcDayInMonthNumber;" +

                  Definition from IAI: The IfcDayInMonthNumber is +an integer that defines the position of the specified day in a +month.

                  +

                  Type: INTEGER

                  +
                  NOTE Corresponding STEP +name: day_in_month_number, please refer to ISO/IS 10303-41:1994 +for the final definition of the formal +standard.
                  +
                  HISTORY New type in IFC +Release 1.5.1.
                  +IFC2x4 CHANGE Where rule +ValidRange added.
                  +
                  " +4124;IfcDayInWeekNumber;" +

                  Definition from IAI: The IfcDayInWeekNumber is +an integer that defines the position of the specified day in a +week. The positions have the following meaning (according to +ISO8601 ""the calendar week"") that assigns the ordinal day number +in the week to the Calender day name.

                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  Ordinal day numberCalendar day
                  +name
                  01Monday
                  02Tuesday
                  03Wednesday
                  04Thursday
                  05Friday
                  06Saturday
                  07Sunday
                  +

                  Type: INTEGER

                  +
                  HISTORY New type in +IFC2x4.
                  +
                  " +4126;IfcMonthInYearNumber;" +

                  Definition from IAI: The IfcDayInMonthNumber is +an integer that defines the position of the specified month in a +year. The positions have the following meaning (according to +ISO8601 ""calendar month"") that assigns the Calendar month number +to the Calender month name.

                  +
                  NOTE Refer to ISO 8601 for the definitions for +using the Gregorian calendar as the standard for the +identification of calendar days.
                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  Calendar month numberCalendar month
                  +name
                  01January
                  02February
                  03March
                  04April
                  05May
                  06June
                  07July
                  08August
                  09September
                  10October
                  11November
                  12December
                  +

                  Type: INTEGER

                  +
                  NOTE Corresponding STEP +name: month_in_year_number, please refer to ISO/IS 10303-41:1994 +for the final definition of the formal +standard.
                  +
                  HISTORY New type in IFC +Release 1.5.1.
                  +
                  " +4298;IfcCardinalPointReference;" +

                  An IfcCardinalPointReference is an index reference to +significant points of a section profile. This index is used to +describe the spatial relationship between the section of a member +and a reference axis of the same member.

                  + +
                  +HISTORY  New Type in IFC2x4. +
                  + +

                  Indexes 1...9 refer to points at the bounding box of a +profile. Indexes 10...19 refer to points defined by geometric +centroid (usually centre of gravity) and shear centre, and their +combinations with bounding box coordinates. In particular, the +following index values are specified in this IFC Release:

                  +
                    +
                  1. bottom left
                  2. +
                  3. bottom centre
                  4. +
                  5. bottom right
                  6. +
                  7. mid-depth left
                  8. +
                  9. mid-depth centre
                  10. +
                  11. mid-depth right
                  12. +
                  13. top left
                  14. +
                  15. top centre
                  16. +
                  17. top right
                  18. +
                  19. geometric centroid
                  20. +
                  21. bottom in line with the geometric centroid
                  22. +
                  23. left in line with the geometric centroid
                  24. +
                  25. right in line with the geometric centroid
                  26. +
                  27. top in line with the geometric centroid
                  28. +
                  29. shear centre
                  30. +
                  31. bottom in line with the shear centre
                  32. +
                  33. left in line with the shear centre
                  34. +
                  35. right in line with the shear centre
                  36. +
                  37. top in line with the shear centre
                  38. +
                  +

                  Other index values are possible but outside the scope of this +specification.

                  + +

                  Figure 283 illustrates cardinal point values.

                  + + + +

                  Figure 283 — Cardinal point values

                  + +

                  Figure 284 illustrates an example extrusion shape with arbitrary profile (IfcArbitraryClosedProfileDef), aligned ""mid-depth right"" on the member axis. The line of sight follows the extrusion direction Z which points into the drawing plane of above illustration. Hence, ""left"" is in the positive X direction of the IfcProfileDef. ""Top"" is in the positive Y direction of the IfcProfileDef.

                  + + + + +

                  Figure 284 — Cardinal point extrusion

                  + +
                  " +4311;IfcAmountOfSubstanceMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: An amount of substance measure is the value for the quantity of a substance when compared with the number of atoms in 0.012kilogram of carbon 12.

                  + +

                  Usually measure in mole (mol).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: amount_of_substance_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4312;IfcAngularVelocityMeasure;" + +

                  IfcAngularVelocityMeasure is a measure of the velocity of a body measured in terms of angle subtended per unit time.

                  +

                  Usually measured in radians/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + + " +4313;IfcAreaMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: An area measure is the value of the extent of a surface.

                  +

                  Usually measured in square metre (m2).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: area_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4314;IfcBoolean;" + +

                  IfcBoolean is a defined data type of simple data type Boolean. It is required since a select type (IfcSimpleValue) cannot directly include simple types in its select list. A boolean type can have value TRUE or FALSE.

                  + +

                  Type: BOOLEAN

                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  + + " +4315;IfcCompoundPlaneAngleMeasure;" + +

                  IfcCompoundPlaneAngleMeasure is a compound measure of plane angle in degrees, minutes, seconds, and optionally millionth-seconds of arc.

                  + +
                  +NOTE: IfcCompoundPlaneAngleMeasure is used where angles need to be described to an accuracy as fine as one millionth of a degree and expressed as parts of an arc. It may be used for angular measurement by surveyors or for other angular measurements where precision is required. Another usage is exact or approximate global positioning against a geographic coordinate systems using longitude and latitude. +
                  + +
                  +NOTE: While the unit of measurement of the type IfcPlaneAngleMeasure depends on unit assignment (radian or degree or other derived units; globally at the IfcPoject or locally at an IfcMeasureWithUnit), the units of IfcCompoundPlaneAngleMeasure are always degrees, minutes, seconds, and millionth-seconds irrespective of unit assignments. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +

                  Type: LIST [3:4] OF INTEGER

                  + +

                  Value restrictions

                  + +
                    +
                  • The first integer measure is the number of degrees and is generally not range-restricted. However, when IfcCompoundPlaneAngleMeasure is used to express geographic coordinates, only latitudes of [-90, 90] and longitudes of [-180, 180] are used in practice.
                  • +
                  • The second integer measure is the number of minutes and shall be in the range (-60, 60).
                  • +
                  • The third integer measure is the number of seconds and shall be in the range (-60, 60).
                  • +
                  • The optional fourth integer measure is the number of millionth-seconds and shall be in the range (-1 000 000, 1 000 000).
                  • +
                  + +

                  Signedness

                  + +

                  All measure components have the same sign (positive or negative). It is therefore trivial to convert between floating point representation (decimal degrees) and compound representation regardless whether the angle is greater or smaller than zero. Example:

                  + +
                  +LOCAL
                  +  a : IfcPlaneAngleMeasure := -50.975864;  (* decimal degrees, -50° 58' 33" 110400 *)
                  +  b : IfcPlaneAngleMeasure;
                  +  c : IfcCompoundPlaneAngleMeasure;
                  +  s : IfcText;
                  +END_LOCAL;
                  +
                  +(* convert from float to compound *)
                  +  c[1] :=    a;                                           -- -50
                  +  c[2] :=   (a - c[1]) * 60;                              -- -58
                  +  c[3] :=  ((a - c[1]) * 60 - c[2]) * 60;                 -- -33
                  +  c[4] := (((a - c[1]) * 60 - c[2]) * 60 - c[3]) * 1.e6;  -- -110400
                  +
                  +(* convert from compound to float *)
                  +  b := c[1] + c[2]/60. + c[3]/3600. + c[4]/3600.e6;       -- -50.975864
                  +
                  + +

                  Use in string representations

                  + +

                  When a compound plane angle measure is formatted for display or printout, the signs of the fractional components will usually be discarded because, to a human reader, the sign of the first component alone already indicates the sense of the angle:

                  + +
                  +(* convert from compound to human-readable string *)
                  +  s := FORMAT(c[1], '+##')     + "000000B0"
                  +     + FORMAT(ABS(c[2]), '##') + ''''
                  +     + FORMAT(ABS(c[3]), '##') + '"'
                  +     + FORMAT(ABS(c[4]), '##');  -- -50° 58' 33" 110400 +
                  + +

                  Another often encountered display format of latitudes and longitudes is to omit the signs and print N, S, E, W indicators instead, for example, 50°58'33"S. When stored as IfcCompoundPlaneAngleMeasure however, a compound plane angle measure is always signed, with same sign of all components.

                  + +
                  " +4321;IfcContextDependentMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: Is the value of a physical quantity as defined by an application context.

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: context_dependent_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4322;IfcCountMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A count measure is the value of a count.

                  +

                  Type: NUMBER

                  + +
                  +NOTE Corresponding ISO 10303 name: count_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4323;IfcDescriptiveMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A descriptive measure is a human interpretable definition of a quantifiable value.

                  +

                  Type: STRING

                  + +
                  +NOTE Corresponding ISO 10303 name:descriptive_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4324;IfcDynamicViscosityMeasure;" + +

                  IfcDynamicViscosityMeasure is a measure of the viscous resistance of a medium.

                  + +

                  Usually measured in Pascal second (Pa s).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4325;IfcElectricCurrentMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: The value for the movement of electrically charged particles.

                  +

                  Usually measured in Ampere (A).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: electric_current_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4326;IfcElectricVoltageMeasure;" + +

                  IfcElectricVoltageMeasure is a measure of electromotive force.

                  +

                  Usually measured in Volts (V, W/A).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4327;IfcEnergyMeasure;" + +

                  IfcEnergyMeasure is a measure of energy required or used.

                  +

                  Usually measured in Joules, (J, Nm).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4328;IfcFrequencyMeasure;" + +

                  IfcFrequencyMeasure is a measure of the number of times that an item vibrates in unit time.

                  +

                  Usually measured in cycles/s or Herz (Hz).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4329;IfcHeatFluxDensityMeasure;" + +

                  IfcHeatFluxDensityMeasure is a measure of the density of heat flux within a body.

                  +

                  Usually measured in W/m2 (J/s m2).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + + " +4330;IfcInteger;" + +

                  IfcInteger is a defined type of simple data type Integer. It is required since a select type (IfcSimpleValue) cannot include directly simple types in its select list.

                  + +

                  In principle, the domain of IfcInteger (being an Integer) is all integer numbers. Here the number of bits used for the IfcInteger representation is unconstrained, but in practice it is implementation specific.

                  + +

                  Type: INTEGER

                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4331;IfcIntegerCountRateMeasure;" + +

                  IfcIntegerCountRateMeasure is a measure of the integer number of units flowing per unit time.

                  + +
                  +EXAMPLE: This measure may be used for measuring integer units per second or per hour. For example, it may be used to measure the number of books per hour passing along a part of a mechanical book handling system, the number of people per hour travelling along a moving walkway or the number of vehicles per hour travelling along a section of road. +
                  + +

                  Type: INTEGER

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4332;IfcKinematicViscosityMeasure;" + +

                  IfcKinematicViscosityMeasure is a measure of the viscous resistance of a medium to a moving body.

                  +

                  Usually measured in m2/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + + " +4333;IfcLengthMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A length measure is the value of a distance.

                  +

                  Usually measured in millimeters (mm).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: length_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4334;IfcLinearVelocityMeasure;" + +

                  IfcLinearVelocityMeasure is a measure of the velocity of a body measured in terms of distance moved per unit time.

                  +

                  Usually measured in m/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + " +4335;IfcLuminousIntensityMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A luminous intensity measure is the value for the brightness of a body.

                  +

                  Usually measured in candela (cd).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: luminous_intensity_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4336;IfcMassDensityMeasure;" + +

                  IfcMassDensityMeasure is a measure of the density of a medium.

                  +

                  Usually measured in kg/m3.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + " +4337;IfcMassFlowRateMeasure;" + +

                  IfcMassFlowRateMeasure is a measure of the mass of a medium flowing per unit time.

                  +

                  Usually measured in kg/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4338;IfcMassMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A mass measure is the value of the amount of matter that a body contains.

                  +

                  Usually measured in kilograms (kg) or grams (g).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: mass_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4339;IfcMonetaryMeasure;" + +

                  A monetary measure is the value of an amount of money without regard to its currency.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4340;IfcNumericMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A numeric measure is the numeric value of a physical quantity.

                  +

                  Type: NUMBER

                  + +
                  +NOTE Corresponding ISO 10303 name: numeric_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + + " +4341;IfcParameterValue;" + +

                  Definition from ISO/CD 10303-41:1992: A parameter value is the value which specifies the amount of a +parameter in some parameter space.

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding STEP name: parameter_value, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4342;IfcPlaneAngleMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A plane angle measure is the value of an angle in a plane. + +

                  Usually measured in radian (rad, m/m = 1), but also grads may be used. The grad unit may be declared as a conversion based unit based on radian unit.

                  + +
                  +NOTE IfcPlaneAngleMeasure is used where angles need to be described to an accuracy of less than one degree and expressed as decimal parts of an angle. It is widely used for angular measurement except for situations where accuracy needs to be defined using arc measurement; for which purpose the IfcCompoundPlaneAngleMeasure is provided. +
                  + +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: plane_angle_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4343;IfcPositiveLengthMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A positive length measure is a length measure that is greater than zero.

                  +

                  Type: IfcLengthMeasure

                  + +
                  +NOTE Corresponding ISO 10303 name: positive_length_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4345;IfcPositivePlaneAngleMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: Positive plane angle measure is a plane angle measure that is greater than zero.

                  +

                  Type: IfcPlaneAngleMeasure

                  + +
                  +NOTE Corresponding STEP name: positive_plane_angle_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4347;IfcPositiveRatioMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A positive ratio measure is a ratio measure that is greater than zero.

                  +

                  Type: IfcRatioMeasure

                  + +
                  +NOTE Corresponding ISO 10303 name: positive_ratio_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +" +4349;IfcRatioMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A ratio measure is the value of the relation between two +physical quantities that are of the same kind.

                  + +
                  +NOTE: Input given in percent is to be divided by 100% when stored as an IfcRatioMeasure. For example, 25% becomes 0.25. +
                  + +

                  Type: REAL

                  + +
                  +NOTE Corresponding STEP name: ratio_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4350;IfcPowerMeasure;" + +

                  IfcPowerMeasure is a measure of power required or used.

                  +

                  Usually measured in Watts (W, J/s).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  + " +4351;IfcPressureMeasure;" + +

                  IfcPressureMeasure is a measure of the quantity of a medium acting on a unit area.

                  +

                  Usually measured in Pascals (Pa, N/m2).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4352;IfcReal;" + +

                  IfcReal is a defined type of simple data type REAL. It is required since a select type (IfcSimpleValue), cannot directly include simple types in its select list.

                  + +

                  In principle, the domain of IfcReal (being a Real) is all rational, irrational and scientific real numbers. Here the precision is unconstrained, but in practice it is implementation specific.

                  + +

                  Type: REAL

                  + +
                  +HISTORY: New type in IFC Release 1.5.1. +
                  + +
                  " +4353;IfcSolidAngleMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A solid angle measure is the value of an angle in a solid.

                  +

                  Usually measured in Steradians, (sr, m2/m2).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: solid_angle_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4354;IfcIdentifier;" +

                  Definition from ISO/CD 10303-41:1992: An identifier is an alphanumeric string which allows an individual thing to be identified. It may not provide natural-language meaning.

                  + +

                  Type: STRING of up to 255 characters

                  + +
                  NOTE Corresponding STEP name: identifier, please refer to ISO/IS 10303-41 for the final definition of the formal standard.
                  + +
                  HISTORY New type in IFC Release 2x.
                  +IFC 2x4 CHANGE: Previously recommended size restriction of 255 characters is now mandatory.
                  + +

                  As a merely machine-readable string for identification purposes, an identifier is usually machine-generated and locale-independent (in contrast to human-readable labels, IfcLabel).

                  + +

                  Per ISO 10303-11, the set of characters that may appear in STRINGs is defined in ISO 10646. The encoding of characters in case of file-based exchange is defined in ISO 10303-21 (STEP physical files) and ISO 10303-28 (XML files). Among else, these specifications define the encoding of 8-bit characters from ISO 8859-1...-16 and of 2-byte Unicode characters.

                  + +

                  Note that while IfcIdentifier is restricted to 255 characters, the size in exchange files after encoding may be considerably larger than 255 octets, depending on the particular encoding and on the contents of the identifier.

                  + +
                  " +4355;IfcThermalAdmittanceMeasure;" + +

                  IfcThermalAdmittanceMeasure is the measure of the ability of a surface to smooth out temperature variations.

                  +

                  Usually measured in Watt / m2 Kelvin.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4356;IfcThermalResistanceMeasure;" + +

                  IfcThermalResistanceMeasure is a measure of the resistance offered by a body to the flow of energy.

                  +

                  Usually measured in m2 Kelvin/Watt.

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4357;IfcThermalTransmittanceMeasure;" + +

                  IfcThermalTransmittanceMeasure is a measure of the rate at which energy is transmitted through a body.

                  +

                  Usually measured in Watts/m2 Kelvin.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4358;IfcThermodynamicTemperatureMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A thermodynamic temperature measure is the value for the degree of heat of a body.

                  +

                  Usually measured in degrees Kelvin (K).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: thermodynamic_temperature_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  + " +4359;IfcTimeMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A time measure is the value of the duration of periods.

                  +

                  Measured in seconds (s) or days (d) or other units of time.

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: time_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4360;IfcTimeStamp;" + +

                  IfcTimeStamp is an indication of date and time by measuring the number of seconds which have elapsed since the beginning of the year 1970.

                  +

                  Type: INTEGER

                  + +
                  + HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4361;IfcVolumeMeasure;" + +

                  Definition from ISO/CD 10303-41:1992: A volume measure is the value of the solid content of a body.

                  +

                  Usually measured in cubic metre (m3).

                  +

                  Type: REAL

                  + +
                  +NOTE Corresponding ISO 10303 name: volume_measure, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
                  + +
                  +HISTORY New type in IFC Release 1.5.1. +
                  + +
                  " +4362;IfcVolumetricFlowRateMeasure;" + +

                  IfcVolumetricFlowRateMeasure is a measure of the volume of a medium flowing per unit time.

                  +

                  Usually measured in m3/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2.0. +
                  + +
                  " +4387;IfcLabel;" +

                  Definition from ISO/CD 10303-41:1992: A label is the term by which something may be referred to. It is a string which represents the human-interpretable name of something and shall have a natural-language meaning.

                  + +

                  Type: STRING of up to 255 characters

                  + +
                  NOTE Corresponding STEP name: label, please refer to ISO/IS 10303-41 for the final definition of the formal standard.
                  + +
                  HISTORY New type in IFC Release 2x.
                  +IFC 2x4 CHANGE: Previously recommended size restriction of 255 characters is now mandatory.
                  + +

                  As a human-readable string for naming purposes, a label is usually human-specified and locale-dependent (in contrast to purely machine-readable identifiers, IfcIdentifier).

                  + +

                  Per ISO 10303-11, the set of characters that may appear in STRINGs is defined in ISO 10646. The encoding of characters in case of file-based exchange is defined in ISO 10303-21 (STEP physical files) and ISO 10303-28 (XML files). Among else, these specifications define the encoding of 8-bit characters from ISO 8859-1...-16 and of 2-byte Unicode characters.

                  + +

                  Note that while IfcLabel is restricted to 255 characters, the size in exchange files after encoding may be considerably larger than 255 octets, depending on the particular encoding and on the contents of the label.

                  + +
                  " +4426;IfcNormalisedRatioMeasure;" + +

                  IfcNormalisedRatioMeasure is a dimensionless measure to express ratio values ranging from 0.0 to 1.0.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4428;IfcComplexNumber;" + +

                  IfcComplexNumber is a representation of a complex number expressed as an array with two elements. + The first element (index 1) denotes the real component which is the numerical + component of a complex number whose square roots can be calculated explicitly. + The second element (index 2) denotes the imaginary component which is the numerical + component of a complex number whose square roots cannot be determined other + than through the provision of the square of the imaginary number j where j^2 = -1. + Note that the imaginary component may be referred to as i in certain references. +

                  + +

                  + Type: ARRAY [1:2] OF REAL +

                  + +
                  +HISTORY New type in IFC Release 2x2. +
                  + +
                  " +4430;IfcNonNegativeLengthMeasure;" + +

                  A non-negative length measure is a length measure that is greater than or equal to zero.

                  + +

                  Type: IfcLengthMeasure

                  + +
                  +HISTORY New type in IFC Release 2x4. +
                  + +
                  " +4444;IfcText;" +

                  Definition from ISO/CD 10303-41:1992: A text is an alphanumeric string of characters which is intended to be read and understood by a human being. It is for information purposes only.

                  + +

                  Type: STRING

                  + +
                  NOTE Corresponding STEP name: text, please refer to ISO/IS 10303-41 for the final definition of the formal standard.
                  + +
                  HISTORY New type in IFC Release 2x.
                  + +

                  Per ISO 10303-11, the set of characters that may appear in STRINGs is defined in ISO 10646. The encoding of characters in case of file-based exchange is defined in ISO 10303-21 (STEP physical files) and ISO 10303-28 (XML files). Among else, these specifications define the encoding of 8-bit characters from ISO 8859-1...-16 and of 2-byte Unicode characters.

                  + +

                  Note that while IfcText is not formally restricted in length, the size of a string in ISO 10303-21:2002 conforming exchange files must not exceed 32767 octets after encoding and escaping.

                  + +
                  " +4445;IfcLogical;" + +

                  IfcLogicalIfcSimpleValue) cannot directly include simple types in its select list). Logical datatype can have values TRUE, FALSE or UNKNOWN.

                  + +

                  Type: LOGICAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4516;IfcThermalConductivityMeasure;" + +

                  IfcThermalConductivityMeasure is a measure of thermal conductivity.

                  +

                  Usually measured in Watt / m Kelvin.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4517;IfcMolecularWeightMeasure;" + +

                  IfcMolecularWeightMeasure is a measure of molecular weight of material (typically gas).

                  +

                  Usually measured in g/mole.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4518;IfcVaporPermeabilityMeasure;" + +

                  IfcVaporPermeabilityMeasure is a measure of vapor permeability.

                  +

                  Usually measured in kg / s m Pascal.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4519;IfcMoistureDiffusivityMeasure;" + +

                  IfcMoistureDiffusivityMeasure is a measure of moisture diffusivity.

                  +

                  Usually measured in m3/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4520;IfcIsothermalMoistureCapacityMeasure;" + +

                  IfcIsothermalMoistureCapacityMeasure is a measure of isothermal moisture capacity.

                  +

                  Usually measured in m3/kg.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4521;IfcSpecificHeatCapacityMeasure;" + +

                  IfcSpecificHeatCapacityMeasure defines the specific heat of material: The heat energy absorbed per temperature unit.

                  +

                  Usually measured in J / kg Kelvin.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4522;IfcMagneticFluxDensityMeasure;" + +

                  IfcMagneticFluxDensityMeasure is a measure of the magnetic flux density.

                  +

                  Usually measured in Tesla (T, Weber/m2 = V s/m2).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4523;IfcMagneticFluxMeasure;" + +

                  IfcMagneticFluxMeasure is a measure of the magnetic flux.

                  +

                  Usually measured in Weber (Wb, V s).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4524;IfcLuminousFluxMeasure;" + +

                  IfcLuminousFluxMeasure is a measure of the luminous flux.

                  +

                  Usually measured in Lumen (lm, Candela Steradian).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4525;IfcForceMeasure;" + +

                  IfcForceMeasure is a measure of the force.

                  +

                  Usually measured in Newton (N, kg m/s2).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4526;IfcInductanceMeasure;" + +

                  IfcInductanceMeasure is a measure of the inductance.

                  +

                  Usually measure in Henry (H, Weber/A = V s/A).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4527;IfcIlluminanceMeasure;" + +

                  IfcIlluminanceMeasure is a measure of the illuminance.

                  +

                  Usually measured in Lux (lx, Lumen/m2 = Candela Steradian/m2).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4528;IfcElectricResistanceMeasure;" + +

                  IfcElectricResistanceMeasure is a measure of the electric resistance.

                  +

                  Usually measured in Ohm (V/A).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4529;IfcElectricConductanceMeasure;" + +

                  IfcElectricConductanceMeasure is a measure of the electric conductance.

                  +

                  Usually measured in Siemens (S, 1/Ohm = A/V).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4530;IfcElectricChargeMeasure;" + +

                  IfcElectricChargeMeasure is a measure of the electric charge.

                  +

                  Usually measured in Coulomb (C, A s).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4531;IfcDoseEquivalentMeasure;" + +

                  IfcDoseEquivalentMeasure is a measure of the radioactive dose equivalent.

                  +

                  Usually measured in Sievert (Sv, J/kg).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4532;IfcElectricCapacitanceMeasure;" + +

                  IfcElectricCapacitanceMeasure is a measure of the electric capacitance.

                  +

                  Usually measured in Farad (F, C/V = A s/V).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4533;IfcAbsorbedDoseMeasure;" + +

                  IfcAbsorbedDoseMeasure is a measure of the absorbed radioactivity dose.

                  +

                  Usually measured in Gray (Gy, J/kg).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4534;IfcRadioActivityMeasure;" + +

                  IfcRadioActivityMeasure is a measure of activity of radionuclide.

                  +

                  Usually measured in Becquerel (Bq, 1/s).

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4535;IfcRotationalFrequencyMeasure;" + +

                  IfcRotationalFrequencyMeasure is a measure of the number of cycles that an item revolves in unit time.

                  +

                  Usually measured in cycles/s.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4536;IfcTorqueMeasure;" + +

                  IfcTorqueMeasure is a measure of the torque or moment of a couple.

                  +

                  Usually measured in N m.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4537;IfcAccelerationMeasure;" + +

                  IfcAccelerationMeasure is a measure of acceleration.

                  +

                  Usually measured in m/s2.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4538;IfcLinearForceMeasure;" + +

                  IfcLinearForceMeasure is a measure of linear force.

                  +

                  Usually measured in N/m.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4539;IfcLinearStiffnessMeasure;" + +

                  IfcLinearStiffnessMeasureA measure of linear stiffness.

                  +

                  Usually measured in N/m.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4540;IfcModulusOfSubgradeReactionMeasure;" + +

                  IfcModulusOfSubgradeReactionMeasure is a geotechnical measure describing interaction between foundation structures and the soil. May also be known as bedding measure.

                  +

                  Usually measured in N/m3.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +

                  Figure 290 illustrates elastic support of a planar member.

                  + + + +

                  Figure 290 — Modulus of subgrade reaction measure

                  + +
                  " +4541;IfcModulusOfElasticityMeasure;" + +

                  IfcModulusOfElasticityMeasure is a measure of modulus of elasticity.

                  +

                  Usually measured in N/m2.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4542;IfcMomentOfInertiaMeasure;" + +

                  IfcMomentOfInertiaMeasure is a measure of moment of inertia.

                  +

                  Usually measured in m4.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4543;IfcPlanarForceMeasure;" + +

                  IfcPlanarForceMeasure is a measure of force on an area.

                  +

                  Usually measured in N/m2.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4544;IfcRotationalStiffnessMeasure;" + +

                  IfcRotationalStiffnessMeasure is a measure of rotational stiffness.

                  +

                  Usually measured in Nm/rad.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4545;IfcShearModulusMeasure;" + +

                  IfcShearModulusMeasure is a measure of shear modulus.

                  +

                  Usually measured in N/m2.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4546;IfcLinearMomentMeasure;" + +

                  IfcLinearMomentMeasure is a measure of linear moment.

                  +

                  Usually measured in Nm/m.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x. +
                  + +
                  " +4547;IfcLuminousIntensityDistributionMeasure;" + +

                  IfcLuminousIntensityDistributionMeasure is a measure of the luminous intensity of a light source that changes according to the direction of the ray. It is normally based on some standardized distribution light distribution curves.

                  + +

                  Usually measured in Candela/Lumen (cd/lm) or (cd/klm).

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4548;IfcCurvatureMeasure;" + +

                  IfcCurvatureMeasure is a measure for curvature, which is defined as the change of slope per length. + This is typically a computed value in structural analysis. + It is usually measured in rad/m. +

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4549;IfcMassPerLengthMeasure;" + +

                  IfcMassPerLengthMeasure is a measure for mass per length. For example for rolled steel profiles the weight of + an imaginary beam is usually expressed by kg/m length for cost calculation and + structural analysis purposes. +

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4550;IfcModulusOfLinearSubgradeReactionMeasure;" + +

                  IfcModulusOfLinearSubgradeReactionMeasure is a measure for modulus of linear subgrade reaction, which expresses the elastic bedding of a linear structural element per length, such as for a beam. It is typically measured in N/m^2.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x2. +
                  + +
                  + " +4551;IfcModulusOfRotationalSubgradeReactionMeasure;" + +

                  IfcModulusOfRotationalSubgradeReactionMeasure is a measure for modulus of rotational subgrade reaction, which expresses the rotational elastic bedding of a linear structural element per length, such as for a beam. It is typically measured in Nm/(m*rad). +

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4552;IfcRotationalMassMeasure;" + +

                  The rotational mass measure denotes the inertia of a body with respect to angular acceleration.

                  +

                  It is usually measured in kg*m^2.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4553;IfcSectionalAreaIntegralMeasure;" + +

                  The sectional area integral measure is typically used in torsional analysis. It is usually measured in m^5.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4554;IfcSectionModulusMeasure;" + +

                  IfcSectionModulusMeasure is a measure for the resistance of a cross section against bending or torsional moment. It is usually measured in m^3.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC Release 2x2. +
                  + +
                  " +4555;IfcTemperatureGradientMeasure;" + +

                  The temperature gradient measures the difference of a temperature per lenght, as for instance used in an external wall or its layers. It is usually measured in K/m.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4556;IfcThermalExpansionCoefficientMeasure;" + +

                  IfcThermalExpansionCoeffientMeasure is a measure of the thermal expansion coefficient of a material, which expresses its elongation (as a ratio) per temperature difference. It is usually measured in 1/K. A positive elongation per (positive) rise of temperature is expressed by a positive value.

                  +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4557;IfcWarpingConstantMeasure;" + +

                  IfcWarpingConstantMeasure is a measure for the warping constant or warping resistance of a cross section under torsional loading. It is usually measured in m^6.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4558;IfcWarpingMomentMeasure;" + +

                  The warping moment measure is a measure for the warping moment, which occurs in warping torsional analysis. It is usually measured in kN*m^2.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4559;IfcSoundPowerMeasure;" + +

                  A sound power measure is a measure of total radiated noise with units of decibels with a reference value of picowatts.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4560;IfcSoundPressureMeasure;" + +

                  A sound pressure measure is a measure of the pressure fluctuations superimposed over the ambient pressure level with units of decibels with a reference value of micropascals.

                  + +

                  Type: REAL

                  + +
                  +HISTORY New type in IFC2x2. +
                  + +
                  " +4561;IfcHeatingValueMeasure;" + +

                  IfcHeatingValueMeasure defines the amount of energy released (usually in MJ/kg) when a fuel is burned.

                  + +
                  +HISTORY: This is new type in IFC2x2. +
                  + +
                  " +4563;IfcPHMeasure;" + +

                  IfcPHMeasure is a measure of the molar hydrogen ion concentration in a liquid (usually defined as the measure of acidity) in a range from 0 to 14.

                  + +
                  +HISTORY: New type in IFC 2x2. +
                  + +
                  " +4565;IfcIonConcentrationMeasure;" + +

                  IfcIonConcentrationMeasure is a measure of particular ion concentration in a liquid, given in mg/L.

                  + +
                  +HISTORY: New type in IFC2x2. +
                  + +
                  " +4566;IfcTemperatureRateOfChangeMeasure;" + +

                  The temperature rate of change measures the difference of a temperature per time (positive: rise, negative: fall), as for instance used with heat sensors. It is for example measured in K/s (Kelvin per second).

                  + +

                  Type: REAL

                  + +
                  +HISTORY  New type in IFC2x4. +
                  + +
                  " +4777;IfcTextAlignment;" + +

                  Definition from CSS1 (W3C Recommendation): This property describes how text is aligned within the element. The actual justification algorithm used is user agent and human language dependent. If 'justify' is not supported, the user agent will supply a replacement. Typically, this will be 'left' for western languages. Values are:

                  +
                    +
                  • left
                  • +
                  • right
                  • +
                  • center
                  • +
                  • justify
                  • +
                  + +
                  +NOTE  Corresponding CSS1 definition is text-align. +
                  + +
                  +HISTORY  New type in IFC2x3. +
                  + +
                  " +4779;IfcTextDecoration;" + +

                  Definition from CSS1 (W3C Recommendation): This property describes decorations that are added to the text of an element. A value of 'blink' causes the text to blink.. Values are:

                  +
                    +
                  • none
                  • +
                  • underline
                  • +
                  • overline
                  • +
                  • line-through
                  • +
                  • blink
                  • +
                  + +

                  User agents must recognize the keyword 'blink', but are not required to support the blink effect.

                  + +
                  +NOTE  Corresponding CSS1 definition is text-decoration. +
                  + +
                  +HISTORY  New type in IFC2x3. +
                  + +
                  " +4781;IfcTextTransformation;" + +

                  Definition from CSS1 (W3C Recommendation): This property describes how the cases of characters are handled. Values are:

                  +
                    +
                  • capitalize: uppercases the first character of each word
                  • +
                  • uppercase: uppercases all letters of the element
                  • +
                  • lowercase: lowercases all letters of the element
                  • +
                  • none
                  • +
                  + +
                  +NOTE  Corresponding CSS1 definition is text-transform. +
                  + +
                  +HISTORY  New type in IFC2x3. +
                  + +
                  " +4865;IfcSpecularExponent;" + +

                  The IfcSpecularExponent defines the datatype for exponent determining the sharpness of the 'reflection'. reflection is made sharper with large values of the exponent, such as 10.0. Small values, such as 1.0, decrease the specular fall-off.

                  + +

                  IfcSpecularExponent is of type REAL.

                  + +
                  +NOTE: The datatype relates to the definition of specular_exponent in ISO 10303-46 entity surface_style_reflectance_ambient_diffuse_specular. +
                  + +
                  +HISTORY: New type in IFC2x2. +
                  + +
                  " +4866;IfcSpecularRoughness;" + +

                  The IfcSpecularRoughness defines the datatype for the reflection resulting from the roughness of a surface through the height of surface impurities where the specular highlight is made sharper with small values for the roughness, such as 0.1.

                  + +

                  Applies to ""glass"", ""metal"", ""mirror"" and ""plastic"" reflection models. Larger values, close to 1.0 decrease the specular fall-off.

                  + +

                  IfcSpecularRoughness is of type REAL. It is constraint to values between (and including) 0 and 1.

                  + +
                  +NOTE: The datatype relates to the definition of ""shiness"" in VRML97, which is the reciprocate value to the specular roughness. +
                  + +
                  +HISTORY: New type in Release IFC2x2. +
                  + +
                  " +4973;IfcBoxAlignment;" + +

                  The box alignment specifies the alignment of the text box relative to its position. The following string values shall be used:

                  +
                    +
                  • top-left
                  • +
                  • top-middle
                  • +
                  • top-right
                  • +
                  • middle-left
                  • +
                  • center
                  • +
                  • middle-right
                  • +
                  • bottom-left
                  • +
                  • bottom-middle
                  • +
                  • bottom-right
                  • +
                  + +
                  +NOTE  The top-left is the default value. +
                  + +

                  Figure 298 illustrates alignment values.

                  + + + + +

                  Figure 298 — Box alignment values

                  + +

                  Figure 299 illustrates use of alignment values together with the placement and planar extent.

                  + + + +

                  Figure 299 — Box alignment examples

                  + +
                  +HISTORY  New type in IFC2x2 Addendum2. +
                  + +
                  +IFC2x3 CHANGE  The IfcBoxAlignment has been added. +
                  + +
                  " +5293;IfcGloballyUniqueId;" + +

                  An IfcGloballyUniqueId holds an encoded string identifier that is used to uniquely identify an IFC object. An IfcGloballyUniqueId is a Globally Unique Identifier (GUID) which is an auto-generated 128-bit number. Since this identifier is required for all IFC object instances, it is desirable to compress it to reduce overhead. The encoding of the base 64 character set is shown below: +

                  +
                  +

                             1         2         3         4         5         6 +
                   0123456789012345678901234567890123456789012345678901234567890123
                  + ""0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz_$""; +

                  +
                  + +

                  The resulting string is a fixed 22 character length string to be exchanged within the IFC exchange file structure.

                  + +

                  Refer to the BuildingSMART website (www.buildingsmart-tech.org) for more information and sample encoding algorithms.

                  + +
                  +HISTORY  New type in IFC R1.5.1. +
                  + +
                  " +5463;IfcDimensionCount;" + +

                  Definition from ISO/CD 10303-42:1992: A dimension count is a positive integer used to define the coordinate space dimensionality.

                  + +

                  The IfcDimensionCount is restricted to have the dimensionality of either 1, 2, or 3 - the WR1 had been added as an addition to the ISO 10303:42 entity dimension_count. In contrary to the ISO 10303:42 constraint, that all geometric representation items within a geometric representation context are forced to have the same dimension count, the IFC geometry allows mixed dimensions, particularly when defining the boundary of planar surfaces.

                  + +
                  +NOTE Corresponding ISO 10303 type: dimension_count, please refer to ISO/IS 10303-42:1994, p. 14 for the final definition of the formal standard. +
                  + +
                  +HISTORY New Type in IFC Release 1.5 +
                  + +
                  " diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntity.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntity.csv new file mode 100644 index 0000000000000000000000000000000000000000..7d26d1b8feda2f264c98590841a5931f100924dd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntity.csv @@ -0,0 +1,38069 @@ +31;IfcOrganization;" +

                  A named and structured grouping with a corporate identity.

                  + +
                  +NOTE: The relationships between IfcOrganizations, like a Department within a Company, can be expressed using IfcOrganizationRelationship. +
                  + +
                  +NOTE Corresponds to the following entity in ISO-10303-41: organization. +
                  + +
                  +HISTORY New entity in IFC Release 1.5.1.
                  +IFC 2x4 change: attribute Id renamed to Identification. +
                  + +
                  " +40;IfcActorRole;" + +

                  Definition: A role which is performed by an actor, either a person, an organization or a +person related to an organization.

                  + +
                  +NOTE: The list of roles of the enumeration values of the Role attribute can never +be complete. Therefore using enumeration value USERDEFINED, the user can provide his/her own role as a value +of the attribute UserDefinedRole. +
                  + +
                  + Corresponds to the following entity in ISO-10303-41: organization_role and person_role. +
                  + +
                  +HISTORY New entity in IFC Release 1.5.1 +
                  + +
                  " +70;IfcAddress;" + +

                  Definition: An abstract entity type for various kinds of postal and telecom addresses.

                  + +
                  +NOTE Corresponds to the following entity in ISO-10303-41: address. +
                  + +
                  +HISTORY New entity in IFC Release 1.5.1. +
                  + +
                  " +79;IfcPostalAddress;" +

                  Definition: The address for delivery of paper based mail.

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  + +
                  " +88;IfcTelecomAddress;" +

                  Definition: Address to which telephone, electronic mail and other forms of telecommunications should be addressed.

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  +IFC 2x4 change: Added attribute MessagingIDs. +Type of attribute WWWHomePageURL compatibly changed from IfcLabel to IfcURIReference. +
                  + +
                  " +102;IfcPerson;" +

                  Definition: an individual human being.

                  + +
                  +NOTE Many countries have legislation concerning the identification of individual persons within databases. Although the intent of the IFC Model is to act as a specification for data exchange +and sharing, an IFC file might in some situations be considered to be a database that enables identification of a particular person under the terms of such legislation. Users should be aware of the constraints of legislation that might apply in the places where IFC files are used. +
                  + +
                  +NOTE Corresponds to the following entity in ISO-10303-41: person. +
                  + +
                  +HISTORY New entity in IFC Release 1.5.1.
                  +IFC 2x4 change: attribute Id renamed to Identification. WHERE rule relaxed to allow omission of names if Identification is provided. +
                  + +
                  " +113;IfcPersonAndOrganization;" + +

                  Definition: Identification of a person within an organization.

                  + +
                  +NOTE Corresponds to the following entity in ISO-10303-41: person_and_organization. +
                  + +
                  +HISTORY New entity in IFC Release 1.5.1 +
                  + +
                  " +117;IfcOrganizationRelationship;" +

                  Definition: establishes an association between one relating organization and one or more related organizations.

                  + +
                  +NOTE Corresponds to the following entity in ISO-10303-41: organization_relationship. +
                  + +
                  +HISTORY New entity in IFC Release 2x.
                  +IFC 2x4 change: attribute Name made optional. +
                  + +
                  " +123;IfcApproval;" + +

                  Definition: An IfcApproval represents information about approval processes such as for a plan, a design, a proposal, or a change order in a construction or facilities management project. IfcApproval is referenced by IfcRelAssociatesApproval in IfcControlExtension schema, and thereby can be related to all subtypes of IfcRoot. An approval may also be given to resource objects using IfcResourceApprovalRelationship +

                  + +
                  +HISTORY New Entity in IFC Release 2.0 +
                  + +
                  +IFC2x Edition 4 CHANGE  Attributes Identifier and Name made optional, where rule added to require at least one of them being asserted. Inverse attributes ApprovedObjects, ApprovedResources and HasExternalReferences added. Inverse attribute Properties deleted (more general relationship via inverse ApprovedResources to be used instead). +
                  + +
                  " +139;IfcApprovalRelationship;" + +

                  An IfcApprovalRelationship associates approvals (one +relating approval and one or more related approvals), each having different status or level as the approval process or the approved +objects evolve.

                  + +
                  +HISTORY: New entity in Release IFC2x2.
                  +
                  + +
                  +IFC2x4 CHANGE  Subtyped from IfcResourceLevelRelationship, order of attributes changed. +
                  + +
                  " +142;IfcResourceApprovalRelationship;" +

                  An IfcResourceApprovalRelationship is used for +associating an approval to resource objects. A single approval +might be given to one or many items via IfcResourceObjectSelect.

                  + +
                  +HISTORY  New +Entity in IFC Release 2x4 +
                  + +
                  " +146;IfcPerformanceHistory;" + +

                  IfcPerformanceHistory is used to document the actual performance of an occurrence instance over time. In practice, performance-related data are generally not easy to obtain as they can originate from different sources (predicted, simulated, or measured) and occur during different stages of the building life-cycle. Such time-related data cover a large spectrum, including meteorological data, schedules, operational status measurements, trend reports, etc.

                  + +

                  IfcPerformanceHistory is assigned to other objects (represented by subtypes of IfcObjectDefinition, excluding subtypes of IfcControl), by the objectified relationship IfcRelAssignsToControl. +

                  + +
                  +HISTORY: New entity in Release IFC2x Edition 2. +
                  + +
                  " +152;IfcRelAssociatesApproval;" + +

                  The entity IfcRelAssociatesApproval is used to apply approval information defined by IfcApproval, in IfcApprovalResource schema, to subtypes of IfcRoot. +

                  + +
                  +HISTORY: New entity in IFC2x2. +
                  + +
                  " +154;IfcRelAssociatesConstraint;" + +

                  The entity IfcRelAssociatesConstraint is used to apply constraint information defined by IfcConstraint, in the IfcConstraintResource schema, to subtypes of IfcRoot. +

                  + +
                  +HISTORY: New entity in IFC2x2. +
                  + +
                  " +157;IfcRelAssociatesTimeSeries;" + +

                  IfcRelAssociatesTimeSeries associates to objects (subtypes of IfcRoot) a time-series that is applicable to one or more calendar dates.

                  + +
                  +HISTORY: New entity in Release IFC2x Edition 2. +
                  + +
                  +IFC2x Edition 4 CHANGE entity renamed to IfcRelAssociatesTimeSeries and made an objectified realtionship (subtype of IfcRelAssociates), replacing the old entity IfcTimeSeriesSchedule (was subtype of IfcControl +
                  + +
                  " +162;IfcPileType;" + +

                  Definition from IAI: Provides shared material, decomposition, representation maps, and property sets for instances of IfcPile.

                  + +
                  HISTORY New entity in IFC Release 2x4
                  + +

                  Material Use Definition:

                  + +

                  Material profile set association analogous to IfcColumnStandardCase should be used when applicable.

                  + +
                  " +174;IfcFootingType;" + +

                  Definition from IAI: Provides shared material, decomposition, representation maps, and property sets for instances of IfcFooting.

                  + +
                  HISTORY New entity in IFC Release 2x4
                  + +

                  Note, slab foundation types are not instantiated as IfcFootingType but as IfcSlabType with a predefined type of IfcSlabTypeEnum.BASESLAB.

                  + +

                  Material Use Definition:

                  + +

                  Material profile set or material layer set association analogous to IfcBeamStandardCase or IfcSlabStandardCase should be used when applicable.

                  + +
                  " +185;IfcSurfaceFeature;" + +

                  Definition from IAI: A surface feature is a modification at (onto, or into) of the surface of an element. Parts of the surface of the entire surface may be affected. The volume and mass of the element may be increased, remain unchanged, or be decreased by the surface feature, depending on manufacturing technology.

                  + +

                  The standard use of instances of IfcSurfaceFeature is as a part of element type objects (instances of subtypes of IfcElementType). The part–whole relationship is established by an aggregation relationship object, expressing the decomposition of an element type into one or more additive elements (element parts) and zero or more feature elements.

                  + +
                  HISTORY New type in IFC 2x4.
                  + +

                  Containment Use Definition:

                  + +

                  Surface features shall have no spatial containment relationship to the spatial structure since they are dependent on element types without spatial containment relationships or on an element occurrence with own spatial containment relationship.

                  +
                    +
                  • The SELF\IfcElement.ContainedInStructure relationship shall be NIL.
                  • +
                  + +

                  Geometry use definition:

                  + +

                  The geometric representation of IfcSurfaceFeatureElement is given by the IfcProductDefinitionShape, allowing multiple geometric representation.

                  + +

                  Local Placement

                  + +

                  The local placement for IfcSurfaceFeatureElement is defined in its supertype IfcProduct. It is defined by the IfcLocalPlacement, which defines the local coordinate system that is referenced by all geometric representations.

                  +
                    +
                  • In case of features which are part of an element type, absolute placement into the type object's implied coordinate system shall be used.
                  • +
                  • In case of features which are voiding an element occurrence, the PlacementRelTo relationship of IfcLocalPlacement shall point to the local placement of the respective element.
                  • +
                  + +

                  Shape representation

                  + +

                  Different shape representations may be used, depending on the nature of the feature and information requirements:

                  +
                    +
                  • Symbolic representation, such as the two-dimensional bounding box of a tag.

                    +
                  • A geometric set representing the geometric items of a mark.
                  • +
                  • Surface representations of treated parts of the lement surface by means of IfcShellBasedSurfaceModel. The faces within the surface model may be included into a B-Rep model within a representation map of the parent element type.
                  • +
                  + +

                  Higher-level parameters (geometric and non-geometric) may be provided by property sets based on local agreements.

                  + +
                  " +194;IfcVoidingFeature;" + +

                  Definition from IAI: A voiding feature is a modification of an element which reduces its volume. Such a feature may be manufactured in different ways, for example by cutting, drilling, or milling of members made of various materials, or by inlays into the formwork of cast members made of materials such as concrete.

                  + +

                  The standard use of instances of IfcVoidingFeature is as a part of element type objects (instances of subtypes of IfcElementType). The part–whole relationship is established by an aggregation relationship object, expressing the decomposition of an element type into one or more additive elements (element parts) and zero or more feature elements.

                  + +
                  HISTORY New type in IFC 2x4.
                  + +

                  Containment Use Definition:

                  + +

                  Voiding features shall have no spatial containment relationship to the spatial structure since they are dependent on element types without spatial containment relationships or on an element occurrence with own spatial containment relationship.

                  +
                    +
                  • The SELF\IfcElement.ContainedInStructure relationship shall be NIL.
                  • +
                  + +

                  Geometry use definition:

                  + +

                  The geometric representation of IfcVoidingFeatureElement is given by the IfcProductDefinitionShape, allowing multiple geometric representation.

                  + +

                  Local Placement

                  + +

                  The local placement for IfcVoidingFeatureElement is defined in its supertype IfcProduct. It is defined by the IfcLocalPlacement, which defines the local coordinate system that is referenced by all geometric representations.

                  +
                    +
                  • In case of features which are part of an element type, absolute placement into the type object's implied coordinate system shall be used.
                  • +
                  • In case of features which are voiding an element occurrence, the PlacementRelTo relationship of IfcLocalPlacement shall point to the local placement of the respective element.
                  • +
                  + +

                  Shape representation

                  + +

                  Different shape representations may be used, depending on the nature of the feature and information requirements:

                  +
                    +
                  • Symbolic representations, such as an axis representation, may be used for simple shapes such as holes or edge features.

                    +
                  • Volumetric representations by means of subtypes of IfcSweptSurface or of IfcCsgPrimitive3D may be used to semi-parametrically model the actual volume of the void created by the feature. The objects within the shape model of the feature's shape representation can be included into a CSG model within a representation map of the parent element type.
                  • +
                  • Surface representations of cutting planes by means of IfcShellBasedSurfaceModel. The faces within the surface model may be included into a B-Rep model within a representation map of the parent element type.
                  • +
                  + +

                  Higher-level parameters (geometric and non-geometric) may be provided by property sets based on local agreements.

                  + +
                  " +206;IfcFooting;" + +

                  A footing is a part of the foundation of a structure that spreads and transmits the load to the soil, either directly or via piles.

                  + +
                  +HISTORY New entity in IFC2x2 +
                  + +

                  Note, slab foundations are not instantiated as IfcFooting but as IfcSlab or IfcSlabStandardCase with a predefined type of IfcSlabTypeEnum.BASESLAB.

                  + +

                  Property Set Use Definition

                  + +

                  The following property set definitions are part of this IFC release:

                  + + + +

                  Quantity Use Definition

                  +

                  The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. The following base quantities are defined and should be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. Other quantities, being subjected to local standard of measurement, can be defined with another string value assigned to Name. In this case a valid value for MethodOfMeasurement has to be provided.

                  + + +

                  Geometry Use Definition

                  + +

                  Local placement and product representations are defined by the supertype IfcBuildingElement. Standard representations as defined at IfcBeamStandardCase or IfcSlabStandardCase should be used when applicable.

                  + +
                  " +210;IfcPile;" + +

                  A pile is a slender timber, concrete, or steel structural element, driven, jetted, or otherwise embedded on end in the ground for the purpose of supporting a load.

                  + +
                  +HISTORY New entity in IFC2x2 +
                  + +

                  Property Set Use Definition

                  + +

                  The following property set definitions are part of this IFC release:

                  + + + +

                  Quantity Use Definition

                  +

                  The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. The following base quantities are defined and should be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. Other quantities, being subjected to local standard of measurement, can be defined with another string value assigned to Name. In this case a valid value for MethodOfMeasurement has to be provided.

                  + + +

                  Geometry Use Definition

                  + +

                  Local placement and product representations are defined by the supertype IfcBuildingElement. Standard representations as defined at IfcColumnStandardCase should be used when applicable.

                  + +
                  " +222;IfcReinforcingElementType;" + +

                  Definition from IAI: Types of bars, wires, strands, meshes, tendons, and other components embedded in concrete in such a manner that the reinforcement and the concrete act together in resisting forces.

                  + +
                  HISTORY New entity in IFC Release 2x4
                  + +
                  " +230;IfcReinforcingElement;" + +

                  Definition from IAI: Bars, wires, strands, meshes, tendons, and other components embedded in concrete in such a manner that the reinforcement and the concrete act together in resisting forces.

                  + +
                  HISTORY New entity in IFC Release 2x2
                  + +
                  IFC 2x4 CHANGE Entity made non-abstract.
                  +Subtypes IfcTendon and IfcTendonAnchor removed.
                  +Attribute SteelGrade removed.
                  +Attributes PredefinedType and Role added.
                  + +
                  " +237;IfcReinforcingBar;" + +

                  Definition from IAI: A steel bar, usually with manufactured deformations in the surface, +used in concrete and masonry construction to provide additional strength. A single instance +of this class may represent one or many of actual rebars, for example a row of rebars.

                  + +
                  HISTORY New entity in IFC Release 2x2
                  + +
                  IFC 2x4 CHANGE All attributes removed; information now provided by IfcReinforcingBarType.
                  + +

                  Geometry Use Definition

                  + +

                  The geometric representation of IfcReinforcingBar is given by the IfcProductDefinitionShape, +allowing multiple geometric representations. Included are:

                  + +

                  Local Placement
                  +The use of local placement is defined at the supertype IfcElementComponent.

                  + +

                  Multiple Mapped Representation
                  +See supertype IfcElementComponent. This method of representation allows for several rebars +represented by a single instance of IfcReinforcingBar. The representation map should contain +one IfcSweptDiskSolidPolygonal.

                  + +

                  An IfcElementQuantity, +attached via IfcRelDefinesByProperties, should contain an IfcQuantityCount named 'Count' +with the number rebars and, if this is a regularly spaced arrangement of rebars, an +IfcQuantityLength named 'Spacing' which expresses the center-to-center distances of bars.

                  + +

                  Simplified Geometric Representation
                  +Simplified geometric representations may be used based on local agreements.

                  + + +
                  " +249;IfcReinforcingMesh;" + +

                  Definition from IAI: A series of longitudinal and transverse wires or bars of various gauges, arranged at right angles to each other and welded at all points of intersection; usually used for concrete slab reinforcement. Also known as welded wire fabric.

                  + +
                  HISTORY New entity in IFC Release 2x2
                  + +
                  IFC 2x4 CHANGE All attributes removed; information now provided by IfcReinforcingMeshType.
                  + +

                  Geometry Use Definition

                  + +

                  The geometric representation of IfcReinforcingBar is given by the IfcProductDefinitionShape, +allowing multiple geometric representations. Included are:

                  + +

                  Local Placement
                  +The use of local placement is defined at the supertype IfcElementComponent.

                  + +

                  Multiple Mapped Representation
                  +See supertype IfcElementComponent. This method of representation allows for several meshes +represented by a single instance of IfcReinforcingMesh.

                  + +

                  An IfcElementQuantity, +attached via IfcRelDefinesByProperties, should contain an IfcQuantityCount named 'Count' +with the number of meshes represented by this instance.

                  + +

                  Simplified Geometric Representation
                  +Simplified geometric representations may be used based on local agreements.

                  + + +
                  " +252;IfcReinforcingBarType;" + +

                  Definition from IAI: A steel bar, usually with manufactured deformations in the surface, +used in concrete and masonry construction to provide additional strength.

                  + +
                  HISTORY New entity in IFC Release 2x4
                  + +

                  Material Use Definition:

                  + +

                  An associated material denotes the steel grade, preferrably by material classification.

                  + +

                  Geometry Use Definition:

                  + +

                  The IfcReinforcingBarType may define the shared geometric representation for all rebar occurrences. The RepresentationMaps attribute refers to a list of IfcRepresentationMap's, that allow for multiple geometric representations (e.g. with IfcShapeRepresentation's having an RepresentationIdentifier 'Box', 'Axis', or 'Body').

                  + +

                  A 'Body' representation map should contain one IfcSweptDiskSolidPolygonal.

                  + +

                  Simplified geometric representations may be used based on local agreements.

                  + + +
                  " +258;IfcReinforcingMeshType;" + +

                  Definition from IAI: A series of longitudinal and transverse wires or bars of various gauges, arranged at right angles to each other and welded at all points of intersection; usually used for concrete slab reinforcement. Also known as welded wire fabric.

                  + +
                  HISTORY New entity in IFC Release 2x4
                  + +

                  Material Use Definition:

                  + +

                  An associated material denotes the steel grade, preferrably via material classification.

                  + +

                  Geometry Use Definition:

                  + +

                  The IfcReinforcingMeshType may define the shared geometric representation for all mesh occurrences. The RepresentationMaps attribute refers to a list of IfcRepresentationMap's, that allow for multiple geometric representations.

                  + + +
                  " +271;IfcReinforcementDefinitionProperties;" +

                  Definition from IAI: An + IfcReinforcementDefinitionProperties defines the cross section + properties of reinforcement included in reinforced concrete building elements. + The property set definition may be used both in conjunction with insitu and + precast structures.

                  + +
                  HISTORY New entity in IFC Release 2x2
                  +IFC 2x4 change: Supertype changed from IfcPropertySetDefinition to IfcPreDefinedPropertySet
                  + +

                  General usage:

                  +

                  This subtype of IfcPropertySetDefinition is used to define the + reinforcement properties in early design stages, such as in requirement + definition or scheme design. In later design stages explicit instances of + subtypes of IfcReinforcingElement are used. The intended usage may be + indicated using the DefinitionType attribute value as a designator: + recommended values are 'Reinforcement area requirement' or 'Reinforcement + configuration requirement'. Other values may be used according to local + standards.

                  +

                  Only one property set definition of this kind is used for each concrete + building element in each intended usage indicated by the DefinitionType + attribute value. This set then defines a list of cross section properties in a + discrete number of longitudinal sections as instances of + IfcSectionReinforcementProperties (one for each structural reinforcement + bar role), which in turn have a section cross section property defined as a + profile and a number of reinforcement properties, one for each steel grade / + bar type.

                  +
                  " +279;IfcPreDefinedTextFont;" + +

                  The pre defined text font determines those qualified names which can be used for fonts that are in scope of the current data exchange specification (in contrary to externally defined text fonts). There are two choices:

                  +
                    +
                  • IfcDraughtingPreDefinedTextFont for definitions from ISO/IS 10303-46:1994 for (old) vector based and monospace text.
                    +
                  • +
                  • IfcTextStyleFontModel for definitions from Cascading Style Sheets, level 1, W3C Recommendation 17 Dec 1996, revised 11 Jan 1999, CSS1, for all true type text. The use of the CSS1 definitions is the preferred way to represent text fonts.
                  • +
                  + +
                  +NOTE  Corresponding ISO 10303 name: pre_defined_text_font. Please refer to ISO/IS 10303-46:1994, p. 138 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  +IFC2x3 CHANGE  The IfcTextStyleFontModel has been added as new subtype. +
                  + +
                  " +282;IfcPreDefinedItem;" + +

                  A pre defined item is a qualified name given to a style or font which is determined within the data exchange specification by convention on using the Name attribute value (in contrary to externally defined items, which are agreed by an external source).

                  + +
                  +NOTE  The convention on using the Name value is defined at the subtypes of IfcPreDefinedItem and is part of the specification. +
                  + +
                  +NOTE  Corresponding ISO 10303 name: pre_defined_item. Please refer to ISO/IS 10303-41:1994, page 137 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +286;IfcPreDefinedColour;" + +

                  The pre defined colour determines those qualified names which can be used to identify a colour that is in scope of the current data exchange specification (in contrary to colour specification which defines the colour directly by its colour components).

                  + +
                  +NOTE  Corresponding ISO 10303 name: pre_defined_colour. It has been made into an abstract entity in IFC. Please refer to ISO/IS 10303-46:1994, p. 141 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +288;IfcDraughtingPreDefinedColour;" + +

                  The draughting pre defined colour is a pre defined colour for the purpose to identify a colour by name. Allowable names are:

                  +
                    +
                  • 'black',
                  • +
                  • 'red',
                  • +
                  • 'green',
                  • +
                  • 'blue',
                  • +
                  • 'yellow',
                  • +
                  • 'magenta',
                  • +
                  • 'cyan',
                  • +
                  • 'white',
                  • +
                  • 'by layer'
                  • +
                  + +
                  +NOTE ÿThe IfcDraughtingPreDefinedColour is an entity that had been adopted from ISO 10303-202, Industrial automation systems and integration—Product data representation and exchange, Part 202: Application protocol: Associative draughting. +
                  + +

                  The following table states the RGB values associated with the names given by the IfcDraughtingPreDefinedColour.

                  +
                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  Colour nameRedGreenBlue
                  black000
                  red1.000
                  green01.00
                  blue001.0
                  yellow1.01.00
                  magenta1.001.0
                  cyan01.01.0
                  white1.01.01.0
                  by layercolour values obtained from
                  +IfcPresentationLayerWithStyle.
                  +
                  + +
                  +NOTE ÿCorresponding ISO 10303 name: draughting_pre_defined_colour. Please refer to ISO/IS 10303-202:1994 page 194 for the final definition of the formal standard. +
                  + +
                  +HISTORY ÿNew entity in IFC2x2. +
                  + +

                  Informal proposition

                  +
                    +
                  1. The value 'by layer' shall only be inserted, if the geometric representation item using the colour definition has an association to IfcPresentationLayerWithStyle, and if that instance of IfcPresentationLayerWithStyle has a valid colour definition for IfcCurveStyle, IfcSymbolStyle, or IfcSurfaceStyle (depending on what is applicable).
                  2. +
                  + +
                  " +290;IfcDraughtingPreDefinedTextFont;" + +

                  The draughting pre defined text font is a pre defined text font for the purpose to identify a font by name. Allowable names are:

                  +
                    +
                  • 'ISO 3098-1 font A',
                  • +
                  • 'ISO 3098-1 font B',
                  • +
                  +

                  The ISO 3098-1 font A is the text font as denoted as Letterng A in clause 3 of ISO 3098-1, the ISO 3098-1 font B is the text font as denoted as Letterng B in clause 3 of ISO 3098-1.

                  + +
                  +NOTE  The IfcDraughtingPreDefinedTextFont is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 202: Application protocol: Associative draughting. Corresponding ISO 10303 name: draughting_pre_defined_text_font. Please refer to ISO/IS 10303-202:1994 page 196 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +292;IfcTextStyleFontModel;" + +

                  Definition from CSS1 (W3C Recommendation): Setting font properties will be among the most common uses of style sheets. Unfortunately, there exists no well-defined and universally accepted taxonomy for classifying fonts, and terms that apply to one font family may not be appropriate for others. For example, 'italic' is commonly used to label slanted text, but slanted text may also be labeled as being Oblique, Slanted, Incline, Cursive or Kursiv. Therefore it is not a simple problem to map typical font selection properties to a specific font.

                  + +

                  Font matching

                  +

                  Because there is no accepted, universal taxonomy of font properties, matching of properties to font faces must be done carefully. The properties are matched in a well-defined order to ensure that the results of this matching process are as consistent as possible across user agents (assuming that the same library of font faces is presented to each of them). +

                  + +
                    +
                  1. The user agent makes (or +accesses) a database of relevant CSS1 +properties of all the fonts of which the UA is aware. The UA may be +aware of a font because it has been installed locally or it has been +previously downloaded over the web. If there are two fonts with +exactly the same properties, one of them is ignored.
                  2. +
                  3. At a given element and for +each character in that element, the UA +assembles the font-properties applicable to that element. Using the +complete set of properties, the UA uses the 'font-family' property to +choose a tentative font family. The remaining properties are tested +against the family according to the matching criteria described with +each property. If there are matches for all the remaining properties, +then that is the matching font face for the given element.
                  4. +
                  5. If there is no matching font +face within the 'font-family' being +processed by step 2, and if there is a next alternative 'font-family' +in the font set, then repeat step 2 with the next alternative +'font-family'.
                  6. +
                  7. If there is a matching font +face, but it doesn't contain a glyph +for the current character, and if there is a next alternative +'font-family' in the font sets, then repeat step 2 with the next +alternative 'font-family'. 
                  8. +
                  9. If there is no font within +the family selected in 2, then use a +UA-dependent default 'font-family' and repeat step 2, using the best +match that can be obtained within the default font.
                  10. +
                  +

                  (The above algorithm can be +optimized to avoid having to revisit +the CSS1 properties for each character.) +

                  +

                  The per-property matching rules +from (2) above are as follows: +

                  +
                    +
                  1. 'font-style' is tried first. +'italic' +will be satisfied if there is either a face in the UA's font database +labeled with the CSS keyword 'italic' (preferred) or 'oblique'. +Otherwise the values must be matched exactly or font-style will fail.
                  2. +
                  3. 'font-variant' is tried +next. 'normal' +matches a font not labeled as 'small-caps'; 'small-caps' matches (1) a +font labeled as 'small-caps', (2) a font in which the small caps are +synthesized, or (3) a font where all lowercase letters are replaced by +upper case letters. A small-caps font may be synthesized by +electronically scaling uppercase letters from a normal font.
                  4. +
                  5. 'font-weight' is matched next, it will never fail. (See 'font-weight' below.)
                  6. +
                  7. 'font-size' must be matched within a +UA-dependent margin of tolerance. (Typically, sizes for scalable fonts +are rounded to the nearest whole pixel, while the tolerance for +bitmapped fonts could be as large as 20%.) Further computations, are +based on the 'font-size' value that is used, not the one that is specified.
                  8. +
                  + +

                  The inherited Name attribute is used to define the font name, particularly in cases, where no (list of) font families are provided.

                  + +
                  +NOTE  Corresponding CSS1 definitions are Font properties ('font-family', 'font-style', 'font-variant',  'font-weight'). +
                  + +
                  +HISTORY  New entity in IFC2x3. +
                  + +
                  " +306;IfcExternallyDefinedTextFont;" + +

                  Definition from ISO/CD 10303-46:1992: The externally defined text font is an external reference to a text font

                  + +
                  +NOTE  Restrictions of the font source and font names to be used may be exposed by implementation guidelines. +
                  + +
                  +NOTE  Corresponding ISO 10303 name: externally_defined_text_font. Please refer to ISO/IS 10303-46:1994, p. 137 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +307;IfcColourSpecification;" + +

                  Definition from ISO/CD 10303-46:1992: The colour specification entity contains a direct colour definition. Colour component values refer directly to a specific colour space.

                  + +
                  +NOTE  Corresponding ISO 10303 name: colour_specification. It has been made into an abstract entity in IFC. Please refer to ISO/IS 10303-46:1994, p. 138 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +310;IfcColourRgb;" + +

                  Definition from ISO/CD 10303-46:1992: A colour rgb as a subtype of colour specifications is defined by three colour component values for red, green, and blue in the RGB colour model.

                  + +
                  +NOTE  In contrary to the usual value range of colour components being integer from 0...255, the definition from ISO10303-46 defines the colour components as real from 0.0 ... 1.0. Applications need to execute this conversion before populating the colour RGB values. +
                  + +
                  +NOTE  Corresponding STEP name: colour_rgb. The name attribute has been omitted, the data type for the reg, green and blue parts is IfcNormalizedRatioMeasure, that already includes the range restrictions for the values. Please +refer to ISO/IS 10303-46:1994, p. 138 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +314;IfcPlanarExtent;" + +

                  The planar extent defines the extent along the two axes of the two-dimensional coordinate system, independently of its position.

                  + +
                  +NOTE  Corresponding ISO 10303 name: planar_extent. Please refer to ISO/IS 10303-46:1994, p. 141 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +318;IfcPlanarBox;" + +

                  Definition from ISO/CD 10303-46:1992: A planar box specifies an arbitrary rectangular box and its location in a two dimensional Cartesian coordinate system.

                  + +
                  +NOTE  Corresponding ISO 10303 name: planar_box. Please refer to +ISO/IS 10303-46:1994, p. 141 for the final definition of the formal standard. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +324;IfcPropertyDependencyRelationship;" + +

                  An IfcPropertyDependencyRelationship describes an identified dependency between the value of one property and that of another.

                  + +
                  +HISTORY  New entity in IFC2x2 +
                  + +
                  +IFC2x4 CHANGE  Made subtype of IfcResourceLevelRelationship (attribute order changed). +
                  + +

                  Use Definition

                  +

                  Whilst the IfcPropertyDependencyRelationship may be used to describe the dependency, and it may do so in terms of the expression of how the dependency operates, it is not possible through the current IFC model for the value of the related property to be actually derived from the value of the relating property. The determination of value according to the dependency is required to be performed by an application that can then use the Expression attribute to flag the form of the dependency.

                  + +
                  " +329;IfcProperty;" + +

                  IfcProperty is an abstract generalization for all types of properties that can be associated with IFC objects through the property set mechanism.

                  + +
                  +HISTORY  New entity in IFC Release 1.0. +
                  + +
                  " +339;IfcComplexProperty;" + +

                  IfcComplexProperty is used to define complex properties to be handled completely within a property set. The included set of properties may be a mixed or consistent collection of IfcProperty subtypes. This enables the definition of a set of properties to be included as a single 'property' entry in an IfcPropertySet. The definition of such an IfcComplexProperty can be reused in many different IfcPropertySet's.

                  + +
                  +NOTE  Since an IfcComplexProperty may contain other complex properties, sets of properties can be nested. This nesting may be restricted by view definitions and implementer agreements. +
                  + +
                  +HISTORY New Entity in IFC Release 2.0, capabilities enhanced in IFC Release 2x. +
                  + +
                  " +344;IfcSimpleProperty;" + +

                  IfcSimpleProperty is a generalization of a single property object. The various subtypes of IfcSimpleProperty establish different ways in which a property value can be set.

                  + +
                  +HISTORY  New Entity in IFC Release 1.0, definition changed in IFC Release 2x. +
                  + +
                  " +351;IfcPropertySingleValue;" + +

                  The property with a single value +IfcPropertySingleValue defines a property object which has +a single (numeric or descriptive) value assigned. It defines a +property - single value combination for which the property +Name, an optional Description,ÿand an optional +NominalValue with measure type is provided. In addition, +the default unit as specified within the project unit context can +be overriden by assigning an Unit.

                  +

                  The unit is handled by the Unit attribute:

                  +
                    +
                  • If the Unit attribute is not given, then the unit is +already implied by the type of IfcMeasureValue or +IfcDerivedMeasureValue. The associated unit can be found +at the IfcUnitAssignment globally defined at the project +level (IfcProject.UnitsInContext).
                  • +
                  • If the Unit attribute is given, then the unit assigned +by the Unit attribute overrides the globally assigned +unit.
                  • +
                  +

                  Examples of a property with single value are:

                  + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  NameNominalValueType
                  (through IfcValue)
                  Unit
                  DescriptionManufacturer ""A"" doorIfcLabel-
                  PanelThickness0.12IfcPositiveLengthMeasure-
                  ThermalTransmittance2.6IfcThermalTransmittanceMeasureW/(m2K)
                  +
                  +HISTORY ÿNew entity in IFC Release 1.0. The entity has been renamed from IfcSimpleProperty in IFC Release 2x. +
                  +
                  +IFC2x3 CHANGE ÿAttribute NominalValue has been made OPTIONAL with upward compatibility for file based exchange. +
                  + +
                  " +354;IfcPropertyEnumeratedValue;" + +

                  A property with an enumerated +value, IfcPropertyEnumeratedValue, defines a property +object which has a value assigned that is chosen from an +enumeration. It defines a property - value combination for which +theÿproperty Name, an optional Description,ÿthe +optional EnumerationValues +with measure type and optionally an Unit is given.

                  + +
                  +NOTE  Multiple choices from the property enumeration are supported. +
                  + +

                  The unit is handled by the Unit attribute of the +IfcPropertyEnumeration:

                  +
                    +
                  • If the Unit attribute is not given, then the unit is +already implied by the type of IfcMeasureValue or +IfcDerivedMeasureValue. The associated unit can be found +at the IfcUnitAssignment globally defined at the project +level (IfcProject.UnitsInContext).
                  • +
                  • If the Unit attribute is given, then the unit assigned +by the unit attribute overrides the globally assigned unit.
                  • +
                  +

                  More precisely: The IfcPropertyEnumeratedValue defines +a property, which value is selected from a defined list of +enumerators. The enumerators are stored in a dynamic enumeration +of values including the type information from IfcValue +(see IfcPropertyEnumeration). This enables applications to +use an enumeration value as a property within a property set +(IfcPropertySet) including the allowed list of +values.ÿ

                  + +
                  +NOTE  An IfcPropertyEnumeratedValue may be exchanged with no values assigned yet. In this case the EnumerationValues are set to NIL. +
                  + +
                  +

                  Examples of a property with enumerated value are:

                  +
                  +
                  + + + + + + + + + + + + + + + + + + + + + +
                  NameÿValue
                  (EnumerationValue)
                  Type
                  (through +IfcValue)
                  ref.IfcPropertyEnumeration
                  +(Name)ÿ
                  BladeActionOpposedIfcStringDamperBladeActionEnum
                  BladeActionParallelIfcStringDamperBladeActionEnum
                  +

                  The IfcPropertyEnumeratedValue refers to an +IfcPropertyEnumeration, e.g. for the above:

                  +
                  +
                  + + + + + + + + + + + + + + + +
                  NameEnumerationValuesType
                  (through +IfcValue)
                  Unit
                  DamperBladeActionEnum(Parallel, Opposed, Other, Unset)IfcString-
                  +
                  +

                  It is not mandatory to use an instance of +IfcPropertyEnumeration to hold the applicable values for +IfcPropertyEnumeratedValue, however this is the preferred +way. A single instance of IfcPropertyEnumeration can be +referenced by multiple instances of +IfcPropertyEnumeratedValue.

                  + +
                  +HISTORY ÿNew Entity in IFC Release 2.0, capabilities enhanced in IFC2x. The entity has +been renamed from IfcEnumeratedProperty in IFC2x. +
                  + +
                  +IFC2x4 CHANGE Attribute EnumerationValues has been made OPTIONAL with upward +compatibility for file based exchange. +
                  + +
                  " +358;IfcPropertyEnumeration;" + +

                  IfcPropertyEnumeration is a collection of simple +or measure values that define a prescribed set of alternatives from +which 'enumeration values' are selected. This enables inclusion of +enumeration values in property sets. IfcPropertyEnumeration +provides a name for the enumeration as well as a list of unique +(numeric or descriptive) values (that may have a measure type +assigned). The entity defines the list of potential enumerators to be +exchanged together (or separately) with properties of type IfcPropertyEnumeratedValue +that selects their actual property values from this enumeration.

                  +

                  The unit is handled by the Unit attribute:

                  +
                    +
                  • If the Unit attribute is not given, +than the unit is already implied by the type of IfcMeasureValue +or IfcDerivedMeasureValue. The associated unit can +be found at the IfcUnitAssignment globally defined +at the project level (IfcProject.UnitsInContext).
                  • +
                  • If the Unit attribute is given, the +unit assigned by the unit attribute overrides the globally assigned +unit.
                  • +
                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  NameEnumerationValuesType (through IfcValue)Unit
                  PEnum_DamperBladeActionParallelIfcString-
                   OpposedIfcString 
                   OtherIfcString 
                   UnsetIfcString 
                  + +
                  +HISTORY  New Entity in IFC Release 2.0, capabilities enhanced in IFC Release 2x. Entity has been renamed from IfcEnumeration in IFC Release 2x. +
                  + +
                  " +365;IfcPropertyBoundedValue;" +

                  + A property with a bounded + value, IfcPropertyBoundedValue, defines a property + object which has a maximum of two (numeric or descriptive) + values assigned, the first value specifying the upper bound + and the second value specifying the lower bound. It defines + a property - value bound (min-max) combination for which + the property Name, an optional + Description,ÿthe optional UpperBoundValue + with measure type, the optional LowerBoundValue with + measure type, and the optional Unit is given. +

                  +

                  A set point value can be provided in addition to the upper and lower bound values for operational value setting. +

                  +

                  + The unit is handled by the Unit attribute: +

                  +
                    +
                  • If the Unit attribute is not given, then the + unit is already implied by the type of + IfcMeasureValue or IfcDerivedMeasureValue. + The associated unit can be found at the + IfcUnitAssignment globally defined at the project + level (IfcProject.UnitsInContext). +
                  • +
                  • If the Unit attribute is given, then the unit + assigned by the Unit attribute overrides the + globally assigned unit. +
                  • +
                  +

                  + The IfcPropertyBoundedValue allows for the + specification of an interval for the value component of the + property description. If either the + LowerBoundValue or the UpperBoundValue is not + given, then it indicates an open bound (either a minimum + value or a maximum value). The interval is by definition + inclusive, that is, the value given for the + LowerBoundValue or the UpperBoundValue is + included in the interval. +

                  +
                  + NOTE  An IfcPropertyBoundedValue may be + exchanged with no values assigned yet. In this case the + LowerBoundValue and the UpperBoundValue are + set to NIL. +
                  +
                  +

                  + Examples of a property with bounded value are: +

                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  + Name + + UpperBoundValue + + LowerBoundValue + + SetPointValue + + Type
                  (through + IfcValue, WR1 ensures same type for both + values) +
                  + Unit
                  +
                  + OverallHeight + + 1930 + + 2300 + + <nil> + + IfcPositiveLengthMeasure + + - +
                  + OverallWidth + + 0.9 + + 1.25 + + <nil> + + IfcPositiveLengthMeasure + + m +
                  + MaxHeight + + 20.0 + + <nil> + + <nil> + + IfcPositiveLengthMeasure + + - +
                  + MinWeight + + <nil> + + 20 + + <nil> + + IfcMassMeasure + + kg +
                  +
                  + +
                  +HISTORY ÿNew entity in IFC Release 2x. +
                  + +
                  +IFC2x2 CHANGE  The attribute type of the attribute UpperBoundValue and LowerBoundValue has been changed from mandatory to optional with upward compatibility for file based exchange. +
                  + +
                  +IFC2x4 CHANGE  The attribute SetPointValue has been added. +
                  + +

                  + Informal proposition: +

                  +
                    +
                  1. If the measure type for the upper and lover bound value + is a numeric measure, then the following shall be true: + UpperBoundValue > LowerBoundValue. +
                  2. +
                  + +
                  " +373;IfcPropertyTableValue;" +

                  + A property with a range value + (IfcPropertyTableValue) defines a property object + which has two lists of (numeric or descriptive) values + assigned, the values specifying a table with two columns. + The defining values provide the first column and establish + the scope for the defined values (the second column). + Interpolations are out of scope of the + IfcPropertyTableValue. An optional Expression + attribute may give the equation used for deriving the range + value, which is for information purposes only. +

                  +

                  + The IfcPropertyTableValue defines a defining/defined + property value combination for which the property name, the + table with defining and defined values with measure type + (and optional the units for defining and defined values) + are given. +

                  +

                  + The units are handled by the DefiningUnit and + DefinedUnit attributes: +

                  +
                    +
                  • If the DefiningUnit or DefinedUnit + attribute is not given, then the unit is already implied by + the type of IfcMeasureValue or + IfcDerivedMeasureValue. The associated unit can be + found at the IfcUnitAssignment globally defined at + the project level (IfcProject.UnitsInContext). +
                  • +
                  • If the DefiningUnit or DefinedUnit + attribute is given, then the unit assigned by the unit + attribute overrides the globally assigned unit. +
                  • +
                  +

                  + The IfcPropertyTableValue allows for the + specification of a table of defining/defined value pairs of + the property description. The optional + attribute CurveInterpolation allows to determine the + interval between two given values. +

                  +

                  + Examples of a property with range value are: +

                  + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  + Name + + DefiningValues + + DefiningValue Type
                  (through IfcValue) +
                  + DefinedValues + + DefinedValue Type
                  (through + IfcValue) +
                  + DefingUnit + + DefinedUnit +
                  + SoundTransmissionLoss + + 100 + + IfcFrequencyMeasure + + 20 + + IfcNumericMeasure + + - + + dB +
                  + ÿ + + 200 + + IfcFrequencyMeasure + + 42 + + IfcNumericMeasure + + ÿ + + ÿ +
                  + ÿ + + 400 + + IfcFrequencyMeasure + + 46 + + IfcNumericMeasure + + ÿ + + ÿ +
                  + ÿ + + 800 + + IfcFrequencyMeasure + + 56 + + IfcNumericMeasure + + ÿ + + ÿ +
                  + ÿ + + 1600 + + IfcFrequencyMeasure + + 60 + + IfcNumericMeasure + + ÿ + + ÿ +
                  + ÿ + + 3200 + + IfcFrequencyMeasure + + 65 + + IfcNumericMeasure + + ÿ + + ÿ +
                  + +
                  +HISTORY: New entity in IFC2x. +
                  + +
                  + +

                  + Informal propositions: +

                  +
                    +
                  1. The list of DefinedValues and the list of + DefiningValues are corresponding lists. +
                  2. +
                  + +" +388;IfcPropertyReferenceValue;" + +

                  IfcPropertyReferenceValue allows a property value to + be given by referencing other entities within the resource + definitions of IFC. Those other entities are regarded as + predefined complex properties and can be aggregated within + a property set (IfcPropertySet). The allowable + entities to be used as value references are given by the + IfcObjectReferenceSelect.

                  +
                  + HISTORY  New entity in IFC + Release 1.5. Entity has been renamed from + IfcObjectReference in IFC Release 2x. +
                  +
                  + IFC2x4 CHANGE  Attribute + PropertyReference has been made OPTIONAL with upward + compatibility for file based exchange. +
                  + +
                  " +400;IfcPropertyListValue;" +

                  + An IfcPropertyListValue + defines a property that has several (numeric or + descriptive) values assigned, these values are given by an + ordered list.ÿIt defines a property - list value + combination for which the property Name, an optional + Description,ÿthe optional ListValues with measure + type and optionally an Unit is given. +

                  +

                  + An IfcPropertyListValue is a list of values. The + order in which values appear is significant. Each value in + the list is unique i.e. no duplicate values are allowed. + All list members shall be of the same type. +

                  +

                  + The unit applicable to all values is handled by the + Unit attribute: +

                  +
                    +
                  • If the Unit attribute is not given, then the + unit is already implied by the type of + IfcMeasureValue or IfcDerivedMeasureValue. + The associated unit can be found at the + IfcUnitAssignment globally defined at the project + level (IfcProject.UnitsInContext). +
                  • +
                  • If the Unit attribute is given, then the unit + assigned by the Unit attribute overrides the + globally assigned unit. +
                  • +
                  +

                  + Example of a property with list value is: +

                  + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  + Name + + ListValues + + Type
                  (through + IfcValue) +
                  + Unit
                  +
                  + ApplicableSizes + + 1200 + + IfcPositiveLengthMeasure + + - +
                  + - + + 1600 + + IfcPositiveLengthMeasure + + - +
                  + - + + 2400 + + IfcPositiveLengthMeasure + + - +
                  + +
                  +HISTORY  New Entity in Release IFC 2x Edition 2. +
                  + +
                  +IFC2x4 CHANGE  Attribute ListValues has been made OPTIONAL with upward compatibility for file based exchange. +
                  + +
                  " +406;IfcPhysicalQuantity;" + +

                  The physical quantity, IfcPhysicalQuantity, is an abstract entity that holds a complex or simple quantity measure together with a semantic definition of the usage for the single or several measure value.

                  + +

                  The Name attribute defines the actual usage or kind of measure. The interpretation of the name label has to be established within the actual exchange context. In addition an informative text may be associated to each quantity by the Description attribute.

                  + +
                  +HISTORY  New entity in IFC2x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +413;IfcPhysicalSimpleQuantity;" + +

                  The physical quantity, IfcPhysicalSimpleQuantity, is an entity that holds a single quantity measure value (as defined at the subtypes of IfcPhysicalSimpleQuantity) together with a semantic definition of the usage for the measure value.

                  + +
                  +EXAMPLE  An element, like a wall, may have several area measures, like footprint area, left wall face area, right wall face area. These areas would be given by three instances of the area quantity subtype, with different Name string values. +
                  + +

                  A section ""Quantity Use Definition"" at individual entities as subtypes of IfcBuildingElement gives guidance to the usage of the Name attribute to characterize the individual quantities. If the Unit attribute is given, the value attribute (introduced at the level of subtypes of IfcPhysicalSimpleQuantity) are given as quantities of this unit, otherwise the global unit definitions (given by IfcUnitAssignment) are used.

                  + +
                  +HISTORY New entity in IFC2x2 Addendum 1. +
                  + +
                  +IFC2x2 ADDENDUM 1 CHANGE  The abstract entity IfcPhysicalSimpleQuantity has been added. Upward compatibility for file based exchange is guaranteed. +
                  + +
                  " +421;IfcQuantityLength;" + +

                  IfcQuantityLength is a physical quantity that defines a derived length measure to provide an element's physical property. It is normally derived from the physical properties of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  A rafter within a roof construction may be measured according to its length (taking a common cross section into account). The actual size of the length depends on the method of measurement used. +
                  + +
                  +HISTORY  New entity in IFC Release 2.x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +426;IfcQuantityArea;" + +

                  IfcQuantityArea is a physical quantity that defines a derived area measure to provide an element's physical property. It is normally derived from the physical properties of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  An opening may have an opening area used to deduct it from the wall surface area. The actual size of the area depends on the method of measurement used. +
                  + +
                  +HISTORY  New entity in IFC2x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +431;IfcQuantityVolume;" + +

                  IfcQuantityVolume is a physical quantity that defines a derived volume measure to provide an element's physical property. It is normally derived from the physical properties of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  A thick brick wall may be measured according to its volume. The actual size of the volume depends on the method of measurement used. +
                  + +
                  +HISTORY New entity in IFC2x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +436;IfcQuantityCount;" + +

                  IfcQuantityCount is a physical quantity that defines a derived count measure to provide an element's physical property. It is normally derived from the physical properties of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  An radiator may be measured according to its number of coils. The actual counting method depends on the method of measurement used. +
                  + +
                  +HISTORY  New entity in IFC2x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +440;IfcQuantityWeight;" + +

                  IfcQuantityWeight is a physical element quantity that defines a derived weight measure to provide an element's physical property. It is normally derived from the physical properties of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  The amount of reinforcement used within a building element may be measured according to its weight. The actual size of the weight depends on the method of measurement used. +
                  + +
                  +HISTORY  New entity in IFC2x. It replaces the calcXxx attributes used in previous IFC Releases. +
                  + +
                  " +445;IfcQuantityTime;" + +

                  IfcQuantityTime is an element quantity that defines a time measure to provide an property of time related to an element. It is normally given by the recipe information of the element under the specific measure rules given by a method of measurement.

                  + +
                  +EXAMPLE  The amount of time needed to pour concrete for a wall is given as a time quantity for the labor part of the recipe information. +
                  + +
                  +HISTORY  New entity in IFC2x2. +
                  + +
                  " +450;IfcPhysicalComplexQuantity;" + +

                  The complex physical quantity, IfcPhysicalComplexQuantity, is an entity that holds a set of single quantity measure value (as defined at the subtypes of IfcPhysicalSimpleQuantity), that all apply to a given component or aspect of the element.

                  + +
                  +EXAMPLE: A layered element, like a wall, may have several material layers, each having individual quantities, like footprint area, side area and volume. An instance of IfcPhysicalComplexQuantity would group these individual quantities (given by a subtype of IfcPhysicalSimpleQuantity) and name them according to the material layer name by using the Name attribute. The Discrimination attribute would then be 'layer'. +
                  + +

                  A section ""Quantity Use Definition"" at individual entities as subtypes of IfcBuildingElement gives guidance to the usage of the Name and Discrimination attribute to characterize the complex quantities.

                  + +
                  +HISTORY  New entity in IFC2x2 Addendum 1. +
                  + +
                  +IFC2x2 ADDENDUM 1 CHANGE  The entity IfcPhysicalComplexQuantity has been added. Upward compatibility for file based exchange is guaranteed. +
                  + +
                  " +459;IfcSystem;" +

                  + Definition from IAI: Organized combination of + related parts within an AEC product, composed for a common + purpose or function or to provide a service. System is + essentially a functionally related aggregation of products. + The grouping relationship to one or several instances of + IfcProduct (the system members) is handled by + IfcRelAssignsToGroup. +

                  +
                  + NOTE: The use of IfcSystem often + applies to the representation of building services related + systems, such as the piping system, cold water system, etc. + Members within such a system may or may not be connected + using the connectivity related entities (e.g. through + IfcPort). +
                  +
                  +

                  + HISTORY: New entity in + IFC Release 1.0 +

                  +
                  +
                  " +464;IfcZone;" +

                  Definition from IAI: A zone isÿa group of spaces, +partial spaces or other zones. Zone structures may not be +hierarchical (in contrary to the spatial structure of a project - +see IfcSpatialStructureElement), i.e. one individual +IfcSpace may be associated with zero, one, or several +IfcZone's. IfcSpace's are grouped into an +IfcZone by using the objectified relationship +IfcRelAssignsToGroup as specified at the supertype +IfcGroup.

                  +
                  NOTE ÿCertain use cases may restrict the +freedom of non hierarchical relationships. In some building +service use cases the zone denotes aÿview based delimited volume +for the purpose of analysis and calculation. This type of zone +cannot overlap with respect to that analysis, but may overlap +otherwise.
                  +

                  An IfcZone is a spatial system under which individual +IfcSpace's (and other IfcZone's) are grouped. In +contrary to the IfcSpatialZone entity, IfcZone is a +mere grouping, it can not define an own geometric representation +and placement. Therefore it cannot be used for spatial zones +having a different shape and size compared to the shape and size +of aggregated spaces.

                  +
                  NOTEÿ The IfcZone is regarded as the +spatial system (as compared to the building service, electrical, +or analytical system), the name remains IfcZone for +compatibility reasons, instead of using a proper naming +convention, like IfcSpatialSystem.
                  +
                  NOTE ÿOne of the purposes of a zone is to +define a fire compartmentation. In this case it defines the +geometric information about the fire compartment (through the +contained spaces) and information, whether this compartment is +ventilated or sprinkler protected. In addition the fire risk code +and the hazard type can be added, the coding is normally defined +within a national fire regulation. All that information is +available within the relevant property sets. Again, if an +independent shape has to be provided to the fire compartment, +then the entity IfcSpatialZone shall be +used.
                  +
                  RECOMMENDATIONÿ In case of a zone denoting a +(fire) compartment, the following types should be used, if +applicable, as values of the ObjectType attribute: +
                    +
                  • FireCompartment - a zone of spaces, collected to +represent a single fire compartment.
                  • +
                  • ElevatorShaft - a collection of spaces within an +elevator, potentially going through many storeys.
                  • +
                  • RisingDuct
                  • +
                  • RunningDuct
                  • +
                  +
                  +

                  Additional classifications of the IfcZone, as provided +by a national classification system, can be assigned by using the +IfcRelAssociatesClassification relationship, accessible +via the inverse attribute HasAssociations. The +IfcZone can be assigned to a spatial structure element, it +refers to, e.g. to a particular IfcBuildingStorey by using +the IfcRelServicesBuildings relationship, accessible via +the inverse attribute ServicesBuilding.

                  +
                  HISTORYÿ New entity in +IFC Release 1.0
                  +IFC2x4 CHANGEÿ The entity is now +subtyped from IfcSystem (not its supertype +IfcGroup) with upward compatibility for file based +exchange.
                  +

                  Property Set Use Definition:

                  +

                  The property sets relating to the IfcZone are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcZone are part +of this IFC release:

                  + +
                  " +467;IfcRelConnectsElements;" +

                  + Definition from IAI: The + IfcRelConnectsElements objectified relationship + provides the generalization of the connectivity between + elements. It is a 1 to 1 relationship. The concept of two + elements being physically or logically connected is + described independently from the connecting elements. The + connectivity may be related to the shape representation of + the connected entities by providing a connection geometry. +

                  +
                    +
                  • In this case the geometrical constraints of the + connection are provided by the optional relationship to the + IfcConnectionGeometry. The connection geometry is + provided as a point, curve or surface within the local + placement coordinate systems of the connecting elements. +
                  • +
                  • If the connection geometry is omitted then the + connection is provided as a logical connection. Under this + circumstance, the connection point, curve or surface has to + be recalculated by the receiving application. +
                  • +
                  +
                  +

                  + HISTORY New entity in IFC + Release 1.0. +

                  +
                  +
                  " +474;IfcRelSpaceBoundary;" +

                  The space boundary defines the +physical or virtual delimiter of a space by the relationship +IfcRelSpaceBoundary to the surrounding elements.

                  +
                    +
                  • In the case of a physical space boundary, the placement and +shape of the boundary may be given, and the building element, +providing the boundary, is referenced,
                  • +
                  • In the case of a virtual space boundary, the placement and +shape of the boundary may be given, but no building element is +referenced and a virtual element is +referenced instead.
                  • +
                  +

                  The IfcRelSpaceBoundary is defined as an objectified +relationship that handles the element to space relationship by +objectifying the relationship between an element and the space it +bounds. It is given as a one-to-one relationship, but allows each +element (including virutal elements and openings) to define many +such relationship and each space to be defined by many such +relationships.

                  +

                  Space boundaries are always defined as seen from the space. In +general two basic types of space boundaries are +distinguished:

                  +
                    +
                  • 1st level space boundary: defined +as boundaries of the space, not taking into account any change in +building element or spaces on the other side.
                  • +
                  • 2nd level space boundary: defined +as boundary taking any change in building element or spaces on +the other side into account. It can be further distinguished into +
                      +
                    • 2nd level type A: There is a space +on the other side.
                    • +
                    • 2nd level type B: There is a +building element on the other side.
                    • +
                    +
                  • +
                  +
                  The exact definition of how space boundaries +are broken down depends on the view definition, more detailed +conventions on how space boundaries are decomposed can only be +given at the domain or application type level. +
                    +
                  • In an architectural or FM related view, a space +boundary is defined totally from inside the space. This is a +1st level space boundary.
                  • +
                  • In a thermal view, the decomposition of the space +boundary depends on the material of the providing building +element and the adjacent spaces behind. This is a +2nd level space boundary.
                  • +
                  +
                  + + + + + + + + + + + + + + + + + +
                  +""1st+""2nd

                  Figure 42 — Space boundary at first level

                  Figure 43 — Space boundary at second level

                  Figure 44 — Space boundary at second level type A

                  Figure 45 — Space boundary at second level type B

                  +
                  HISTORY New entity in IFC Release 1.5, the entity has been modified in IFC Release +2x.
                  +
                  IFC2x CHANGE The data type of the attributeRelatedBuildingElement has +been changed from IfcBuildingElement to its supertype IfcElement. The data type of the attribute +ConnectionGeometry has been changed from IfcConnectionSurfaceGeometry to its supertype +IfcConnectionGeometry.
                  +
                  +IFC2x4 CHANGE  Attributes DefiningValues and DefinedValues have been made OPTIONAL with upward compatibility for file based exchange. The attribute CurveInterpolation has been added.. +
                  IFC2x4 CHANGE The attribute RelatedBuildingElement has been made mandatory. For virtual boundaries the reference to IfcVirtualElement is now mandatory.
                  + +

                  Attribute Use Definitions

                  +

                  The differences between the 1st and +2nd level space boundaries is +identified by:

                  +
                    +
                  • 1st level:
                    +SELF\IfcRoot.Name = ""1stLevel""
                    +SELF\IfcRootDescription = NIL
                  • +
                  • 2nd level:
                    +SELF\IfcRoot.Name = ""2ndLevel""
                    +SELF\IfcRootDescription = ""2a"", or ""2b""
                  • +
                  +

                  Differentiation between physical and virtual space boundary is illustrated in Figure 46 and Figure 47.

                  + +

                  As shown in Figure 46, if the IfcRelSpaceBoundary is used to express a virtual boundary, the attribute PhysicalOrVirtualBoundary has to be set to VIRTUAL. The attribute RelatedBuildingElement shall point to an instance of IfcVirtualElement. If the correct location is of interest, the attribute ConnectionGeometry is required.

                  +
                  NOTE The connection geometry, either by a 2D curve or a 3D surface, is used to describe the portion of the ""virtual wall"" that separates the two spaces. All instances of IfcRelSpaceBoundary given at the adjacent spaces share the same instance of IfcVirtualElement. Each instance of IfcRelSpaceBoundary provides in addition the ConnectionGeometry given within the local placement of each space.
                  + + + + +

                  Figure 46 — Space boundary of virtual element

                  + +

                  As shown in Figure 47, if the IfcRelSpaceBoundary is used to express a physical boundary between two spaces, the attribute PhysicalOrVirtualBoundary has to be set to PHYSICAL. The attribute RelatedBuildingElement has to be given and points to the element providing the space boundary. The attribute ConnectionGeometry may be inserted, in this case it describes the physical space boundary geometically, or it may be omited, in that case it describes a physical space boundary logically.

                  + + + + +

                  Figure 47 — Space boundary of physical element

                  + +

                  Geometry Use Definitions

                  +

                  The IfcRelSpaceBoundary may have geometry attached. If +geometry is not attached, the relationship between space and +building element is handled only on a logical level. If geometry +is attached, it is given within the local coordinate systems of +the space.

                  +
                  NOTE: The attributes +CurveOnRelatingElement at +IfcConnectionCurveGeometry or +SurfaceOnRelatingElement at +IfcConnectionSurfaceGeometry provide the geometry within +the local coordinate system of the IfcSpace, whereas the +attributes CurveOnRelatedElement at +IfcConnectionCurveGeometry or +SurfaceOnRelatedElement at +IfcConnectionSurfaceGeometry provide the geometry within +the local coordinate system of the subtype of +IfcElement.
                  +NOTE In most view definitions the connection geometry for +the related IfcElement is not +provided.
                  +

                  The geometric representation (through the +ConnectionGeometry attribute) is defined using either 2D +curve geometry or 3D surface geometry for space boundaries. In +most view definitions the 3D connection surface geometry is +required.

                  +
                    +
                  • 1st level space boundary: +
                      +
                    • only connection geometry for related space shall be +provided
                    • +
                    • only surface connection geometry shall be provided
                    • +
                    • only the following surface representations are supported: +
                        +
                      • IfcSurfaceOfLinearExtrusion
                      • +
                      • IfcCurveBoundedPlane
                      • +
                      • IfcCurveBoundedSurface
                      • +
                      • IfcFaceBasedSurfaceModel
                      • +
                      +
                    • +
                    +
                  • +
                  • 2nd level space boundary: +
                      +
                    • only connection geometry for related space shall be +provided
                    • +
                    • only surface connection geometry shall be provided
                    • +
                    • only the following surface representations are supported: +
                        +
                      • IfcCurveBoundedPlane with restrictions to have +polygonal boundaries only
                      • +
                      • IfcFaceBasedSurfaceModel
                      • +
                      +
                    • +
                    +
                  • +
                  +

                  Surface connection geometry

                  +

                  The following constraints apply to the surface connection +geometry representation:

                  +
                    +
                  • planar boundaries: +
                      +
                    • IfcSurfaceOfLinearExtrusion defined by a +SweptCurve being an IfcArbitraryOpenProfileDef with +straight segements, or
                    • +
                    • IfcCurveBoundedPlane
                    • +
                    +
                  • +
                  • curved boundaries +
                      +
                    • IfcSurfaceOfLinearExtrusion defined by a +SweptCurve being an IfcArbitraryOpenProfileDef with +curves segements, or
                    • +
                    • IfcCurveBoundedSurface with a BasisSurface +being a non planar surface, such as IfcCylindricalSurface, +or
                    • +
                    • IfcFaceBasedSurfaceModel if already faceted.
                    • +
                    +
                  • +
                  +

                  Curve connection geometry

                  +

                  The following constraints apply to the 2D curve +representation:

                  +
                    +
                  • Curve: IfcPolyline, IfcTrimmedCurve or +IfcCompositeCurve
                  • +
                  +" +483;IfcRelSpaceBoundary1stLevel;" +

                  The 1st level space boundary +defines the physical or virtual delimiter of a space by the +relationship IfcRelSpaceBoundary1stLevel to the +surrounding elements. 1st level space boundaries are +characterizeda by:

                  +
                    +
                  • 1st level space boundaries are the boundaries of a space +defined by the surfaces of building elements bounding this space +(physical space boundaries) or by virtual surfaces provided by an +adjacent space with no dividing wall.
                  • +
                  • 1st level space boundaries do not consider any change of +material in the bounding building elements, or different +spaces/zones behind a wall or slab (floor or ceiling).
                  • +
                  • 1st level space boundaries are differentiated in two ways: +virtual or physical and internal,external, or undefined (internal +and external) e.g. for a wall that is partially inside and +outside.
                  • +
                  • 1st level space boundaries form a closed shell around the +space (so long as the space is completely enclosed) and include +overlapping boundaries representing openings (filled or not) in +the building elements (see implementers agreement below).
                  • +
                  +

                  1st level space boundaries define a space by its boundary +surfaces without taking anything on the other side of the +bounding elements into account.

                  +
                  NOTE 1st level space boundaries are used e.g. +in quantity take-off and facility management as they describe the +surfaces for finishes. They cannot be directly used for thermal +analysis. However 1st level space boundaries can provide the +input to preprocessors to thermal analysis software that take 1st +level space boundaries and perform the necessary transformation +into 2nd level space boundaries that are required for energy +analysis.
                  + +
                  HISTORY New entity in IFC2x4.
                  + +

                  Relationship Use Definitions

                  + +

                  As shown in Figure 48, the attribute ParentBoundary with inverse InnerBoundaries is provided to link the space boundaries of doors, windows, and openings to the parent boundary, such as of a wall or slab.

                  +
                  NOTE The space boundary of the parent is not cut by the inner boundary - both overlap.
                  + + + + +

                  Figure 48 — Space boundary first level relationships

                  + +

                  Geometry Use Definitions

                  +

                  See the definition at the supertype IfcRelSpaceBoundary for +guidance on using the connection geometry for first level space +boundaries.

                  + +
                  " +486;IfcRelSpaceBoundary2ndLevel;" +

                  The 2nd level space boundary defines the physical or virtual delimiter of a space by the relationship IfcRelSpaceBoundary2ndLevel to the surrounding elements. 2nd level space boundaries are characterized by:

                  +
                    +
                  • 2nd level space boundaries still represent building elements that bound the space, but are more granular in that they are subdivided in any of the following cases: +
                      +
                    • Differences in materials and/or material assemblies (for example, a wainscot or paneling on the lower portion of a wall).
                    • +
                    • Differences in spaces or zones on the other side of the building element (or virtual boundary) represented by the space boundary (for example, two different spaces on the other side of a wall)
                    • +
                    +
                  • +
                  • 2nd level space boundaries are differentiated in two ways: virtual or physical and internal or external, whereby any space boundary that is both internal and external has to be split into segments being either or.
                  • +
                  • 2nd level space boundaries represent both sides of a heat transfer surface separated by the thickness of the building element. They can be further differentiated in: +
                      +
                    • Type 2a that occurs when there is a space on the opposite side of the building element providing the space boundary
                    • +
                    • Type 2b occurs if there is a building element on the opposite side of the building element providing the space boundary.
                    • +
                    +
                  • +
                  • The connection geometry of 2nd level space boundaries is restricted to planar surfaces only. This means that curved surfaces must be segmented.
                  • +
                  +

                  2nd level space boundaries define the heat transfer surfaces on both sides of building elements that separate spaces. The generation of 2nd level space boundaries has to take building elements and spaces on the other side into account.

                  +
                  NOTE 2nd level space boundaries are used by many analysis packages that require a surface view of the building that can be transformed into the various simple topological models. Examples of such analysis packages include: (1) energy analysis, (2) lighting analysis, (3) fluid dynamics
                  + +
                  HISTORY New entity in IFC2x4.
                  + +

                  Relationship Use Definitions

                  +

                  As shown in Figure 49, the attribute ParentBoundary with inverse InnerBoundaries is provided to link the space boundaries of doors, windows, and openings to the parent boundary, such as of a wall or slab.

                  +
                  NOTE The space boundary of the parent is not cut by the inner boundary - both overlap.
                  +

                  The attribute CorrespondingBoundary with inverse Corresponds is provided to link the pair of space boundaries on the opposite sides of the building element.

                  +
                  NOTE Only 2nd level space boundaries of type A have corresponding boundaries.
                  + + + + +

                  Figure 49 — Space boundary second level relationships

                  + +

                  Geometry Use Definitions

                  +

                  See the definition at the supertype IfcRelSpaceBoundary +for guidance on using the connection geometry for second level +space boundaries.

                  + +" +494;IfcSpace;" +

                  A space represents an area or volume +bounded actually or theoretically. Spaces are areas or volumes that +provide for certain functions within a building.

                  +

                  A space is associated to a building storey (or in case of +exterior spaces to a site). A space may span over several connected +spaces. Therefore a space group provides for a collection of spaces +included in a storey. A space can also be decomposed in parts, +where each part defines a partial space. This is defined by the +CompositionType attribute of the supertype +IfcSpatialStructureElement which is interpreted as +follow:

                  +
                    +
                  • COMPLEX = space group
                  • +
                  • ELEMENT = space
                  • +
                  • PARTIAL = partial space
                  • +
                  +
                  NOTE View definitions and implementation +agreements may restrict spaces with CompositionType=ELEMENT +to be non-overlapping.
                  +

                  The following guidelines should apply for using the Name, +Description, LongName and ObjectType +attributes.

                  +
                    +
                  • Name holds the unique name (or space number) from the +plan.
                  • +
                  • Description holds any additional information field the +user may have specified, there are no further recommendations.
                  • +
                  • LongName holds the full name of the space, it is often +used in addition to the Name, if a number is assigned to the +room, then the descriptive name is exchanged as +LongName.
                  • +
                  • ObjectType holds the space type, i.e. usually the +functional category of the space .
                  • +
                  +
                  HISTORY New Entity in IFC Release 1.0
                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to the IfcSpace are defined by +the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcSpace are part of this +IFC release:

                  + + +

                  Quantity Use Definition

                  +

                  The quantities relating to the IfcSpace are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following base +quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + + +

                  Spatial Structure Use Definition

                  +

                  The IfcSpace is used to build the spatial structure of a +building (that serves as the primary project breakdown and is +required to be hierarchical). The spatial structure elements are +linked together by using the objectified relationship +IfcRelAggregates. The IfcSpace references them by its +inverse relationships:

                  +
                    +
                  • IfcSpace.Decomposes -- referencing (IfcSite || +IfcBuildingStorey || IfcSpace) by +IfcRelAggregates.RelatingObject, If it refers to another +instance of IfcSpace, the referenced IfcSpace +needs to have a different and higher CompositionType, i.e. +COMPLEX (if the other IfcSpace has ELEMENT), or ELEMENT (if +the other IfcSpace has PARTIAL).
                  • +
                  • IfcSpace.IsDecomposedBy -- referencing (IfcSpace) +by IfcRelAggregates.RelatedObjects. If it refers to another +instance of IfcSpace, the referenced IfcSpace needs +to have a different and lower CompositionType, i.e. ELEMENT +(if the other IfcSpace has COMPLEX), or PARTIAL (if the +other IfcSpace has ELEMENT).
                  • +
                  +

                  If there are building elements and/or other elements directly +related to the IfcSpace (like most furniture and +distribution elements), they are associated with the +IfcSpace by using the objectified relationship +IfcRelContainedInSpatialStructure. The IfcSpace +references them by its inverse relationship:

                  +
                    +
                  • IfcSpace.ContainsElements -- referencing any subtype of +IfcProduct (with the exception of other spatial structure +element) by +IfcRelContainedInSpatialStructure.RelatedElements.
                  • +
                  + +

                  Figure 57 shows the IfcSpace as part of the spatial structure. It also serves as the spatial container for space related elements.

                  +
                  NOTE Detailed requirements on mandatory element containment and placement structure relationships are given in view definitions and implementer agreements.
                  + + + + +

                  Figure 57 — Space composition

                  + +

                  Attribute Use Definition

                  + +

                  Figure 58 describes the heights and elevations of the IfcSpace.

                  +
                    +
                  • elevation of the space (top of construction slab) equals elevation of storey: provided by IfcBuildingStorey.Elevation relative to IfcBuilding.ElevationOfRefHeight
                  • +
                  • elevation of the space flooring (top of flooring on top of slab): provided by IfcSpace.ElevationWithFlooring relative to IfcBuilding.ElevationOfRefHeight
                  • +
                  • height of space (top of slab below to bottom of slab above): provided by BaseQuantity with Name=""Height""
                  • +
                  • floor height of space (top of slab below to top of flooring): provided by BaseQuantity with Name=""FinishFloorHeight""
                  • +
                  • net height of space (top of flooring to bottom of suspended ceiling): provided by BaseQuantity with Name=""FinishCeilingHeight""
                  • +
                  + + + + +

                  Figure 58 — Space elevations

                  + +

                  Geometry Use Definition

                  +

                  The geometric representation of IfcSpace is given by the +IfcProductDefinitionShape and IfcLocalPlacement +allowing multiple geometric representations.

                  +
                  NOTE In cases of inconsistency between the +geometric representation of the IfcSpace and the combined +geometric representations of the surrounding +IfcRelSpaceBoundary, the geometric representation of the +space should take priority over the geometric representation of the +surrounding space boundaries.
                  +

                  Local Placement

                  +

                  The local placement for IfcSpace is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point to the local placement of the +IfcSpatialStructureElement of type ""IfcBuildingStorey"", if +relative placement is used, or of type ""IfcSpace"" (e.g. to position +a space relative to a space group, or a partial space to a +space).
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Currently, the use of a 2D 'FootPrint' representation of type +'Curve2D' or 'GeometricCurveSet' and a 3D 'Body' representation of +type 'SweptSolid, 'Clipping' and 'Brep' is supported.

                  +

                  'Foot Print' Representation

                  +

                  The 2D geometric representation of IfcSpace is defined +using the 'Curve2D' or 'GeometricCurveSet' geometry. The following +attribute values should be inserted

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = 'Curve2D' or +'GeometricCurveSet' .
                  • +
                  +

                  The following constraints apply to the 2D representation:

                  +
                    +
                  • Profile: IfcBoundedCurve is required, using +IfcPolyline for faceted space contours or +IfcCompositeCurve for space contours with arc segments. For +spaces with inner boundaries, a set of IfcBoundedCurve's is +used, that should be grouped into an +IfcGeometricCurveSet.
                  • +
                  + +

                  Figure 59 shows a two-dimensional bounded curve representing the +foot print of IfcSpace.

                  + + + + +

                  Figure 59 — Space footprint

                  + +

                  'Swept Solid' Representation

                  +

                  The standard geometric representation of IfcSpace is +defined using the swept area solid geometry. The following +attribute values should be inserted

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'SweptSolid'.
                  • +
                  +

                  The following constraints apply to the standard +representation:

                  +
                    +
                  • Solid: IfcExtrudedAreaSolid is required,
                  • +
                  • Profile: IfcArbitraryClosedProfileDef is +required, IfcArbitraryProfileDefWithVoids shall be +supported.
                  • +
                  • Extrusion: The extrusion direction shall be vertically, +i.e., along the positive Z Axis of the co-ordinate system of the +containing spatial structure element.
                  • +
                  + +

                  Figure 60 shows an extrusion of an arbitrary profile definition with voids into the swept area solid of IfcSpace.

                  + + + + +

                  Figure 60 — Space body swept solid

                  + +

                  'Clipping' representation

                  +

                  The advanced geometric representation of IfcSpace is +defined using the swept area solid geometry that can be subjected +to a Boolean expression. The following attribute values should be +inserted.

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'Clipping'.
                  • +
                  +

                  The following additional constraints apply to the advanced +representation:

                  +
                    +
                  • Solid: see standard geometric representation,
                  • +
                  • Profile: see standard geometric representation,
                  • +
                  • Extrusion: see standard geometric representation,
                  • +
                  • Boolean result: The difference operation with the second +operand being of type IfcHalfSpaceSolid (or one of its +subtypes) shall be supported.
                  • +
                  + +

                  Figure 61 shows an extrusion of an arbitrary profile definition into the swept area solid. The solid and an half space solid are operands of the Boolean result of IfcSpace. + + + + +

                  Figure 61 — Space body clipping

                  + +

                  'Brep' representation

                  +

                  The fallback advanced geometric representation of +IfcSpace is defined using the Brep solid geometry. may +be represented as a single or multiple instances of +IfcFacetedBrep or IfcFacetedBrepWithVoids. The Brep +representation allows for the representation of complex element +shape. The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier : +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType : +'Brep'
                  • +
                  +
                  " +501;IfcSpatialStructureElement;" +

                  A spatial structure element +(IfcSpatialStructureElement) is the generalization of all +spatial elements that might be used to define a spatial +structure. That spatial structure is often used to provide a +project structure to organize a building project.

                  +

                  A spatial project structure might define as many levels of +decomposition as necessary for the building project. Elements +within the spatial project structure are:

                  +
                    +
                  • site as IfcSite
                  • +
                  • building as IfcBuilding
                  • +
                  • storey as IfcBuildingStorey
                  • +
                  • space as IfcSpace
                  • +
                  +

                  or aggregations or parts thereof. The composition type +declares an element to be either an element itself, or an +aggregation (complex) or a decomposition (part). The +interpretation of these types is given at each subtype of +IfcSpatialStructureElement.

                  +

                  The IfcRelAggregates is defined as an 1-to-many +relationship and used to establish the relationship between +exactly two levels within the spatial project structure. Finally +the highest level of the spatial structure is assigned to +IfcProject using the IfcRelAggregates.

                  +

                  Informal proposition:

                  +
                    +
                  1. The spatial project structure, established by the +IfcRelAggregates, shall be acyclic.
                  2. +
                  3. A site should not be (directly or indirectly) associated to a +building, storey or space.
                  4. +
                  5. A building should not be (directly or indirectly) associated +to a storey or space.
                  6. +
                  7. A storey should not be (directly or indirectly) associated to +a space.
                  8. +
                  +
                  HISTORY New entity in IFC Release 2x.
                  + +

                  Relationship Use Definition

                  +

                  The subtypes of IfcSpatialStructureElement relate to +other elements and systems by establishing the following +relationships:

                  +
                    +
                  • Containment of elements : +IfcRelContainedInSpatialStructure by inverse attribute +ContainsElements, used to assign any element, like +building elements, MEP elements, etc. to the spatial structure +element in which they are primarily contained. +
                      +
                    • NOTE This relationship is +mandatory for elements in several view definitions and +implementer agreements.
                    • +
                    +
                  • +
                  • Reference of elements : +IfcRelReferencedInSpatialStructure by inverse attribute +ReferencesElements, used to reference any element, like +building elements, MEP elements, etc. in spatial structure +elements, other then the one, where it is contained.
                  • +
                  • Reference of systems : IfcRelServicesBuildings +by inverse attribute ServicedBySystems, used to reference +a sytem, like a building service or electrical distribution +system, a zonal system, or a structural analysis system, that is +assigned to this spatial structure element. +
                      +
                    • NOTE Elements within the +referenced system may be directly contained (or referenced) by +other spatial structure elements.
                    • +
                    +
                  • +
                  +

                  The subtypes of IfcSpatialStructureElement relate to +each other by using the IfcRelAggregates relationship to +build the project spatial structure.

                  + +

                  Figure 62 shows the use of IfcRelAggregates to establish a spatial structure including site, building, building section and storey. More information is provided at the level of the subtypes.

                  + + + + +

                  Figure 62 — Spatial structure element composition

                  + +
                  " +509;IfcSpatialElement;" +

                  + Definition from IAI: A spatial element is the + generalization of all spatial elements that might be used + to define a spatial structure or to define spatial zones. +

                  +
                    +
                  • a hierarchical spatial structure element as + IfcSpatialStructureElement +
                      +
                    • a spatial structure is a hiearchical decomposition + of the project. That spatial structure is often used to + provide a project structure to organize a building + project. +
                    • +
                    • A spatial project structure might define as many + levels of decomposition as necessary for the building + project. Elements within the spatial project structure + are site, building, storey, and space +
                    • +
                    +
                  • +
                  • a spatial zone as IfcSpatialZone +
                      +
                    • a spatial zone is a non-hierarchical and + potentially overlapping decomposition of the project + under some functional consideration. +
                    • +
                    • a spatial zone might be used to represent a thermal + zone, a lighting zone, a usable area zone. +
                    • +
                    • a spatial zone might have its independent placement + and shape representation. +
                    • +
                    +
                  • +
                  +
                  + HISTORY New entity in IFC + Release 2x Edition 4. +
                  +
                  " +516;IfcElement;" +

                  Definition from IAI: Generalization of all components +that make up an AEC product. Those elements can be logically +contained by a spatial structure element that constitutes a +certain level within a project structure hierarchy (e.g., site, +building, storey or space). This is done by using the +IfcRelContainedInSpatialStructure relationship.

                  +

                  Elements are physically existent objects, although they might +be void elements, such as holes. Elements either remain +permanently in the AEC product, or only temporarily, as formwork +does. Elements can be either assembled on site or +pre-manufactured and built in on site.

                  +
                  EXAMPLEs of elements in a building +construction context are walls, floors, windows and +recesses.
                  +

                  An element can have material and quantity information assigned +through the IfcRelAssociatesMaterial and +IfcRelDefinesByProperties relationship.

                  +

                  In addition an element can be declared to be a specific +occurrence of an element type (and thereby be defined by the +element type properties) using the IfcRelDefinesByType +relationship.

                  +

                  An element can also be defined as an element assembly that is +a group of semantically and topologically related elements that +form a higher level part of the AEC product. Those element +assemblies are defined by virtue of the IfcRelAggregates +relationship.

                  +
                  EXAMPLEs for element assembly are +complete Roof Structures, made by several Roof Areas, or a Stair, +composed by Flights and Landings.
                  +

                  Elements that performs the same function may be grouped by an +""Element Group By Function"". It is realized by an instance of +IfcGroup with the ObjectType = +'ElementGroupByFunction"".

                  +
                  HISTORY New entity in +IFC Release 1.0
                  +

                  Property Set Use Definition:

                  +

                  The property sets relating to the IfcElement are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship.

                  +

                  Quantity Use Definition:

                  +

                  The quantities relating to the IfcElement are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties. A detailed specification for +individual quantities is introduced at the level of subtypes of +IfcElement.

                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of any IfcElement is given +by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations. A detailed specification for the local placement +and shape representaion is introduced at the level of subtypes of +IfcElement.

                  +
                  " +537;IfcBuildingElement;" +

                  Definition from ISO 6707-1:1989: Major functional part +of a building, examples are foundation, floor, roof, wall.

                  +

                  The building element comprises all +elements that are primarily part of the construction of a +building, i.e., its structural and space separating system.

                  +
                  EXAMPLEs of building elements are walls, +beams, or doors, they are all physically existent and tangible +things.
                  +

                  The IfcBuildingElement utilizes the following +capabilities mainly through inverse attributes referencing +objectified relationships:

                  +
                  NOTE View definitions and implementer +agreements will determine those relationships that have to be +supported in actual exchange.
                  +
                    +
                  1. Grouping - being part of a logical group of objects +
                      +
                    • objectified relationship: IfcRelAssignsToGroup
                    • +
                    • object referenced by relationship: IfcGroup (and +subtypes)
                    • +
                    • inverse attribute: HasAssignment
                    • +
                    +
                  2. +
                  3. Work processes - reference to work tasks, in which this +building element is used +
                      +
                    • objectified relationship: IfcRelAssignsToProcess
                    • +
                    • object referenced by relationship: IfcProcess (and +subtypes)
                    • +
                    • inverse attribute: HasAssignments
                    • +
                    +
                  4. +
                  5. Structural member reference - information whether the +building element is represented in a structural analysis model by +a structural member +
                      +
                    • objectified relationship: IfcRelAssignsToProduct
                    • +
                    • object referenced by relationship: IfcStructuralMember +(and by default IfcStructuralCurveMember)
                    • +
                    • inverse attribute: HasAssignments
                    • +
                    +
                  6. +
                  7. Aggregation - aggregated together with other elements to form +an aggregate +
                      +
                    • objectified relationship: IfcRelAggregates
                    • +
                    • object referenced by relationship: IfcElement (and +subtypes)
                    • +
                    • inverse attribute (for container): IsDecomposedBy
                    • +
                    • inverse attribute (for contained parts): +Decomposes
                    • +
                    +
                  8. +
                  9. Material - assignment of material used by this building +element +
                      +
                    • objectified relationship: +IfcRelAssociatesMaterial
                    • +
                    • object referenced by relationship: IfcMaterialSelect +(and selected items)
                    • +
                    • inverse attribute: HasAssociations
                    • +
                    +
                  10. +
                  11. Classification - assigned reference to an external +classification +
                      +
                    • objectified relationship: +IfcRelAssociatesClassification
                    • +
                    • object referenced by relationship: +IfcClassificationNotationSelect (and selected items, +default IfcClassificationReference)
                    • +
                    • inverse attribute: HasAssociations
                    • +
                    +
                  12. +
                  13. Library - assigned reference to an external library item +reference +
                      +
                    • objectified relationship: +IfcRelAssociatesClassification
                    • +
                    • object referenced by relationship: IfcLibrarySelect +(and selected items, default IfcLibraryReference)
                    • +
                    • inverse attribute: HasAssociations
                    • +
                    +
                  14. +
                  15. Documentation - assigned reference to an external +documentation +
                      +
                    • objectified relationship: +IfcRelAssociatesDocumentation
                    • +
                    • object referenced by relationship: IfcDocumentSelect +(and selected items, default IfcDocumentReference)
                    • +
                    • inverse attribute: HasAssociations
                    • +
                    +
                  16. +
                  17. Type - reference to the common product type information for +the element occurrence +
                      +
                    • objectified relationship: IfcRelDefinesByType
                    • +
                    • object referenced by relationship: +IfcBuildingElementType (and subtypes)
                    • +
                    • inverse attribute: IsTypedBy
                    • +
                    +
                  18. +
                  19. Properties - reference to all attached properties, including +quantities +
                      +
                    • objectified relationship: +IfcRelDefinesByProperties
                    • +
                    • object referenced by relationship: +IfcPropertySetDefinition (default +IfcPropertySet)
                    • +
                    • inverse attribute: IsDefinedBy
                    • +
                    +
                  20. +
                  21. Connection - connectivity to other elements, including the +definition of the joint +
                      +
                    • objectified relationship: IfcRelConnectsElements
                    • +
                    • object referenced by relationship: IfcElement
                    • +
                    • inverse attribute: ConnectedTo
                    • +
                    • inverse attribute: ConnectedFrom
                    • +
                    +
                  22. +
                  23. Realization - information, whether the building element is +used to realize a connection (e.g. as a weld in a connection +between two members) +
                      +
                    • objectified relationship: +IfcRelConnectsWithRealizingElements
                    • +
                    • object referenced by relationship: IfcElement
                    • +
                    • inverse attribute: IsConnectionRealization
                    • +
                    +
                  24. +
                  25. Assignment to spatial structure - hierarchical assignment to +the right level within the spatial structure +
                      +
                    • objectified relationship: +IfcRelContainedInSpatialStructure
                    • +
                    • object referenced by relationship: +IfcSpatialStructureElement
                    • +
                    • inverse attribute: ContainedInStructure
                    • +
                    +
                  26. +
                  27. Reference to spatial structure(s) - non hierarchical +reference to one or more elements within the spatial structure +(e.g. a curtain wall, being contained in the building, references +several stories) +
                      +
                    • objectified relationship: +IfcRelContainedInSpatialStructure
                    • +
                    • object referenced by relationship: +IfcSpatialElement
                    • +
                    • inverse attribute: ContainedInStructure
                    • +
                    +
                  28. +
                  29. Boundary - provision of space boundaries by this building +element +
                      +
                    • objectified relationship: IfcRelSpaceBoundary
                    • +
                    • object referenced by relationship: IfcSpace
                    • +
                    • inverse attribute: ProvidesBoundaries
                    • +
                    +
                  30. +
                  31. Coverings - assignment of covering elements to this building +element (note: normally covering elements are assigned to the +space, only used for special cases) +
                      +
                    • objectified relationship: +IfcRelCoversBldgElements
                    • +
                    • object referenced by relationship: IfcCovering
                    • +
                    • inverse attribute: HasCoverings
                    • +
                    +
                  32. +
                  33. Voids - information, whether the building element includes +openings, recesses or other voids +
                      +
                    • objectified relationship: IfcRelVoidsElement
                    • +
                    • object referenced by relationship: +IfcFeatureElementSubtraction (default +IfcOpeningElement)
                    • +
                    • inverse attribute: HasOpenings
                    • +
                    +
                  34. +
                  35. Projection - information, whether the building element has +projections (such as a fascia) +
                      +
                    • objectified relationship: IfcRelProjectsElement
                    • +
                    • object referenced by relationship: +IfcFeatureElementAddition (default +IfcProjectionElement)
                    • +
                    • inverse attribute: HasProjections
                    • +
                    +
                  36. +
                  37. Filling - information whether the building element is used to +fill openings +
                      +
                    • objectified relationship: IfcRelFillsElement
                    • +
                    • object referenced by relationship: +IfcOpeningElement
                    • +
                    • inverse attribute: FillsVoids
                    • +
                    +
                  38. +
                  +
                  HISTORY New entity in IFC Release 1.0
                  + +

                  Property Set Use Definition

                  +

                  The properties relating to the IfcBuildingElement are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties. A detailed specification for +individual property sets applicable is introduced at the level of +subtypes of IfcBuildingElement.

                  +
                  NOTE The applicable property sets are provided +by an xml property set definition that includes multilingual +translations for each property. The xml definition file format, +psdXML, can be used to automatically configure the properties for +each building element.
                  +

                  Quantity Use Definition:

                  +

                  The quantities relating to the IfcBuildingElement are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties. A detailed specification for +individual quantities is introduced at the level of subtypes of +IfcBuildingElement.

                  +
                  NOTE The applicable element quantities are +provided by an xml quantity definition that includes multilingual +translations for each quantity. The xml definition file format, +qdXML, can be used to automatically configure the quantities for +each building element.
                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of any IfcBuildingElement +is given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations.

                  +

                  Local Placement

                  +

                  The local placement for any IfcBuildingElement is +defined in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations. +Further constraints are defined at the level of its subtypes.

                  +

                  Geometric Representations

                  +

                  An IfcBuildingElement can be represented by one or +several geometric representations. The following representation +identifiers are used for building elements 'Box', 'Axis', +'FootPrint', 'Surface', and 'Body'. A detailed specification is +introduced at the level of subtypes.

                  +
                  NOTE Some subtypes of +IfcBuildingElement may exclude one or several geometric +representation types, e.g. standard case elements, such as +IfcWallStandardCase, do not allow the use of +'SurfaceModel', 'Brep', 'AdvancedBrep', and +'MappedRepresentation'. In addition view definitions and +implementer agreements may restrict the use of geometric +representation types, e.g. the use of +'AdvancedBrep'.
                  +

                  Box Representation

                  +

                  Any IfcBuildingElement may be represented as a bounding +box, which shows the maximum extend of the body within the +coordinated system established by the IfcLocalPlacement. +The bounding box representation is the simplest geometric +representation available. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Box'
                  • +
                  • RepresentationType : 'BoundingBox'
                  • +
                  + +

                  As shown in Figure 22, the bounding box representation is given by an +IfcShapeRepresentation that includes a single item, an +IfcBoundingBox.

                  + + + + + + + + +
                  +""bounding +

                  Figure 22 — Building element box representation

                  + +

                  Axis Representation

                  +

                  Some IfcBuildingElement may be represented by an axis +as an abstract geometric representation. See each subtype for +specific guidance. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation are used:

                  +
                    +
                  • RepresentationIdentifier : 'Axis'
                  • +
                  • RepresentationType : 'Curve2D', 'Curve3D'
                  • +
                  +

                  Surface Representation

                  +

                  Some IfcBuildingElement may be represented by an +surface as an abstract geometric representation. See each subtype +for specific guidance. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation are used:

                  +
                    +
                  • RepresentationIdentifier : 'Surface'
                  • +
                  • RepresentationType : 'Surface2D', 'Surface3D'
                  • +
                  +

                  FootPrint Representation

                  +

                  Any IfcBuildingElement may be represented by a +footprint as a specific floor plan geometric representation. See +each subtype for specific guidance. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation are used:

                  +
                    +
                  • RepresentationIdentifier : 'FootPrint'
                  • +
                  • RepresentationType : 'GeometricCurveSet', +'Annotation2D'
                  • +
                  +

                  Body Representation

                  +

                  The body representation of any IfcBuildingElement can +have the following representation types: 'SurfaceModel', 'Brep', +'AdvancedBrep', and 'MappedRepresentation'. Other representation +types might be specified at the level of subtypes.

                  +

                  SurfaceModel Representation Type

                  +

                  Any IfcBuildingElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple surface models, based on either shell or face +based models. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SurfaceModel'
                  • +
                  +

                  In some cases it may be useful to also expose a simple +representation as a bounding box representation of the same +complex shape.

                  + +

                  As shown in Figure 23, the surface model representation is given by an IfcShapeRepresentation, which includes a single item which is either:

                  +
                    +
                  • IfcShellBasedSurfaceModel, or
                  • +
                  • IfcFaceBasedSurfaceModel.
                  • +
                  + + + + + +

                  Figure 23 — Building element surface model representation

                  + +

                  Brep Representation Type

                  +

                  Any IfcBuildingElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple Boundary Representation elements (which are +restricted to faceted Brep with or without voids). The Brep +representation allows for the representation of complex element +shape. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'Brep'
                  • +
                  +

                  In some cases it may be useful to also expose a simple +representation as a bounding box representation of the same +complex shape.

                  +

                  As shown in Figure 24, the Brep representation is given by an IfcShapeRepresentation, which includes one or more items, all of type IfcFacetedBrep.

                  + + + + + + +

                  Figure 24 — Building element body boundary representation

                  + +

                  AdvancedBrep Representation Type

                  +

                  An IfcBuildingElement (so far no further constraints +are defined at the level of its subtypes or by view definitions) +may be represented as a single or multiple Boundary +Representation elements (which are based on advanced surfaces, +usually refered to as NURBS surfaces). The AdvancedBrep +representation allows for the representation of complex free-form +element shape. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'AdvancedBrep'
                  • +
                  +

                  In some cases it may be useful to also expose a simple +representation as a bounding box representation of the same +complex shape.

                  +

                  MappedRepresentation Representation Type

                  +

                  Any IfcBuildingElement (so far no further constraints +are defined at the level of its subtypes) may be represented +using the MappedRepresentation. This shall be supported as it +allows for reusing the geometry definition of a type at all +occurrences of the same type. The following attribute values for +the IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'MappedRepresentation'
                  • +
                  +

                  The same constraints, as given for 'SurfaceModel', 'Brep', and +'AdvancedBrep' geometric representation, shall apply to the +MappedRepresentation of the +IfcRepresentationMap.

                  +
                  " +540;IfcFurnishingElement;" +

                  Definition from IAI: Generalization of all furniture +related objects. Furnishing objects are characterized as +being

                  +
                    +
                  • pre-manufactured and assembled on-site, or
                  • +
                  • manufactured on-site (built-in)
                  • +
                  +

                  Thus furnishing elements can either be movable, or not (as the +built-ins).

                  +
                  HISTORY New entity in +IFC Release 2x.
                  +IFC2x4 CHANGE The entity is marked +as deprecated for instantiation - will be made ABSTRACT after +IFC2x4.
                  +

                  Geometry Use Definitions:

                  +

                  The geometric representation of IfcFurnishingElement is +given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcFurnishingElement is defined +in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement , which +is used in the ContainedInStructure inverse attribute, or +to a spatial structure element at a higher level, referenced by +that.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Any IfcFurnishingElement can be represented by one or +several geometric representations. This includes the general +representation types 'BoundingBox', 'GeometricCurveSet', +'SurfaceModel', 'Brep', and 'MappedRepresentation' being defined +here.

                  +

                  Bounding Box Representation

                  +

                  Any IfcFurnishingElement may be represented as a +bounding box, which shows the maximum extend of the body within +the coordinated system established by the +IfcLocalPlacement. The bounding box representation is the +simplest geometric representation available. The following +attribute values for the IfcShapeRepresentation holding +this geometric representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Box'
                  • +
                  • RepresentationType : 'BoundingBox'
                  • +
                  +

                  Foot Print Representation

                  +

                  The foot print representation of IfcFurnishingElement +is given by either a single or multiple 2D points and curves. The +representation identifier and type of this geometric +representation are:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet'
                  • +
                  +

                  SurfaceModel Representation

                  +

                  Any IfcFurnishingElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple surface models, based on either shell or face +based models. In some cases it may be useful to also expose a +simple representation as a bounding box representation of the +same complex shape. The representation identifier and type of +this geometric representation are:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'SurfaceModel'
                  • +
                  +

                  Brep Representation

                  +

                  Any IfcFurnishingElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple Boundary Representation elements (which are +restricted to faceted Brep with or without voids). The Brep +representation allows for the representation of complex element +shape. In some cases it may be useful to also expose a simple +representation as a bounding box representation of the same +complex shape. The representation identifier and type of this +geometric representation are:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'Brep'
                  • +
                  +

                  MappedRepresentation

                  +

                  The IfcMappedItem should always be used in appropriate +cases as it allows for reusing the geometry definition of the +furnishing type for all occurrences of the same type. The +representation identifier and type of this geometric +representation are:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint', or 'Body' (depending of the representation map)
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'MappedRepresentation'
                  • +
                  + +
                  " +541;IfcDistributionElement;" +

                  Definition from IAI: Generalization of all elements +that participate in a distribution system. Typical examples of +IfcDistributionElement are (among others):

                  +
                    +
                  • building service elements within a heating systems
                  • +
                  • building service elements within a cooling system
                  • +
                  • building service elements within a ventilation system
                  • +
                  • building service elements within a plumbing system +
                      +
                    • e.g. sanitary elements, fire suppression elements
                    • +
                    +
                  • +
                  • electrical elements
                  • +
                  • elements within a communication network
                  • +
                  +

                  The IfcDistributionElement is further specialized in +the IFC model. Direct instantiation of +IfcDistributionElement without an assigned subtype of +IfcDistributionElementType provides the meaning of an +distribution element proxy.

                  +
                  HISTORY New entity in +IFC Release 1.5.
                  +IFC2x4 CHANGE The entity is marked +as deprecated for instantiation - will be made ABSTRACT after +IFC2x4.
                  +

                  Relationship Use Definition

                  +
                    +
                  1. Ports - information, whether the distribution element has +ports for system connections +
                      +
                    • objectified relationship: +IfcRelConnectsPortToElement
                    • +
                    • object referenced by relationship: IfcPort
                    • +
                    • inverse attribute: HasPorts
                    • +
                    +
                  2. +
                  +

                  Type Use Definition

                  +

                  The IfcDistributionElement defines the occurrence of +any HVAC, electrical, sanitary or other element within a +distribution system. Common information about distribution +element types (or styles) is handled by subtypes of +IfcDistributionElementType. The +IfcDistributionElementType (if present) may establish the +common type name, usage (or predefined) type, common material, +common set of properties and common shape representations (using +IfcRepresentationMap). The +IfcDistributionElementType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                  +

                  The assignment of types to distribution element occurrences is +vital for providing the additional meaning, or ontology, of the +distribution element. Many specialized type are defined in other +schemas of the IFC specification.

                  +

                  Quantity Use Definition

                  +

                  The quantities relating to the IfcDistributionElement +are defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties. A detailed specification for +individual quantities is introduced at the level of subtypes of +IfcDistributionElement.

                  +

                  Containment Use Definition

                  +

                  The IfcDistributionElement may participate in two +different containment relationships. The first (and in most +implementation scenarios mandatory) relationship is the +hierachical spatial containment, the second (optional) +relationship is the aggregation within anÿelement assembly.

                  +
                    +
                  • The IfcDistributionElement is places within the +project spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcSpace being the default +container.
                  • +
                  • The IfcDistributionElement may be aggregated into an +element assembly using the objectified relationship +IfcRelAggregates, referring to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this +case it should not be additionally contained in the project +spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                  • +
                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcDistributionElement +is given by the IfcProductDefinitionShape, allowing +multiple geometric representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcDistributionElement is +defined in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement , which +is used in the ContainedInStructure inverse attribute, or +to a spatial structure element at a higher level, referenced by +that.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  The geometric representation of IfcDistributionElement +is defined using different geometric representation types for the +various subtypes. Only general recommendations are given at the +level of the supertype, further constraints are defined at the +level of its subtypes.

                  +
                    +
                  • all occurrences of IfcDistributionElement (and its +subtypes) should (whenever possible) share a representation map +established by the assigned type. The geometric representation of +the occurrence is then an IfcMappedItem. The +IfcShapeRepresentation has: +
                      +
                    • RepresentationIdentifier : 'Body'
                    • +
                    • RepresentationType : 'MappedRepresentation'
                    • +
                    +
                  • +
                  +

                  The shared geometric representation of the distribution +element type (or in some cases of the distribution element) +should follow (if applicable) the the following guidelines:

                  +
                    +
                  • all fixtures (all non distribution flow elements, i.e. +everything which is not a duct, a pipe, a cable, or a cable +carrier) should be defined by an b-rep geometry. This includes +also the complex flow fitting elements (e.g. Y branch or T +branch) or distribution flow elements with size changes (e.g. +reducer). The IfcShapeRepresentation has: +
                      +
                    • RepresentationIdentifier : 'Body'
                    • +
                    • RepresentationType : 'Brep'
                      +
                    • +
                    +
                  • +
                  • if the geometric model consistency of a b-rep shape +representation can not be guaranteed (arcwise connected volume +bounded by faces, each being connected, oriented, finite, closed +2-manifold), a surface representation based on open shells should +be used. The IfcShapeRepresentation then has: +
                      +
                    • RepresentationIdentifier : 'Body'
                    • +
                    • RepresentationType : 'SurfaceModel'
                      +
                    • +
                    +
                  • +
                  • all ""simple"" distribution flow elements (general ducts and +pipes) are defined by sweep geometry. The +IfcShapeRepresentation has: +
                      +
                    • RepresentationIdentifier : 'Body'
                    • +
                    • RepresentationType : 'SweptSolid'
                      +
                    • +
                    +
                  • +
                  • an additional representation type for all ""simple"" +distribution flow elements (general ducts and pipes) is the +ability to have a simple line based representation. The +IfcShapeRepresentation has: +
                      +
                    • RepresentationIdentifier : 'FootPrint'
                    • +
                    • RepresentationType : 'GeometricCurveSet'
                      +
                    • +
                    +
                  • +
                  • if only the analytical shape is required for which the exact +interpolation between the cross sections is not required, a +sectioned spine can be used. +
                      +
                    • RepresentationIdentifier : 'Body'
                    • +
                    • RepresentationType : 'SectionedSpine'
                    • +
                    +
                  • +
                  +
                  " +545;IfcDistributionElementType;" +

                  Definition from IAI: The +IfcDistributionElementType defines a list of commonly +shared property set definitions of an element and an optional set +of product representations. It is used to define an element +specification (i.e. the specific product information, that is +common to all occurrences of that product type).

                  +
                  NOTEÿ The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
                  +

                  A distribution element type is used to define the common +properties of a certain type of a distribution element that may +be applied to many instances of that feature type to assign a +specific style. Distribution element types (or the instantiable +subtypes) may be exchanged without being already assigned to +occurrences.

                  +

                  The occurrences of the IfcDistributionElementType are +represented by instances of IfcDistributionElement (or its +subtypes).

                  +
                  HISTORYÿ New entity in +Release IFC2x Edition 2.
                  +IFC2x3 CHANGEÿ The entity has been made +non-abstract

                  +IFC2x4 CHANGE The entity is marked +as deprecated for instantiation - will be made ABSTRACT after +IFC2x4.
                  +
                  " +549;IfcElementType;" +

                  + Definition from IAI: The IfcElementType + defines a list of commonly shared property set definitions + of an element and an optional set of product + representations. It is used to define an element + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

                  +
                  +

                  + NOTE The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +

                  +
                  +

                  + An element type is used to define the common properties of + a certain type or style of an element that may be applied + to instances of that element type to assign a specific + style. Element types (the instantiable subtypes) may be + exchanged without being already assigned to occurrences. +

                  +
                  +

                  + HISTORY New entity in + Release IFC2x Edition 2 +

                  +
                  +
                  " +557;IfcSpatialElementType;" +

                  Definition from IAI: The IfcSpatialElementType +defines a list of commonly shared property set definitions of a +spatial structure element and an optional set of product +representations. It is used to define a spatial element +specification (i.e. the specific element information, that is +common to all occurrences of that element type).

                  +
                  +

                  NOTE ÿThe product representations are defined as +representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.

                  +
                  +

                  A spatial element type is used to define the common properties +of a certain type of a spatial structure element that may be +applied to many instances of thatÿtype to assign a specific +style. Spatial element types (i.e. the instantiable subtypes) may +be exchanged without being already assigned to occurrences.

                  +
                  +

                  NOTE ÿThe spatial element types are often used to +represent catalogues of predefined spatial types for shared +attributes, less so for sharing a common representation +map.

                  +
                  +

                  The occurrences of subtypes of the abstract +IfcSpatialElementType are represented by instances of +subtypes of the abstract IfcSpatialElement.

                  +
                  +

                  HISTORY ÿNew entity in Release +IFC2x Edition 4.

                  +
                  +
                  " +561;IfcSpatialStructureElementType;" +

                  + Definition from IAI: The element type + (IfcSpatialStructureElementType) defines a list of + commonly shared property set definitions of a spatial + structure element and an optional set of product + representations. It is used to define an element + specification (i.e. the specific element information, that + is common to all occurrences of that element type). +

                  +
                  +

                  + NOTE ÿThe product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +

                  +
                  +

                  + A spatial structure element type is used to define the + common properties of a certain type of a spatial structure + element that may be applied to many instances of thatÿtype + to assign a specific style. Spatial structure element types + (i.e. the instantiable subtypes) may be exchanged without + being already assigned to occurrences. +

                  +
                  +

                  + NOTE ÿThe spatial structure element types are + often used to represent catalogues of predefined spatial + types for shared attributes, less so for sharing a common + representation map. +

                  +
                  +

                  + The occurrences of subtypes of the + abstractÿIfcSpatialStructureElementType are + represented by instances of subtypes of + IfcSpatialStructureElement. +

                  +
                  +

                  + HISTORY ÿNew entity in + Release IFC2x Edition 3. +

                  +
                  +
                  " +563;IfcSpaceType;" +

                  Definition from IAI: A space represents an area or +volume bounded actually or theoretically. Spaces are areas or +volumes that provide for certain functions within a building.

                  +

                  The IfcSpaceType defines a list of commonly shared +defines commonly shared information for occurrences of spaces. +The set of shared information may include:

                  +
                    +
                  • common properties within shared property sets
                  • +
                  • common shape representations
                  • +
                  +

                  It is used to define an space specification (i.e. the specific +space information, that is common to all occurrences of that +space type. Space types may be exchanged without being already +assigned to occurrences.

                  +
                  NOTE ÿThe space types are often used to +represent space catalogues, less so for sharing a common +representation map. Space types in a space catalogue share same +space classification and a common set of space requirement +properties.
                  +

                  The occurrences of IfcSpaceType are represented by +instances of IfcSpace.

                  +
                  +

                  HISTORY ÿNew entity in +IFC2x3.

                  +
                  +

                  Property Set Use Definition:

                  +

                  The shared property sets relating to the IfcSpaceType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcSpaceType are part of this +IFC release:

                  +
                  NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcSpaceType and those that are only assignable to +IfcSpace. If the same property is assigned to the +IfcSpaceType and the IfcSpace being an occurrence +of the IfcSpaceType, then the occurrence property +overrides the type property.
                  + +

                  Geometry Use Definition:

                  +

                  The IfcSpaceType may define the shared geometric +representation for all space occurrences. The +RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'FootPrint', or 'Body').

                  +
                  +

                  NOTE ÿThe product representations are defined as +representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.

                  +
                  +
                  However view definitions and implementer +agreements may prevent the usage of shared geometry for +spaces.
                  +. +
                  " +574;IfcSpatialZoneType;" +

                  Definition from IAI: The IfcSpatialZoneType +defines a list of commonly shared property set definitions of a +space and an optional set of product representations. It is used +to define a space specification (i.e. the specific space +information, that is common to all occurrences of that space +type).

                  +
                  +

                  NOTE ÿThe product representations are defined as +representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.

                  +
                  +

                  A spatial zone type is used to define the common properties of +a certain type of space that may be applied to many instances of +that type to assign a specific style. Space types may be +exchanged without being already assigned to occurrences.

                  +
                  +

                  NOTE ÿThe spatial zone types are often used to +represent space catalogues, less so for sharing a common +representation map. Spatial zone types in a space catalogue share +same space classification and a common set of space requirement +properties.

                  +
                  +

                  The occurrences of IfcSpatialZoneType are represented +by instances of IfcSpatialZone.

                  +
                  +

                  HISTORY ÿNew entity in Release +IFC2x Edition 4.

                  +
                  +
                  " +586;IfcBuildingElementType;" +

                  + Definition from IAI: The element type + (IfcBuildingElementType) defines a list of commonly + shared property set definitions of a building element and + an optional set of product representations. It is used to + define an element specification (i.e. the specific product + information, that is common to all occurrences of that + product type). +

                  +
                  +

                  + NOTE: The product representations are + defined as representation maps (at the level of the + supertype IfcTypeProduct, which gets assigned by + an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +

                  +
                  +

                  + A building element type is used to define the common + properties of a certain type of a building element that may + be applied to many instances of that feature type to assign + a specific style. Building element types (or the + instantiable subtypes) may be exchanged without being + already assigned to occurrences. +

                  +

                  + The IfcBuildingElementType is an abstract type. + Occurrences of subtypes of the + IfcBuildingElementType are represented by instances + of the appropriate subtypes of IfcBuildingElement. +

                  +
                  +

                  + HISTORY New entity in + Release IFC2x Edition 2. +

                  +
                  +
                  " +587;IfcFurnishingElementType;" +

                  Definition from IAI: The +IfcFurnishingElementType defines a list of commonly shared +property set definitions of an element and an optional set of +product representations. It is used to define an element +specification (i.e. the specific product information, that is +common to all occurrences of that product type).

                  +
                  NOTEÿ The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
                  +

                  A furnishing element type is used to define the common +properties of a certain type of a furnishing element that may be +applied to many instances of that feature type to assign a +specific style. Furnishing element types (or the instantiable +subtypes) may be exchanged without being already assigned to +occurrences.

                  +

                  The occurrences of the IfcFurnishingElementType are +represented by instances of IfcFurnishingElement (or its +subtypes).

                  +
                  HISTORYÿNew entity in +Release IFC2x Edition 2.
                  +IFC2x3 CHANGE The entity has been +made non-abstract
                  +IFC2x4 CHANGE The entity is marked +as deprecated for instantiation - will be made ABSTRACT after +IFC2x4.
                  +
                  " +590;IfcTransportElementType;" +

                  Definition from IAI: The element type +IfcTransportElementType defines commonly shared +information for occurrences of transport elements. The set of +shared information may include:

                  +
                    +
                  • common properties within shared property sets
                  • +
                  • common material information
                  • +
                  • common shape representations
                  • +
                  +

                  It is used to define a transport element specification (i.e. +the specific product information that is common to all +occurrences of that beam type). Transport element types (or the +instantiable subtypes) may be exchanged without being already +assigned to occurrences.

                  +

                  The occurrences of the IfcTransportElementType are +represented by instances of IfcTransportElement (or its +subtypes).

                  +
                  +

                  HISTORY: New entity in Release +IFC2x Edition 2.

                  +
                  +

                  Property Set Use Definition:

                  +

                  The shared property sets relating to the +IfcTransportElementType are defined by the +IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcTransportElementType are +part of this IFC release:

                  +
                  NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcTransportElementType and those that are only assignable +to IfcTransportElement. If the same property is assigned +to the IfcTransportElementType and the +IfcTransportElement being an occurrence of the +IfcTransportElementType, then the occurrence property +overrides the type property.
                  + +

                  Geometry Use Definition:

                  +

                  The IfcTransportElementType may define the shared +geometric representation for all transport element occurrences. +The RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'FootPrint', or +'Body').

                  +
                  NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
                  +
                  NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcTransportElementType.
                  +
                  " +601;IfcGeographicElementType;" +

                  + Definition from IAI: An + IfcGeographicElementType is used to define an + element specification of a geographic element (i.e. the + specific product information, that is common to all + occurrences of that product type).ÿGeographic element types + include for different types of element that may be used to + represent information within a geographical landscape + external to a building. Within the world of geographic + information they are referred to generally as 'features'.ÿ +

                  Geographic element types includes for many possibilities: +
                    +
                  • linear elements such as sections of a roadway + (including carriageway/pavement, verge, median, marker + line, kerb etc.), path, river, stream +
                  • +
                  • connections and junctions including traffic + roundabouts, T junctions, 4 way junctions +
                  • +
                  • point features such as street lighting, seating, bus + shelters, signage, trees +
                  • +
                  • linear features such as layby's +
                  • +
                  • area features such as ponds, lakes, woods and forests +
                  • +
                  +

                  + The specification of the specific types are given by the + inherited attribute IfcElementType.ElementType given + as an IfcLabel.ÿ +

                  +
                  +

                  + NOTE ÿThis is due to the range of choices of + element type thyat are available and their expression in + different languages. It is not considered possible to + create a reasonably full list of types within an + enumeration. It is suggested that selection of the + relevant type be drawn from an available 'feature + catalog'. +

                  +

                  + HISTORYÿ New entity in + Release IFC2x Edition 4. +

                  +
                  +

                  + Feature Catalog Use Definition +

                  +

                  + Geographic element types are frequently identified in + feature catalogs that are produced for particular + purposes.ÿThe IfcGeographicElementType entity + enables the continued use of existing feature catalogs + through capture of their identity and attributes. +

                  +

                  + Information from feature catalogs might be captured in + various ways: +

                  +
                    +
                  1. via property sets, some of which will be specifically + defined within the IFC property set catalog whilst others + will be created for local use; this is the form of capture + that is expected to be most widely used +
                  2. +
                  3. through use of the IFC classification model whereby + features might be identified through a classification + notation and additional description; in which case, any + further attributes required would still need to be captured + in property sets. +
                  4. +
                  +
                  " +607;IfcElementAssemblyType;" +

                  Definition from IAI: The IfcElementAssemblyType +defines a list of commonly shared property set definitions of an +element and an optional set of product representations. It is +used to define an element specification (i.e. the specific +product information, that is common to all occurrences of that +product type).

                  +
                  NOTEÿ The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
                  +

                  An element assembly type is used to define the common +properties of a certain type of an element assembly that may be +applied to many instances of that type to assign a specific +style. An element assembly types (or the instantiable subtypes) +may be exchanged without being already assigned to +occurrences.

                  +

                  The occurrences of the IfcElementAssemblyType are +represented by instances of IfcElementAssembly.

                  +
                  HISTORYÿ New entity in +Release IFC2x Edition 4.
                  +
                  " +622;IfcRelConnectsPortToElement;" +

                  The objectified relationship +IfcRelConnectsPortToElement defines the relationship that +is made between a port and the IfcElement, or +IfcElementType in which it is contained. It is a 1 to 1 +relationship.

                  +
                  +

                  The +IfcRelConnectsPortToElement established a whole part +relationship between the element and its port. The port is used as +the means to connect to other ports in other elements. Since both, +the element-to-port, and the port-to-port relationships are 1:1 +relationships, a topological system (or system path or ciruit) can +be defined.

                  +
                  +

                  Ports contained in different elements are connected to each +other using the IfcRelConnectsPorts relationship.

                  +
                  +

                  See relevant subtypes of +IfcDistributionElement for examples and port use +definition sections.

                  +
                  +
                  +

                  HISTORY  New +entity in Release IFC2x Edition 2.
                  +IFC2x4 CHANGE  The +definition has been extended to include element types.

                  +
                  + +
                  " +626;IfcPort;" +

                  + Definition from IAI: An IfcPort provides the + means for an element to connect to other elements. +

                  +

                  + An IfcPort is associated with an IfcElement, + it belongs to, through the objectified relationship + IfcRelConnectsPortToElement. Exactly two ports, + belonging to two different elements, are connected with + each other through the objectified relationship + IfcRelConnectsPorts. +

                  +

                  + An instance of IfcElement may have one or more + points at which it connects to other instances of + IfcElement. An instance of IfcPort is located + at a point where a connection can occur. The location of + the port is determined in the context of the local + coordinate system of the element to which it belongs. +

                  +
                  +

                  + HISTORY New entity in + Release IFC2x Edition 2. +

                  +
                  +

                  + Containment Use Definitions +

                  +

                  + As a subordinate part being fully dependent on the master + element the IfcPort shall have no + independent containment relationship to the spatial + structure. +

                  +

                  + Geometry Use Definition +

                  +

                  + The geometric representation of IfcPort is + given by the IfcProductDefinitionShape, allowing + multiple geometric representation. +

                  +

                  + Local Placement +

                  +

                  + The local placement for IfcPort is defined + in its supertype IfcProduct. It is defined by the + IfcLocalPlacement, which defines the local + coordinate system that is referenced by all geometric + representations. +

                  +
                    +
                  • The PlacementRelTo relationship of + IfcLocalPlacement shall point to the + local placement of the master IfcElement (its + relevant subtypes), which is associated to the + IfcPort by the relationship object + IfcRelConnectsPortToElement. +
                  • +
                  +

                  + Shape Representation +

                  +

                  + The geometry use definitions for the shape representation + of the IfcPort is given at the level of + its subtypes. +

                  +
                  " +630;IfcRelConnectsPorts;" +

                  + Definition from IAI: An IfcRelConnectsPorts + defines the relationship that is made between two ports at + their point of connection. It may include the connection + geometry between two ports. +

                  +

                  + IfcRelConnectsPorts is required for defining how + instances of IfcPort connect together. Each of the + port is being logically attached to the IfcElement + by using the IfcRelConnectsPortToElement + relationship. +

                  +
                  +

                  + HISTORY New entity in IFC + 2.0, modified in IFC2x. +

                  +
                  +
                  " +638;IfcTransportElement;" +

                  Definition from IAI: Generalization of all transport +related objects that move people, animals or goods within a +building or building complex. The IfcTransportElement +defines the occurrence of a transport element, that (if given), +is expressed by the IfcTransportElementType.

                  +
                  EXAMPLE Transportation elements include +elevator (lift), escalator, moving walkway, etc.
                  +NOTE More detailed equipment that may be a part of a +transportation device, like a lifting hook, is defined as +IfcDiscreteAccessory
                  +

                  Depending on local classification systems transport elements +and transportation systems in buildings are either considered as +part of a building system, or as part of a building service +system. Within IFC they are considered as part of a building +system and may have to be mapped appropriately.

                  +
                  HISTORY New entity in +IFC Release 2x.
                  +IFC2x PLATFORM CHANGE The attribute +PredefinedType (previously OperationType) is made +optional.
                  +

                  Type Use Definition

                  +

                  IfcTransportElement defines the occuurence of any +transportation device, common information about transportation +device types (or styles) is handled by +IfcTransportElementType. The +IfcTransportElementType (if present) may establish the +commonÿtype name, usage (or predefined) type, common material +layer set, common set of properties and common shape +representations (using IfcRepresentationMap). The +IfcTransportElementType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                  +

                  If no IfcTransportElementType is attachedÿ(i.e. if only +occurrence information is given) the PredefinedType should +be provided. If set to .USERDEFINED. a user defined value can be +provided by the ObjectType attribute.

                  +

                  Property Set Use Definition:

                  +

                  The property sets relating to the IfcTransportElement +are defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the +IfcTransportElement are part of this IFC release:

                  + +

                  Containment Use Definition

                  +

                  The IfcTransportElement, as any subtype of +IfcElement, may have a hierarchical spatial containment +relationships that is mandatory in most implementation +scenarios.

                  +
                    +
                  • The IfcTransportElement is placed within the project +spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuilding being the default +container.
                  • +
                  +

                  Geometry Use Definitions:

                  +

                  The geometric representation of IfcTransportElement is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcTransportElement is defined +in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement , which +is used in the ContainedInStructure inverse attribute, or +to a spatial structure element at a higher level, referenced by +that.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  SurfaceModel Representation

                  +

                  Any IfcTransportElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple surface models, based on either shell or face +based models. Then the following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SurfaceModel'
                  • +
                  +

                  Brep Representation

                  +

                  Any IfcTransportElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple Boundary Representation elements (which are +restricted to faceted Brep with or without voids). Then the +following attribute values for the IfcShapeRepresentation +holding this geometric representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'Brep'
                  • +
                  +

                  MappedRepresentation

                  +

                  The mapped item, IfcMappedItem, should be used if +appropriate as it allows for reusing the geometry definition of +the property element type at occurrences of the same equipement +type. Then the following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'MappedRepresentation'
                  • +
                  +
                  " +644;IfcFeatureElement;" +

                  Definition from IAI: Generalization of all existence +dependent elements which modify the shape and appearance of the +associated master element. The IfcFeatureElement offers +the ability to handle shape modifiers as semantic objects within +the IFC object model.

                  +
                  +

                  NOTE The term ""feature"" has a predefined meaning in a +context of ""feature-based modeling"" and within steel construction +work. It is introduced here in a broader sense to cover all +existence dependent, but semantically described, modifiers of an +element's shape and appearance. It is envisioned that future +releases enhance the feature-based capabilities of the IFC +model.

                  +
                  +

                  In contrary to the aggregation, as used in +IfcElementAssembly, that defines the aggregate as a +container element, that has equally treated parts, the feature +concept introduced by IfcFeatureElement defines the master +element with subordinate parts as additions, or with voids or +cut-outs as subtractions.

                  +
                  +

                  HISTORY New entity in Release +IFC2x Edition 2.
                  +NOTE The entity is introduced as an +upward compatible extension of the IFC2x platform. It is an +intermediate abstract supertype without defining its own explicit +attributes.

                  +
                  +

                  Containment Use Definition

                  +

                  As a subordinate part being fully dependent on the master +element the IfcFeatureElement shall have no independent +containment relationship to the spatial structure.

                  +
                    +
                  • The SELF\IfcElement.ContainedInStructure relationship +shall be NIL.
                  • +
                  +

                  Geometry Use Definition

                  +

                  The geometric representation of IfcFeatureElement is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcFeatureElement is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the master IfcElement (its relevant +subtypes), which is associated to the IfcFeatureElement by +the appropriate relationship object.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Any IfcFeatureElement can be represented by one or +several geometric representations. A detailed specification is +introduced at the level of subtypes. Only the general +representation identifier 'Box' with representation type +'BoundingBox', and representation identifier 'Body' with +representation type 'Brep' are defined here.

                  +

                  Box Representation

                  +

                  Any IfcFeatureElement may be represented as a bounding +box, which shows the maximum extend of the body within the +coordinated system established by the IfcLocalPlacement. +The bounding box representation is the simplest geometric +representation available. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Box'
                  • +
                  • RepresentationType : 'BoundingBox'
                  • +
                  +

                  Body Representation

                  +

                  The body representation of any IfcFeatureElement can +have the following representation types: 'Brep'. Other +representation types might be specified at the level of +subtypes.

                  +

                  Brep Representation Type

                  +

                  Any IfcFeatureElement (so far no further constraints +are defined at the level of its subtypes) may be represented as a +single or multiple Boundary Representation elements (which are +restricted to faceted Brep with or without voids). The Brep +representation allows for the representation of complex element +shape. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'Brep'
                  • +
                  +

                  In some cases it may be useful to also expose a simple +representation as a bounding box representation of the same +complex shape.

                  +
                  " +647;IfcFeatureElementAddition;" +

                  + Definition from IAI: A specialization of the general + feature element, that represents an existence dependent + element which modifies the shape and appearance of the + associated master element. The + IfcFeatureElementAddition offers the ability to + handle shape modifiers as semantic objects within the IFC + object model that add to the shape of the master element. +

                  +
                  +

                  + HISTORY New entity in + Release IFC2x Edition 2.
                  + NOTE The entity is + introduced as an upward compatible extension of the IFC2x + platform. It is an intermediate abstract supertype + without defining its own explicit + attributes. +

                  +
                  +

                  + The IfcFeatureElementAddition is associated to its + master element by virtue of the objectified relationship + IfcRelProjectsElement. This relationship implies a + Boolean 'union' operation between the shape of the master + element and the shape of the addition feature. +

                  +

                  + Containment use definition +

                  +

                  + The containment to the spatial structure is defined at the + level of the supertype IfcFeatureElement +

                  +

                  + Geometry Use Definitions +

                  +

                  + The geometric representation of + IfcFeatureElementAddition is given by the + IfcProductDefinitionShape, allowing multiple + geometric representations. +

                  +

                  + Local Placement +

                  +

                  + The local placement for IfcFeatureElementAddition is + defined in its supertype IfcProduct. It is defined + by the IfcLocalPlacement, which defines the local + coordinate system that is referenced by all geometric + representations. The local placement is always defined in + relation to the local placement of the element to which the + feature element is added: +

                  +
                    +
                  • The PlacementRelTo relationship of + IfcLocalPlacement shall point to the local placement + of the same IfcElement, which is used in the + HasAdditionFeature.RelatingElement inverse + attribute. +
                  • +
                  +

                  + Shape Representation +

                  +

                  + The geometry use definitions for the shape representation + of the IfcFeatureElementAddition is given at the + level of its subtypes. +

                  +
                  " +650;IfcProjectionElement;" +

                  The projection element is a +specialization of the general feature element to represent +projections applied to building elements. It represents a solid +attached to any element that has physical manifestation.

                  +
                  EXAMPLE A wall projection such as a pilaster +strip is handled by +IfcProjectionElement
                  +
                  NOTE View definitions or implementer agreements +may restrict the types of elements to which +IfcProjectionElement can be applied.
                  +

                  An IfcProjectionElement has to be linked to a element +(all subtypes of IfcElement) by using the +IfcRelProjectsElement relationship. Its existence depends on +the existence of the master element. The relationship implies a +Boolean union operation between the volume of the projection +element and the volume of the element.

                  +
                  HISTORY New entity in IFC2x2.
                  +
                  IFC2x4 CHANGE The attribute PredefinedType has been added at the end of attribute +list.
                  +

                  The quantities relating to the IfcProjectionElement are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following base +quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + +

                  Containment Use Definition

                  +

                  The IfcProjectionElement shall not participate in the +containment relationship, i.e. it is not linked directly to the +spatial structure of the project. It has a mandatory +ProjectsElements inverse relationship pointing to the +IfcElement that is contained in the spatial structure.

                  +
                    +
                  • The inverse relationship ContainedInStructure shall be +NIL.
                  • +
                  +

                  Geometry Use Definition

                  +

                  The geometric representation of IfcProjectionElement is +given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations.

                  +

                  Local Placement

                  +

                  The local placement for IfcOpeningRecess is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement should point to the local placement of the +same element, to which the projection adds, i.e. referred to by +ProjectsElement.RelatingBuildingElement.
                  • +
                  +

                  Swept Solid Representation

                  +

                  The geometric representation of IfcProjectionElement is +defined using the swept area solid geometry. The following +attribute values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SweptSolid'
                  • +
                  +

                  The following additional constraints apply to the swept solid +representation:

                  +
                    +
                  • Solid: IfcExtrudedAreaSolid is required.
                  • +
                  • Profile: IfcRectangleProfileDef, +IfcCircleProfileDef and IfcArbitraryClosedProfileDef +shall be supported.
                  • +
                  • Extrusion: The profile shall be extruded horizontally +(that is, perpendicular to the extrusion direction of the modified +element), such as for wall projections, or vertically (that is, in the +extrusion direction of the projected element), such as for floor +projections.
                  • +
                  + +

                  As shown in Figure 38, the following interpretation of dimension parameter applies for +rectangular projection:

                  +
                    +
                  • IfcRectangleProfileDef.YDim interpreted as projection +width
                  • +
                  • IfcRectangleProfileDef.XDim interpreted as projection +height
                  • +
                  • IfcExtrudedAreaSolid.Depth is interpreted as projection +depth
                  • +
                  +
                  NOTE  Rectangles are now defined centric, the placement location has to be set: +
                  • IfcCartesianPoint(XDim/2,YDim/2)
                  +
                  NOTE  The local placement directions for the IfcProjectionElement are only given as an example, other directions are valid as well.
                  + + + + +

                  Figure 38 — Projection representation

                  + +

                  Brep Representation

                  +

                  The general b-rep geometric representation of +IfcProjectionElement is defined using the Brep geometry. The +Brep representation allows for the representation of complex +element shape. The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'Brep'
                  • +
                  + +
                  " +655;IfcRelProjectsElement;" +

                  The IfcRelProjectsElement is an objectified relationship +between an element and one projection element that creates a +modifier to the shape of the element. The relationship is defined +to be a 1:1 relationship, if an element has more than one +projection, several relationship objects have to be used, each +pointing to a different projection element. The +IfcRelProjectsElement establishes an aggregation +relationship between the main element and a sub ordinary addition +feature.

                  +
                  +

                  NOTE  In contrary the +IfcRelAggregates relationship established an aggregation +of equal parts to a whole.

                  +
                  +

                  The IfcRelProjectsElement implies a Boolean operation of +addition for the geometric bodies of the element and the feature +element. As with all decomposition relationships it determines:

                  +
                    +
                  • existence dependency - the RelatedFeatureElement +cannot exist without the RelatingElement
                  • +
                  • hierarchical and non-cyclical relationship - the +IfcRelProjectsElement can only alter a single +IfcElement
                  • +
                  • no spatial containment - the IfcFeatureElementAddition +as related element never participates in the hiearchical spatial +containment relationship +IfcRelContainedInSpatialStructure
                  • +
                  +
                  +

                  HISTORY New entity in +Release IFC2x Edition 2.
                  +IFC2x4 CHANGE  +Supertype changed to IfcRelDecomposes.

                  +
                  + +
                  " +658;IfcRelVoidsElement;" + +

                  IfcRelVoidsElement is an objectified relationship between a building element and one opening element that creates a void in the element. It is a one-to-one relationship. This relationship implies a Boolean operation of subtraction between the geometric bodies of the element and the opening.

                  + +

                  As shown in Figure 50, the insertion of a void into a wall is represented by the relationship IfcRelVoidsElement. The opening is created within the wall by IfcWall(StandardCase) o-- IfcRelVoidsElement --o IfcOpeningElement.

                  + + + + +

                  Figure 50 — Relationship for element voiding

                  + +
                  HISTORY New entity in IFC Release 1.0
                  + +
                  " +661;IfcFeatureElementSubtraction;" +

                  The IfcFeatureElementSubtraction is specialization of +the general feature element, that represents an existence dependent +elements which modifies the shape and appearance of the associated +master element. The IfcFeatureElementSubtraction offers the +ability to handle shape modifiers as semantic objects within the +IFC object model that subtract from the shape of the master +element.

                  +
                  +

                  A single subtraction feature +such as the subtype IfcOpeningElement is assigned by a +single subtraction relationship IfcRelVoidsElement to one +occurrences of IfcElement. It establishes a 1:1 +relationship between the opening and the element. An element may +have several IfcRelVoidsElement relationships, enabling +several voids.

                  +
                  +

                  The voiding relationship between a master element and a +subtraction feature is geometrically resolved by a Boolean +difference operation.

                  +
                  +

                  HISTORY New entity in +Release IFC2x Edition 2.

                  +
                  +

                  Containment use definition

                  +

                  The IfcFeatureElementSubtraction shall have no +independent containment relationship to the spatial structure. See +explanation at supertype IfcFeatureElement

                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of +IfcFeatureElementSubtraction is given by the +IfcProductDefinitionShape, allowing multiple geometric +representations.

                  +

                  Local Placement

                  +

                  The local placement for IfcFeatureElementSubtraction is +defined in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations. The local +placement is always defined in relation to the local placement of +the building element from which the feature element substration is +substracted:

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcElement, which is used in the +VoidsElements.RelatingElement inverse attribute.
                  • +
                  +

                  Shape Representation

                  +

                  The geometry use definitions for the shape representation of the +IfcFeatureElementSubtraction is given at the level of its +subtypes.

                  + +
                  " +666;IfcOpeningElement;" +

                  The opening element stands for +opening, recess or chase, all reflecting voids. It represents a +void within any element that has physical manifestation. Openings +can be inserted into walls, slabs, beams, columns, or other +elements.

                  +

                  The IFC specification provides two entities for opening +elements:

                  +
                    +
                  • IfcOpeningStandardCase is used for all openings that +have a constant profile along a linear extrusion. They are placed +relative to the voided elements and the extrusion direction is +perpendicular to the plane of the element (horizontally for +walls, vertically for slabs). Only a single extrusion body is +allowed. It cuts through the whole thickness of the voided +element, i.e. it reflects a true opening.
                  • +
                  • IfcOpeningElement is used for all other occurrences of +openings and in particular also for niches or recesses.
                  • +
                  +
                  NOTE View definitions or implementer +agreements may restrict the types of elements which can be voided +by an IfcOpeningElement or +IfcOpeningStandardCase
                  +

                  There are two different types of opening elements:

                  +
                    +
                  • an opening, where the thickness of the opening is greater or +equal to the thickness of the element;
                  • +
                  • a recess or niche, where the thickness of the recess is +smaller than the thickness of the element.
                  • +
                  +

                  The attribute PredefinedType should be used to capture +the differences,

                  +
                    +
                  • the attribute is set to OPENING for an opening or
                  • +
                  • the attribute is set to RECESS for a recess or niche.
                  • +
                  • If the value for PredefinedType is omitted, or the +value is set to NOTDEFINED, no specific information of whether it +is an opening or recess shall be assumed.
                  • +
                  +
                  NOTE Until IFC2x3 the information had been +provided by the inherited attribute +ObjectType.
                  +

                  An IfcOpeningElement has to be inserted into an +IfcElement by using the IfcRelVoidsElement +relationship. The relationship implies a Boolean subtraction +operation between the volume of the voided element and the volume +of the opening. It may be filled by an IfcDoor, +IfcWindow, or another filling element by using the +relationship IfcRelFillsElements.

                  +
                  HISTORY New entity in +IFC Release 1.0
                  +IFC2x CHANGE The intermediate +ABSTRACT supertypes IfcFeatureElement and +IfcFeatureSubtraction have been added.
                  +IFC2x4 CHANGE The attribute +PredefinedType has been added at the end of attribute +list.
                  +

                  Property Set Use Definition:

                  +

                  The property sets relating to the IfcOpeningElement are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcOpeningElement +are part of this IFC release:

                  + +

                  Quantity Use Definition:

                  +

                  The quantities relating to the IfcOpeningElement are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + + +

                  Containment Use Definition

                  +

                  The IfcOpeningElement shall not participate in the +containment relationship, i.e. it is not linked directly to the +spatial structure of the project. It has a mandatory +VoidsElements inverse relationship pointing to the +IfcElement that is contained in the spatial structure.

                  +
                    +
                  • The inverse relationship ContainedInStructure shall be +NIL.
                  • +
                  +
                  NOTE See IfcRelVoidsElement for a +diagram on how to apply spatial containment and the voiding +relationship.
                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcOpeningElement is +given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations.

                  +

                  Local Placement

                  +

                  The local placement for IfcOpeningElement is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement should point to the local placement of +the same element, which is voided by the opening, i.e. referred +to by VoidsElement.RelatingBuildingElement.
                  • +
                  +

                  Geometric Representation

                  +

                  Currently, the 'Body', and 'Box' representations are +supported. The 'Box' representation includes the representation +type 'BoundingBox' and is explained at +IfcFeatureElement.

                  +

                  Body Representation

                  +

                  The 'Body' representation of IfcOpeningElement can be +represented using the representation types 'SweptSolid', and +'Brep'. The representation type 'Brep' is explained at +IfcFeatureElement

                  +

                  Swept Solid Representation Type with Horizontal +Extrusion

                  +

                  The 'SweptSolid' geometric representation of +IfcOpeningElement, using horizontal extrusion direction +(for walls), is defined using the swept area solid geometry. The +following attribute values for the IfcShapeRepresentation +holding this geometric representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SweptSolid'
                  • +
                  +

                  The following additional constraints apply to the swept solid +representation:

                  +
                    +
                  • Solid: IfcExtrudedAreaSolid is required, the +set of IfcShapeRepresentation.Items may include a single, +or multiple, instances of IfcExtrudedAreaSolid.
                  • +
                  • Profile: IfcRectangleProfileDef, +IfcCircleProfileDef and +IfcArbitraryClosedProfileDef shall be supported.
                  • +
                  • Extrusion: The profile shall be extruded horizontally +(i.e. perpendicular to the extrusion direction of the voided +element), e.g. for wall openings, or vertically (i.e. in the +extrusion direction of the voided element), e.g., for floor +openings. If multiple instances of IfcExtrudedAreaSolid +are used, the extrusion direction of each extrusion should be +equal.
                  • +
                  +
                  NOTE In case of non-parallel jambs, the shape +representation shall be a 'SweptSolid' representation with +vertical extrusion.
                  + +

                  Figure 34 illustrates an opening with horizontal extrusion.

                  +
                  NOTE The local placement directions for the IfcOpeningElement are only given as an example, other directions are valid as well.
                  + + + + +

                  Figure 34 — Opening with full extrusion

                  + +

                  Figure 35 illustrates an opening for a recess.

                  +
                  NOTE The local placement directions for the IfcOpeningElement are only given as an example, other directions are valid as well.
                  +
                  NOTE Rectangles are now defined centric, the placement +location has to be set:
                  +
                    +
                  • IfcCartesianPoint(XDim/2,YDim/2)
                  • +
                  + + + + +

                  Figure 35 — Opening with recess extrusion

                  + +

                  Swept Solid Representation with Vertical Extrusion

                  +

                  The 'SweptSolid' geometric representation of +IfcOpeningElement, using vertical extrusion direction (for +walls), is defined using the swept area solid geometry, however +the extrusion direction may be vertical, i.e. in case of a wall +opening, the extrusion would be in the direction of the wall +height. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SweptSolid'
                  • +
                  +

                  The following additional constraints apply to the swept solid +representation:

                  +
                    +
                  • Solid: IfcExtrudedAreaSolid is required, the +set of IfcShapeRepresentation.Items may include a single, +or multiple, instances of IfcExtrudedAreaSolid.
                  • +
                  • Profile: IfcRectangleProfileDef, +IfcCircleProfileDef and +IfcArbitraryClosedProfileDef shall be supported.
                  • +
                  • Extrusion: The profile shall be extruded vertically, +i.e. for wall openings along the extrusion direction of the +voided element.ÿ If multiple instances of +IfcExtrudedAreaSolid are used, the extrusion direction +should be equal.
                  • +
                  +

                  Vertical extrusions shall be used when an opening or recess +has a non rectangular foot print geometry that does not change +along the height of the opening or recess.

                  +

                  Figure 36 shows a vertical extrusion with multiple extrusion bodies for the opening. Each extrusion body has a different extrusion lenght.

                  +
                  NOTE The local placement directions for the IfcOpeningElement are only given as an example, other directions are valid as well.
                  + + + + +

                  Figure 36 — Opening with multiple extrusions

                  +
                  " +670;IfcOpeningStandardCase;" +

                  The standard opening, +IfcOpeningStandardCase, defines an opening with certain +constraints for the dimension parameters, position within the +voided element, and with certain constraints for the geometric +representation. The IfcOpeningStandardCase handles all +cases of openings, that:

                  +
                    +
                  • are true openings by cutting through the body of the voided +element, i.e. where the opening depth is >= to the thickness +of the element,
                  • +
                  • are extruded perpendicular to the wall plane in case of +openings in a wall
                  • +
                  • are extruded perpendicular to the slab plane in case of +openings in a slab
                  • +
                  • have a local placement relative to the local placement of the +voided element
                  • +
                  • have a 'Body' shape representation with 'SweptSolid' +representation type
                  • +
                  • have only a single extrusion body within the 'Body' shape +representation
                  • +
                  +
                  HISTORY New entity in +IFC2x4
                  +

                  Property Set Use Definition:

                  +

                  The property sets relating to the +IfcOpeningStandardCase are defined at the supertype +IfcOpeningElement.

                  +

                  Quantity Use Definition:

                  +

                  The quantities relating to the IfcOpeningStandardCase +are defined at the supertype IfcOpeningElement.

                  +

                  Containment Use Definition

                  +

                  The containment use definitions relating to the +IfcOpeningStandardCase are defined at the supertype +IfcOpeningElement.

                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcOpeningStandardCase +is given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations.

                  +

                  Local Placement

                  +

                  The following constraint is mandatory for +IfcOpeningStandardCase

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement should point to the local placement of +the same element, which is voided by the opening, i.e. referred +to by VoidsElement.RelatingBuildingElement.
                  • +
                  +

                  Geometric Representation

                  +

                  The geometric representation of IfcOpeningStandardCase +is defined using the following multiple shape representations for +its definition:

                  +
                    +
                  • Body: A SweptSolid representation defining the 3D subtraction +shape of the standard opening
                  • +
                  +

                  Body Representation

                  +

                  The body representation of IfcOpeningStandardCase is +represented using the representation type 'SweptSolid'.

                  +

                  Swept Solid Representation Type with Horizontal +Extrusion

                  +

                  The standard geometric representation of +IfcOpeningStandardCase is defined using the 'SweptSolid' +representation. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used::

                  +
                    +
                  • RepresentationIdentifier : 'Body'
                  • +
                  • RepresentationType : 'SweptSolid'
                  • +
                  +

                  The following additional constraints apply to the swept solid +representation:

                  +
                    +
                  • Solid: a single IfcExtrudedAreaSolid is +required
                  • +
                  • Profile: IfcRectangleProfileDef, +IfcCircleProfileDef and +IfcArbitraryClosedProfileDef shall be supported.
                  • +
                  • Extrusion: The profile shall be extruded horizontally +(i.e. perpendicular to the extrusion direction of the voided +element) for wall openings, or vertically (i.e. in the extrusion +direction of the voided element), for slab openings.
                  • +
                  + +

                  As shown in Figure 37, the orientation of the opening profile that is extruded +for the opening body shall guarantee the following interpretation +of dimension parameter for rectangular openings:

                  +
                    +
                  • IfcRectangleProfileDef.YDim interpreted as +opening width
                  • +
                  • IfcRectangleProfileDef.XDim interpreted as +opening height
                  • +
                  + + + + +
                  +""standard

                  Figure 37 — Opening standard representation

                  + +
                  " +676;IfcRelFillsElement;" + +

                  IfcRelFillsElement is an objectified relationship between an opening element and an element that fills (or partially fills) the opening element. It is an one-to-one relationship.

                  + +
                  NOTE view definitions or implementer agreements may restrict an opening to be filled by one filling element only.
                  + +
                  HISTORY New entity in IFC Release 1.0
                  + +

                  As shown in Figure 40, the insertion of a door into a wall is represented by two separate relationships. First the door opening is created within the wall by IfcWall(StandardCase) o-- IfcRelVoidsElement --o IfcOpeningElement, then the door is inserted within the opening by IfcOpeningElement o-- IfcRelFillsElement --o IfcDoor.

                  + + + + +

                  Figure 40 — Relationships for element filling

                  + +
                  " +679;IfcElementAssembly;" +

                  The IfcElementAssembly +represents complex element assemblies aggregated from several +elements, such as discrete elements, building elements, or other +elements.

                  +
                  EXAMPLE Steel construction assemblies, such as +trusses and different kinds of frames, can be represented by the +IfcElementAssembly entity. Other examples include slab +fields aggregated from a number of precast concrete slabs or +reinforcement units made from several reinforcement bars. Also +bathroom units, staircase sections and other premanufactured or +precast elements are examples of the general +IfcElementAssembly entity
                  +
                  NOTE The IfcElementAssembly is a +general purpose entity that is required to be decomposed. Also +other subtypes of IfcElement can be decomposed, with some +dedicated entities such as IfcWallElementedCase and +IfcSlabElementedCase.
                  +

                  The assembly structure can be nested, i.e. an +IfcElementAssembly could be an aggregated part within +another IfcElementAssembly.

                  +
                  NOTE View definitions and/or implementer +agreements may restrict the number of allowed levels of +nesting.
                  +
                  HISTORY New Entity for +Release IFC2x Edition 2.
                  + +

                  Containment Use Definition

                  +

                  The IfcElementAssembly should have (and in most +implementation scenarios it is mandatory) a relationship for its +hierachical containment in the spatial structure of the +project.

                  +
                    +
                  • The IfcElementAssembly is places within the project +spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                  • +
                  +

                  The IfcElementAssembly shall represent an aggregate, +i.e. it should have other elements, being subtypes of +IfcElement, as contained (sub)parts.

                  +
                    +
                  • The IfcElementAssembly is an aggregate i.e. being +composed by other elements and acting as an assembly using the +objectified relationship IfcRelAggregates, refering to it +by its inverse attribute +SELF\IfcObjectDefinition.IsDecomposedBy. Components of an +assembly are described by instances of subtypes of +IfcElement.
                  • +
                  • In this case, the containedÿsubtypes of IfcElement +shall not be additionally contained in the project spatial +hierarchy, i.e. the inverse attribute +SELF\IfcElement.ContainedInStructure of those +IfcElement's shall be NIL.
                  • +
                  + +

                  Figure 27 illustrates spatial containment and element aggregation relationships.

                  + + + +

                  Figure 27 — Element assembly containment

                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcElementAssembly is +given by the IfcProductDefinitionShape, allowing multiple +geometric representations.

                  +

                  Local Placement

                  +

                  The local placement for IfcElementAssembly is defined +in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  The geometry of an IfcElementAssembly is generally +formed from its components, in which case it does not need to +have an explicit geometric representation. In some cases it may +be useful to also expose an own explicit representation of the +aggregate.

                  +
                  NOTEÿ View definitions or implementer +agreements may further constrain the applicability of certain +shape representations at the IfcElementAssembly in respect +of the shape representations of its parts.
                  +

                  Informal proposition

                  +
                    +
                  1. The IfcElementAssembly shall have an aggregation +relationship to the contained parts, i.e. the (INV) +IsDecomposedBy relationship shall be utilzed.
                  2. +
                  +
                  " +688;IfcVirtualElement;" + +

                  A virtual element is a special element used to provide imaginary boundaries, such as between two adjacent, but not separated, spaces. Virtual elements are usually not displayed and does not have quantities and other measures. Therefore IfcVirtualElement does not have material information and quantities attached.

                  + +
                  NOTE The main purpose of IfcVirtualElement is the provision of a virtual space boundary. The IfcVirtualElement may provide the 2D curve or 3D surface representation of the virtual space connection and is referenced by two instances of IfcRelSpaceBoundary, each pointing to one of the two adjacent IfcSpaces.
                  + +
                  HISTORY New entity in IFC Release 2x2 Addendum.
                  +
                  IFC2x2 CHANGE: The entity IfcVirtualElement has been added. Upward compatibility for file based exchange is guaranteed.
                  + +

                  Space Boundary Use Definition

                  +

                  The IfcVirtualElement is mainly used to define a virtual boundary between two spaces. Figure 63 describes how to use IfcRelSpaceBoundary in conjunction with IfcVirtualElement to define space boundaries.

                  + + + + +
                  +""space

                  Figure 63 — Virtual element space boundaries

                  + +

                  Geometry Use Definition

                  +

                  The geometric representation of any IfcVirtualElement +is given by the IfcProductDefinitionShape and +IfcLocalPlacement allowing multiple geometric +representations. Included are:

                  +

                  Local Placement

                  +

                  The local placement for IfcVirtualElement is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representation

                  +

                  Currently, the use of 'FootPrint' and 'Surface' representation +is supported.

                  +

                  FootPrint Representation

                  +

                  The 2D geometric representation of IfcVirtualElement is +defined using the 'FootPrint' representation.

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = 'Curve2D' +or 'GeometricCurveSet' .
                  • +
                  +

                  The following constraints apply to the 2D FootPrint +representation:

                  +
                    +
                  • 'Curve2D': IfcPolyline, IfcTrimmedCurve or +IfcCompositeCurve
                  • +
                  • 'GeometricCurveSet': a list of 2D curves within the +constraints shown above.
                  • +
                  +

                  Surface Representation

                  +

                  The 3D geometric representation of IfcVirtualElement is +defined using a surface geometry.

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Surface'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'Surface3D' or 'GeometricSet .
                  • +
                  +

                  The following constraints apply to the 3D surface +representation:

                  +
                    +
                  • 'Surface3D': IfcSurfaceOfLinearExtrusion, +IfcCurveBoundedPlane, IfcCurveBoundedSurface, +IfcRectangularTrimmedSurface
                  • +
                  • in case of an +IfcSurfaceOfLinearExtrusion +
                      +
                    • Profile: +IfcArbitraryOpenProfileDef
                    • +
                    • Extrusion: The extrusion direction shall be +vertically, i.e., along the positive Z Axis of the co-ordinate +system of the containing spatial structure element.
                    • +
                    +
                  • +
                  • in case of an +IfcCurveBoundedPlane, IfcCurveBoundedSurface, +IfcRectangularTrimmedSurface +
                      +
                    • Extrusion: The BasisSurface shall be a +surface that is upright, i.e. standing perpendicular to the xy +place of the co-ordinate system of the containing spatial +structure element.
                    • +
                    +
                  • +
                  • 'GeometricSet': a list of 3D surfaces within the constraints +shown above.
                  • +
                  +
                  " +689;IfcGeographicElement;" +

                  Definition from IAI: An IfcGeographicElement is +a generalization of all elements within a geographical landscape. +It includes occurrences of typical geographical element, often +referred to as features, such as roads, zones, trees, etc. Common +type information behind several occurrences of +IfcGeographicElement is provided by the +IfcGeographicElementType.ÿ

                  +
                  HISTORY ÿNew entity in +Release IFC2x4.
                  +

                  Type Use Definition

                  +

                  An IfcGeographicElement defines the occuurence of any +element within a geographic landscape, common information about +geographic elements is handled by +IfcGeographicElementType. The +IfcGeographicElementType (if present) may establish the +commonÿtype name, usage (or predefined) type, common set of +properties and common shape representations (using +IfcRepresentationMap). The IfcGeographicElementType +is attached using the IfcRelDefinedByType.RelatingType +objectified relationship and is accessible by the inverse +IsDefinedBy attribute.

                  +

                  Classification Use Definition

                  +

                  An IfcGeographicElement might be further qualified by +referencing a feature catalog as a particular classification. The +feature classification is assigned using the inverse relationship +HasAssociations pointing to +IfcClassificationReference. The attributes should have the +following meaning:

                  +
                    +
                  • Catalog : IfcClassification.Name
                  • +
                  • Identity: +IfcClassificationReference.ItemReference
                  • +
                  • ElementName: IfcClassificationReference.Name
                  • +
                  • if there is a differentiation between an main element and a +sub element without a unique notation facet, then the main +element and sub element(s) can be established by using the +subtype +
                      +
                    • +IfcClassificationReferenceWithFacets.ItemReferenceFacets
                    • +
                    +
                  • +
                  +

                  Containment Use Definition

                  +

                  The IfcGeographicElement, as any subtype of +IfcElement, may participate in two different containment +relationships. The first (and in most implementation scenarios +mandatory) relationship is the hierachical spatial containment, +the second (optional) relationship is the aggregation within +anÿelement assembly.

                  +
                    +
                  • The IfcGeographicElement is places within the project +spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcSite being the default container.
                  • +
                  • The IfcGeographicElement may be aggregated into an +element assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this +case it should not be additionally contained in the project +spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                  • +
                  +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcGeographicElement is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcGeographicElement is defined +in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement , which +is used in the ContainedInStructure inverse attribute, or +to a spatial structure element at a higher level, referenced by +that.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representation

                  +

                  GeometricCurveSet and GeometricSet Representation

                  +

                  The standard representation of IfcGeographicElement is +defined using 'GeometricCurveSet' or, when including surfaces, +the 'GeometricSet' geometry. This also supports a 2D +representation of IfcGeographicElement.ÿ

                  +

                  The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'FootPrint' for 2D +representation
                  • +
                  • RepresentationType :ÿ'GeometricCurveSet' +orÿ'GeometricSet'
                  • +
                  +

                  Annotation2D Representation

                  +

                  Additional annotation objects, like text or hatching, and +style information to the 2D representations, may be exchanged +using the 'Annotation2D' representation. Style information is +assigned to the geometric representation items within the set of +Items at IfcShapeRepresentation using the inverse +StyledByItem relationship.

                  +

                  The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'FootPrint' for 2D +representation
                  • +
                  • RepresentationType :ÿ'Annotation2D'
                  • +
                  +

                  SurfaceModel and Brep Representation

                  +

                  For full 3D representations, the use of 'SurfaceModel' and +'Brep' geometry is supported. This supports a 3D representation, +including support for 3D digital terrain models.

                  +

                  The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'Body' for 3D +representation
                  • +
                  • RepresentationType :ÿ'SurfaceModel' orÿ'Brep'
                  • +
                  +MappedRepresentation Representation
                  +

                  When using the IfcGeographicElement in conjunction with +the IfcGeographicElementType having +RepresentationMaps defined, the geometric representation +ofÿIfcGeographicElementÿshall be based on +'MappedRepresentation', referencing the +IfcRepresentationMap given at the type object.

                  +

                  The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                  +
                    +
                  • RepresentationIdentifier : 'FootPrint' for 2D +representation, 'Body' for 3D representation
                  • +
                  • RepresentationType :ÿ'MappedRepresentation'
                  • +
                  +
                  " +693;IfcRelInterferesElements;" +

                  Definition from IAI: The +IfcRelInterferesElements objectified relationship +indicates that two elements interfere. Interference is a spatial +overlap between the two elements. It is a 1 to 1 relationship. +The concept of two elements interfering physically or logically +is described independently from the elements. The interference +may be related to the shape representation of the entities by +providing an interference geometry.

                  +
                    +
                  • When the interference geometry is available it can be passed +by the optional attribute InterferenceGeometry pointing to +IfcConnectionGeometry. The connection geometry is provided +as a point, curve, surface, or volume within the local placement +coordinate systems of the connecting elements. The +IfcConnectionVolumeGeometry is the default type to be used +for interference in 3D space, as indicated in e.g. clash +detections.
                  • +
                  • If the interference geometry is omitted then the interference +is provided as a logical relationship. Under this circumstance, +the connection point, curve, surface, or solid has to be +recalculated by the receiving application.
                  • +
                  +

                  The RelatingElement and RelatedElement define +the two elements in the relationship, that may have different +roles. This is controlled by the attribute +ImpliedOrder.

                  +
                    +
                  • ImpliedOrder=TRUEÿ The RelatingElement +constitutes the primary element of the interference relationship. +If the interference is to be resolved by subtracting the +overlapping part, it should be subtracted from the +RelatingElement. The net result would be the +RelatingElement subtracted by the +InterferenceGeometry. This would be the case in +interference relationships where the RelatedElement +creates a void in the RelatingElement dynamically.
                  • +
                  • ImpliedOrder=FALSEÿ The RelatingElement and +RelatedElement have no priority among each other. If the +interference is to be resolved then no information about whether +the InterferenceGeometry should be subtracted from the +RelatingElement or thed RelatedElement can be +traced. This would be the case for clash detection results.
                  • +
                  • ImpliedOrder=UNKNOWÿ No information about the +priorities is provided.
                  • +
                  +
                  HISTORYÿ New entity in +IFC2x4.
                  +
                  " +700;IfcRelReferencedInSpatialStructure;" +

                  + The objectified relationship, + IfcRelReferencedInSpatialStructure is used to + assign elements in addition to those levels of the project + spatialÿstructure, in which they are referenced, but not + primarily contained.ÿ +

                  +
                  +

                  + NOTE ÿThe primary containment relationship between + an element and the spatial structure is handled + byÿIfcRelContainsInSpatialStructure. +

                  +
                  +

                  + Any element can be referencedÿto zero, one or several + levels of the spatial structure. Whereas the + IfcRelContainsInSpatialStructure relationship is + required to be hierarchical (an element can only be + contained in exactly one spatial structure element), the + IfcRelReferencedInSpatialStructure is not restricted + to be hierarchical. +

                  +
                  +

                  + EXAMPLE A wall might be normally contained within + a storey, and since it does not span through several + stories, it is not referenced in any additional storey. + However a curtain wall might span through several + stories, in this case it can be contained within the + ground floor, but it would be referenced by all + additional stories, it spans. +

                  +
                  +

                  + Predefined spatial structure elements to which elements can + be assigned are +

                  +
                    +
                  • site as IfcSite +
                  • +
                  • building as IfcBuilding +
                  • +
                  • storey as IfcBuildingStorey +
                  • +
                  • space as IfcSpace +
                  • +
                  +

                  Elements can also be references in a spatial zone that is provided as IfcSpatialZone.

                  +

                  + The same element can be assigned to different spatial + structure elements depending on the context. +

                  +
                  + HISTORY New entity + inÿRelease IFC2x Edition 3. +
                  +

                  Use Definition

                  +

                  Figure 41 shows the use of IfcRelContainedInSpatialStructure and IfcRelReferencedInSpatialStructure to assign an IfcCurtainWallÿto two different levels within the spatial structure. It is primarily contained within the ground floor, and additionally referenced within the first and second floor.

                  + + + + + + + + + + +

                  +

                  Figure 41 — Relationship for spatial structure referencing

                  + +
                  " +704;IfcRelConnectsWithRealizingElements;" +

                  + Definition from IAI: + IfcRelConnectsWithRealizingElements defines a + generic relationship that is made between two elements that + require the realization of that relationship by means of + further realizing elements. +

                  +

                  + An IfcRelConnectsWithRealizingElements is a + specialization of IfcRelConnectsElement where the + connecting operation has the additional attribute of (one + or many) realizing elements that may be used to realize or + further qualify the relationship. It is defined as a + ternary relationship. +

                  +
                  +

                  + EXAMPLE: It may be used to describe the + attachment of one element to another where the attachment + is realized by a 'fixing' element such as a bracket. It + may also be used to describe the mounting of one element + onto another such as the requirement for the mounting + major plant items onto builders work bases and/or + anti-vibration isolators. +

                  +
                  +
                  +

                  + HISTORY: New entity in + Release IFC2x Edition 2. +

                  +
                  +
                  " +707;IfcRelContainedInSpatialStructure;" +

                  + This objectified relationship, + IfcRelContainedInSpatialStructure, is used to assign + elements to a certain level of the spatial project + structure. Any element can only be assigned once to a + certain level of the spatial structure. The question, which + level is relevant for which type of element, can only be + answered within the context of a particular project and + might vary within the various regions. +

                  +
                  +

                  + EXAMPLE A multi-storey space is contained (or + belongs to) the building storey at which its ground level + is, but it is referenced by all the other building + storeys, in which it spans. A lift shaft might be + contained by the basement, but referenced by all storeys, + through which it spans. +

                  +
                  +

                  + The containment relationship of an element within a + spatial structure has to be a hierarchical relationship, an + element can only be contained within a single spatial + structure element. The reference relationship between an + element and the spatial structure may not be hierarchical, + i.e. an element can reference many spatial structure + elements. +

                  +
                  +

                  + NOTE The reference relationship is expressed by + IfcRelReferencedInSpatialStructure. +

                  +
                  +

                  + Predefined spatial structure elements to which elements can + be assigned are +

                  +
                    +
                  • site as IfcSite +
                  • +
                  • building as IfcBuilding +
                  • +
                  • storey as IfcBuildingStorey +
                  • +
                  • space as IfcSpace +
                  • +
                  +

                  + Occurrences of the same element type can be assigned to + different spatial structure elements depending on the + context of the occurrence. +

                  +
                  +

                  + EXAMPLE A wall might be normally assigned + to a storey, however the curtain wall might be assigned + to the building and the retaining wall in the terrain + might be assigned to the site. +

                  +
                  +
                  +

                  + HISTORY New entity in IFC + Release 2x. +

                  +
                  +
                  + IFC2x PLATFORM CHANGE: The + data type of the attribute RelatedElements has been + changed from IfcElement to its supertype + IfcProduct with upward compatibility for file based + exchange. +
                  +

                  Containment Use Definition

                  +

                  Figure 39 shows the use of IfcRelContainedInSpatialStructure to assign a stair and two walls to two different levels within the spatial structure.

                  + + + + + +
                  + ÿ +

                  Figure 39 — Relationship for spatial structure containment

                  +
                  " +711;IfcGrid;" +

                  IfcGrid ia a planar design +grid defined in 3D space used as an aid in locating structural and +design elements. The position of the grid (ObjectPlacement) +is defined by a 3D coordinate system (and thereby the design grid +can be used in plan, section or in any position relative to the +world coordinate system). The position can be relative to the +object placement of other products or grids. The XY plane of the 3D +coordinate system is used to place the grid axes, which are 2D +curves (for example, line, circle, trimmed curve, polyline, or composite +curve).

                  +

                  The inherited attributes Name and Description can +be used to define a descriptive name of the grid and to indicate +the grid's purpose. A grid is defined by (normally) two, or +(in case of a triangular grid) three lists of grid axes. The +following table shows some examples.

                  +

                  A grid may support a rectangular layout (Figure 28), a radial layout (Figure 29), or a triangular layout (Figure 30).

                  + + + + + + + + + + + + + + +

                  Figure 28 — Grid rectangular layout

                  Figure 29 — Grid radial layout

                  Figure 30 — Grid triangular layout

                  + +

                  The grid axes, defined within the design grid, are those +elements to which project objects will be placed relatively using +the IfcGridPlacement.

                  + +
                  HISTORY New entity in IFC Release 1.0.
                  +

                  Informal Proposition

                  +
                    +
                  1. Grid axes, which are referenced in different lists of axes +(UAxes, VAxes, WAxes) shall not be parallel.
                  2. +
                  3. Grid axes should be defined such as there are no two grid axes +which intersect twice (see Figure 31). +
                      +
                    • left side: ambiguous intersections A1 and A2, a grid containing +such grid axes is not a valid design grid.
                    • +
                    • right side: the conflict can be resolved by splitting one grid +axis in a way, such as no ambiguous intersections exist.
                    • +
                    +
                  4. +
                  + + + + + + +

                  Figure 31 — Grid intersections

                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcGrid is given by the +IfcProductDefinitionShape, allowing geometric +representations. Included are:

                  +

                  Local Placement

                  +

                  The local placement for IfcGrid is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to a +spatial structure element at a higher level, referenced by +that.
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Currently, the use of a 2D 'FootPrint' representation of type +'GeometricCurveSet' is supported.

                  +

                  GeometricCurveSet representation

                  +

                  The 2D geometric representation of IfcGrid is defined +using the 'GeometricCurveSet' geometry. The following attribute +values should be inserted

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'.
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet' .
                  • +
                  +

                  The following constraints apply to the 2D representation:

                  +
                    +
                  • The IfcGeometricCurveSet shall be an (and the only) +Item of the IfcShapeRepresentation. It should contain +an IfcGeometricCurveSet containing subtypes of +IfcCurve, each representing a grid axis. Applicable subtypes +of IfcCurve are: IfcPolyline, IfcCircle, +IfcTrimmedCurve (based on BaseCurve referencing +IfcLine or IfcCircle). 
                  • +
                  • Each subtype of IfcCurve may have a curve style +assigned, using IfcAnnotationCurveOccurrence referencing +IfcCurveStyle.
                  • +
                  • Optionally the grid axis labels may be added as +IfcTextLiteral, and they may have text styles assigned, +using IfcAnnotationTextOccurrence referencing +IfcTextStyle.
                  • +
                  + + +

                  As shown in Figure 32, the IfcGrid defines a placement coordinate system using the ObjectPlacement. The XY plane of the coordinate system is used to place the 2D grid axes. The Representation of IfcGrid is defined using IfcProductRepresentation, referencing an IfcShapeRepresentation, that includes IfcGeometricCurveSet as Items. All grid axes are added as IfcPolyline to the IfcGeometricCurveSet.

                  + + + + +

                  Figure 32 — Grid layout

                  + +

                  As shown in Figure 33, the attributes UAxes and VAxes define lists of IfcGridAxis within the context of the grid. Each instance of IfcGridAxis refers to the same instance of IfcCurve (here the subtype IfcPolyline) that is contained within the IfcGeometricCurveSet that represents the IfcGrid.

                  + + + + +

                  Figure 33 — Grid representation

                  + + + + + + +
                  " +717;IfcAnnotation;" +

                  + Definition from IAI: An annotation is a graphical + representation within the geometric (and spatial) context + of a project, that adds a note or meaning to the objects + which constitutes the project model. Annotations include + additional line drawings, text, dimensioning, hatching and + other forms of graphical notes. +

                  +
                  +

                  + NOTE Additional presentation information (often + 2D) such as tag number, hatching, etc., that is directly + related to a particular product representation is + included within the IfcProductDefinitionShape + having various IfcShapeRepresentation's of the + IfcElement (and its subtypes). Only those + presentation information, that cannot be directly related + to a single product, have to be wrapped within the + IfcAnnotation. +

                  +
                  +

                  + If available, the annotation should be related to the + spatial context of the project, by containing the + annotation within the appropriate level of the building + structure (site, building, storey, or space). This is + handled by the IfcRelContainedInSpatialStructure + relationship. +

                  +
                  +

                  + HISTORY: New entity in + Release IFC2x Edition 2. +

                  +
                  +

                  + Use definition +

                  +

                  + The IfcAnnotation can provide specific 0D, 1D, and + 2D geometric items as representation of the annotation, + offering annotation point, curves, and surfaces. +

                  +
                    +
                  • + 'Annotation point' is an annotation provided by a + point that has additional semantic. The inherited + attribute ObjectType should be used to capture the + type of point annotation, some predefined values are: +
                  • +
                  • +
                      +
                    • 'Survey': A survey point has a set of + cartesian coordinates determined by its location at + point. These coordinates are determined relative to the + coordinates of a reference point, which acts as the + datum for the survey. The difference in elevation of + the survey points enables terrain to be determined.
                      + +
                      +
                    • +
                    +
                  • +
                  • + 'Annotation curve' is an annotation provided by a + curve that has additional semantic. The inherited + attribute ObjectType should be used to capture the + type of curve annotation, some predefined values are: +
                  • +
                  • +
                      +
                    • 'ContourLine': A line of constant + elevation typically used on geographic maps where the + spacing of lines at constant intervals of elevation may + be used as an indication of slope. +
                    • +
                    • 'IsoBar': A line of constant pressure + typically used on weather maps or to show pressure + gradient in spaces, chambers or externally. +
                    • +
                    • 'IsoLux': A line of constant illumination + typically used to show the distribution of illumination + levels and/or daylighting in a space or externally. +
                    • +
                    • 'IsoTherm': A line of constant temperature + typically used to show the distribution and effect of + heating or cooling within a space or to show + temperature distribution on a geographic map.
                      +
                      +
                    • +
                    +
                  • +
                  • + 'Annotation surface' is an annotation provided by + a surface that has additional semantic. The inherited + attribute ObjectType should be used to capture the + type of surface annotation, some predefined values are: +
                  • +
                  • +
                      +
                    • 'SurveyArea': A surface patch based on + survey points.
                      +
                      +
                    • +
                    +
                  • +
                  +

                  + Geometry Use Definitions +

                  +

                  + The geometric representation of any IfcAnnotation is + given by the IfcProductDefinitionShape and + IfcLocalPlacement allowing multiple geometric + representations. +

                  +

                  + Local Placement +

                  +

                  + The local placement for any IfcAnnotation is defined + in its supertype IfcProduct. It is defined by the + IfcLocalPlacement, which defines the local + coordinate system that is referenced by all geometric + representations. +

                  +
                    +
                  • The PlacementRelTo relationship of + IfcLocalPlacement shall point (if given) to the + local placement of the same + IfcSpatialStructureElement, which is used in the + ContainedInStructure inverse attribute, or to a + spatial structure element at a higher level, referenced + by that. +
                  • +
                  • If the relative placement is not used, the absolute + placement is defined within the world coordinate system. +
                  • +
                  +

                  + Geometric Representations +

                  +

                  + The standard representation of IfcAnnotation is + defined using 'Annotation2D', when using 2D geometry, + hatching and text, 'GeometricCurveSet' when using points + and curves, or, when including als surfaces, the + 'GeometricSet' geometry. Geometric representation items may + be styled items by adding the style information. +

                  +

                  + Annotation2D Representation
                  + This representation is used, when the representation of the + IfcAnnotation includes specific drafting + representation elements. The Annotation may have: +

                  +
                    +
                  • subtypes of IfcPoint, IfcCurve being 2D +
                  • +
                  • directly as Items, or + within an IfcGeometricCurveSet +
                  • +
                  • subtypes of IfcAnnotationFillArea for hatches +
                  • +
                  • subtypes of IfcDefinedSymbol for symbols +
                  • +
                  • subtypes of IfcTextLiteral for text +
                  • +
                  • subtypes of IfcDraughtingCallout for dimensions +
                  • +
                  The following attribute values for the + IfcShapeRepresentation holding this geometric + representation shall be used: +
                    +
                  • + RepresentationIdentifier : 'Annotation' +
                  • +
                  • + RepresentationType : 'Annotation2D' +
                  • +
                  +

                  + Annotation Curve Representation
                  + This representation is used, when the representation of the + IfcAnnotation does not includes specific drafting + representation elements. The Annotation may have: +

                  +
                    +
                  • subtypes of IfcPoint, IfcCurve being 2D +
                  • +
                  • directly as Items, or + within an IfcGeometricCurveSet +
                  • +
                  The following attribute values for the + IfcShapeRepresentation holding this geometric + representation shall be used: +
                    +
                  • + RepresentationIdentifier : 'Annotation' +
                  • +
                  • + RepresentationType : 'GeometricCurveSet' +
                  • +
                  +

                  + Annotation Surface Representation
                  + This representation is used, when the representation of the + IfcAnnotation does includes surfaces. The Annotation + may have: +

                  +
                    +
                  • subtypes of IfcPoint, IfcCurve, or + IfcSurface +
                  • +
                  • directly as Items, or + within an IfcGeometricCurveSet +
                  • +
                  The following attribute values for the + IfcShapeRepresentation holding this geometric + representation shall be used: +
                    +
                  • + RepresentationIdentifier : 'Annotation' +
                  • +
                  • + RepresentationType : 'GeometricSet' +
                  • +
                  +
                  " +719;IfcSpatialZone;" +

                  Definition from IAI: A spatial element is the +generalization of all spatial elements that might be used to +define a spatial structure or to define spatial zones.

                  +
                    +
                  • a hierarchical spatial structure element as +IfcSpatialStructureElement +
                      +
                    • a spatial structure is a hiearchical decomposition of the +project. That spatial structure is often used to provide a +project structure to organize a building project.
                    • +
                    • a spatial project structure might define as many levels of +decomposition as necessary for the building project. Elements +within the spatial project structure are site, building, storey, +and space
                    • +
                    +
                  • +
                  • a spatial zone as IfcSpatialZone +
                      +
                    • a spatial zone is a non-hierarchical and potentially +overlapping decomposition of the project under some functional +consideration.
                    • +
                    • a spatial zone might be used to represent a thermal zone, a +construction zone, a lighting zone, a usable area zone.
                    • +
                    • a spatial zone might have its independent placement and shape +representation.
                    • +
                    +
                  • +
                  +
                  NOTE The IfcSpatialZone is different to +the IfcZone entity by allowing an own placement and shape +representation, whereas IfcZone is only a grouping of +IfcSpace's.
                  +

                  Attribute Use Definition

                  +

                  The IfcSpatialZone inherits and declares these +attributes that shall have the following meaning:

                  +
                    +
                  • Name: A number or designator provided by the user or +system for the spatial element, e.g. a space number ""1-003"", +could also be a running number provided by default by the +application
                  • +
                  • LongName: Name of the spatial element provided by the +user, e.g. a space name ""Office"".
                  • +
                  • Description: Any additional description provided by +the user, e.g. a space description ""Corner office with habour +view"".
                  • +
                  • ObjectType: reserved for typing of spatial elements in +case of PredefinedType = .USERDEFINED., restrictions on +applicable values might be published in view definitions or +implementer agreements.
                  • +
                  +
                  HISTORY New entity in +IFC Release 2x Edition 4.
                  +
                  " +723;IfcExternalSpatialStructureElement;" +

                  Definition from IAI: The external spatial structure +element is an abstract entity provided for different kind of +external spaces, regions, and volumes.

                  +
                  HISTORY New entity in +IFC2x4.
                  + +
                  " +725;IfcExternalSpatialElement;" +

                  Definition from IAI: The external spatial element +defines external regions at the building site. Those regions can +be defined:

                  +
                    +
                  • logically - e.g. an instance of +IfcExternalSpatialElement could represent the air space +around the building without having an own shape representation, +or
                  • +
                  • physically - e.g. an instance of +IfcExternalSpatialElement could represent the sloping +ground around the building to identify the part of the external +building envelop that is below ground.
                  • +
                  +
                  HISTORY New entity in +IFC2x4.
                  +
                  " +735;IfcRelServicesBuildings;" +

                  + Definition from IAI: An objectified relationship + that defines the relationship between a system and the + sites, buildings, storeys or spaces, it serves. Examples of + systems are: +

                  +
                    +
                  • building service systems (heating, cooling, waste water + system) represented by instances of IfcSystem +
                  • +
                  • idealized structural analysis systems represented by + instances of IfcStructuralAnalysisSystem +
                  • +
                  +
                  +

                  + HISTORY New entity in IFC + Release 1.0 +

                  +
                  +
                  + IFC2x PLATFORM CHANGEÿ The + data type of the attributeRelatedBuildings has been + changed from IfcBuilding to its supertype + IfcSpatialStructureElement with upward compatibility + for file based exchange. The name + IfcRelServicesBuildings is a knownÿanomaly, as the + relationship is not restricted to buildings anymore. +
                  +
                  " +738;IfcBuilding;" +

                  Definition from ISO 6707-1:1989: Construction work that +has the provision of shelter for its occupants or contents as one +of its main purpose and is normally designed to stand permanently +in one place.

                  +

                  A building represents a structure +that provides shelter for its occupants or contents and stands in +one place. The building is also used to provide a basic element +within the spatial structure hierarchy for the components of a +building project (together with site, storey, and space).

                  +

                  A building is (if specified) associated to a site. A building +may span over several connected or disconnected buildings. +Therefore building complex provides for a collection of buildings +included in a site. A building can also be decomposed in +(vertical) parts, where each part defines a building section. +This is defined by the composition type attribute of the +supertype IfcSpatialStructureElements which is interpreted +as follow:

                  +
                    +
                  • COMPLEX = building complex
                  • +
                  • ELEMENT = building
                  • +
                  • PARTIAL = building section
                  • +
                  +
                  HISTORY New entity in IFC Release 1.0.
                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to the IfcBuilding are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcBuilding are +part of this IFC release:

                  +
                    +
                  • Pset_BuildingCommon: common property set for all +types of buildings
                  • +
                  • Pset_BuildingWaterStorage: specific property +set for buildings to capture the water supply requirements
                  • +
                  • Pset_BuildingUse: specific property set for +buildings to capture the current and anticipated real estate +context.
                  • +
                  • Pset_BuildingUseAdjacent: specific property +set for buildings to capture the use information about the +adjacent buildings.
                  • +
                  + +

                  Quantity Use Definition

                  +

                  The quantities relating to the IfcBuilding are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + + +

                  Spatial Structure Use Definition

                  +

                  The IfcBuilding is used to build the spatial structure +of a building (that serves as the primary project breakdown and +is required to be hierarchical). The spatial structure elements +are linked together by using the objectified relationship +IfcRelAggregates. The IfcBuilding references them +by its inverse relationships:

                  +
                    +
                  • IfcBuilding.Decomposes -- referencing (IfcSite +|| IfcBuilding) by IfcRelAggregates.RelatingObject, +If it refers to another instance of IfcBuilding, the +referenced IfcBuilding needs to have a different and +higher CompositionType, i.e. COMPLEX (if the other +IfcBuilding has ELEMENT), or ELEMENT (if the other +IfcBuilding has PARTIAL).
                  • +
                  • IfcBuilding.IsDecomposedBy -- referencing +(IfcBuilding || IfcBuildingStorey) by +IfcRelAggregates.RelatedObjects. If it refers to another +instance ofÿIfcBuilding, the referenced IfcBuilding +needs to have a different and lower CompositionType, i.e. ELEMENT +(if the other IfcBuilding has COMPLEX), or PARTIAL (if the +other IfcBuilding has ELEMENT).
                  • +
                  +

                  If there are building elements and/or other elements directly +related to the IfcBuildingÿ(like a curtain wall spanning +several stories), they are associated with the IfcBuilding +by using the objectified relationship +IfcRelContainedInSpatialStructure. The IfcBuilding +references them by its inverse relationship:

                  +
                    +
                  • IfcBuilding.ContainsElements -- referencing any +subtype of IfcProduct (with the exception of other spatial +structure element) by +IfcRelContainedInSpatialStructure.RelatedElements.
                  • +
                  + +

                  Figure 20 shows the IfcBuilding as part of the spatial +structure. It also serves as the spatial container for building +and other elements.

                  +
                  NOTE Detailed requirements on mandatory element +containment and placement structure relationships are given in +view definitions and implementer agreements.
                  + + + + +
                  +""IfcBuildingStorey

                  Figure 20 — Building composition

                  + + +

                  Systems, such as building service or electrical distribution +systems, zonal systems, or structural analysis systems, relate to +IfcBuilding by using the objectified relationship +IfcRelServicesBuildings.

                  + +

                  Attribute Use Definition

                  + +

                  Figure 21 describes the heights and elevations of the IfcBuilding. It is used to provide the height above sea level of the project height datum for this building, that is, the internal height 0.00. The height 0.00 is often used as a building internal reference height and equal to the floor finish level of the ground floor. +

                    +
                  • base elevation of building provided by: IfcBuilding.ElevationOfRefHeight, it is usually the top of construction slab
                  • +
                  • base elevation of terrain at the perimeter of the building provided by: IfcBuilding.ElevationOfTerrain, it is usually the minimum elevation is sloped terrain
                  • +
                  • total height of building, also referred to as ridge height (top of roof structure, e.g the ridge against terrain): provided by BaseQuantity with Name=""TotalHeight""
                  • +
                  • eaves height of building (base of roof structure, e.g the eaves against terrain): provided by BaseQuantity with Name=""EavesHeight""
                  • +
                  + + + + + + + + + +
                  ÿ

                  Figure 21 — Building elevations

                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcBuilding is given by +the IfcProductDefinitionShape and +IfcLocalPlacement, allowing multiple geometric +representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcBuilding is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if relative placement is +used) to the IfcSpatialStructureElement of type +IfcSite, or of type IfcBuilding (e.g. to position a +building relative to a building complex, or a building section to +a building).
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Currently, the use of a 2D 'FootPrint' representation of type +'GeometricCurveSet' and a 3D 'Body' representation of type 'Brep' +is supported.

                  +

                  Foot Print Representation

                  +

                  The foot print representation of IfcBuilding is given +by either a single 2D curve (such as IfcPolyline or +IfcCompositeCurve), or by a list of 2D curves (in case of +inner boundaries), if the building has an independent geometric +representation.

                  +

                  The representation identifier and type of this geometric +representation of IfcBuilding is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet'
                  • +
                  +

                  Body Representation

                  +

                  The body (or solid model) geometric representation (if the +building has an independent geometric representation) of +IfcBuilding is defined using faceted B-Rep capabilities +(with or without voids), based on the IfcFacetedBrep or on +the IfcFacetedBrepWithVoids.

                  +

                  The representation identifier and type of this representation +of IfcBuilding is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'Brep'
                  • +
                  +

                  Since the building shape is usually described by the exterior +building elements, an independent shape representation shall only +be given, if the building is exposed independently from its +constituting elements.

                  +
                  " +742;IfcBuildingStorey;" +

                  The building storey has an +elevation and typically represents a (nearly) horizontal +aggregation of spaces that are vertically bound.

                  +

                  A storey is (if specified) associated to a building. A storey +may span over several connected storeys. Therefore storey complex +provides for a collection of storeys included in a building. A +storey can also be decomposed in (horizontical) parts, where each +part defines a partial storey. This is defihned by the composition +type attribute of the supertype +IfcSpatialStructureElements which is interpreted as +follow:

                  +
                    +
                  • COMPLEX = building storey complex
                  • +
                  • ELEMENT = building storey
                  • +
                  • PARTIAL = partial building storey
                  • +
                  +
                  EXAMPLE In split level houses, a storey is split into two or more partial storeys, each with a different elevation. It can be handled by defining a storey, which includes two or more partial storeys with the individual elevations.
                  +
                  HISTORY New entity in IFC Release 1.0
                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to the IfcBuildingStorey are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcBuildingStorey +are part of this IFC release:

                  + +

                  Quantity Use Definition

                  +

                  The quantities relating to the IfcBuildingStorey are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + + +

                  Spatial Structure Use Definition

                  +

                  The IfcBuildingStorey is used to build the spatial +structure of a building (that serves as the primary project +breakdown and is required to be hierarchical). The spatial +structure elements are linked together by using the objectified +relationship IfcRelAggregates. The +IfcBuildingStoreyreferences them by its inverse +relationships:

                  +
                    +
                  • IfcBuildingStorey.Decomposes -- referencing +(IfcBuilding || IfcBuildingStorey) by +IfcRelAggregates.RelatingObject, If it refers to another +instance ofÿIfcBuildingStorey, the referenced +IfcBuildingStorey needs to have a different and higher +CompositionType, i.e. COMPLEX (if the other +IfcBuildingStorey has ELEMENT), or ELEMENT (if the other +IfcBuildingStorey has PARTIAL).
                  • +
                  • IfcBuildingStorey.IsDecomposedBy -- referencing +(IfcBuildingStorey || IfcSpace) by +IfcRelAggregates.RelatedObjects. If it refers to another +instance ofÿIfcBuildingStorey, the referenced +IfcBuildingStorey needs to have a different and lower +CompositionType, i.e. ELEMENT (if the other +IfcBuildingStorey has COMPLEX), or PARTIAL (if the other +IfcBuildingStorey has ELEMENT).
                  • +
                  +

                  If there are building elements and/or other elements directly +related to the IfcBuildingStorey (like most building +elements, such as walls, columns, etc.), they are associated with +the IfcBuildingStorey by using the objectified +relationship IfcRelContainedInSpatialStructure. The +IfcBuildingStorey references them by its inverse +relationship:

                  +
                    +
                  • IfcBuildingStorey.ContainsElements -- referencing any +subtype of IfcProduct (with the exception of other spatial +structure element) by +IfcRelContainedInSpatialStructure.RelatedElements.
                  • +
                  + +

                  Figure 25 shows the IfcBuildingStorey as part of the +spatial structure. It also serves as the spatial container for +building and other elements.

                  +
                  NOTE Detailed requirements on mandatory element +containment and placement structure relationships are given in +view definitions and implementer agreements.
                  + + + + +
                  +""IfcBuildingStorey

                  Figure 25 — Building storey composition

                  + +

                  Elements can also be referenced in an +IfcBuildingStorey, for example, if they span through several +storeys. This is expressed by using the objectified relationship +IfcRelReferencedInSpatialStructure. Systems, such as +building service or electrical distribution systems, zonal +systems, or structural analysis systems, relate to +IfcBuildingStorey by using the objectified relationship +IfcRelServicesBuildings.

                  + +

                  Attribute Use Definition

                  + +

                  Figure 26 describes the heights and elevations of the IfcBuildingStorey. +

                    +
                  • elevation of storey provided by: IfcBuildingStorey.Elevation as a local height value +relative to IfcBuilding.ElevationOfRefHeight, it is usually the top of construction slab
                  • +
                  • net height of storey, also referred to as total height or system height (top of construction slab to top of construction slab above): provided by BaseQuantity with Name=""GrossHeight""
                  • +
                  • net height of storey (top of construction slab to bottom of construction slab above): provided by BaseQuantity with Name=""NetHeight""
                  • +
                  + + + + + + + + +

                  Figure 26 — Building storey elevations

                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcBuildingStorey is +given by the IfcProductDefinitionShape and +IfcLocalPlacement, allowing multiple geometric +representation.

                  +

                  Local Placement

                  +

                  The local placement for IfcBuildingStorey is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if relative placement is +used) to the IfcSpatialStructureElement of type +IfcBuilding, or of type IfcBuildingStorey (e.g. to +position a building storey relative to a building storey complex, +or a partial building storey to a building storey).
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                  • +
                  +

                  Geometric Representations

                  +

                  Currently, the use of a 2D 'FootPrint' representation of type +'GeometricCurveSet' and a 3D 'Body' representation of type 'Brep' +is supported.

                  +
                  +

                  NOTE The independent geometric representation of +IfcBuildingStorey may not be required or allowed in +certain view definitions. In those cases only the contained +elements and spaces have an independent geometric +representation.

                  +
                  +

                  Foot Print Representation

                  +

                  The foot print representation of IfcBuildingStorey is +given by either a single 2D curve (such as IfcPolyline or +IfcCompositeCurve), or by a list of 2D curves (in case of +inner boundaries), if the building storey has an independent +geometric representation.

                  +

                  The representation identifier and type of this geometric +representation of IfcBuildingStorey is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet'
                  • +
                  +

                  Body Representation

                  +

                  The body (or solid model) geometric representation (if the +building storey has an independent geometric representation) of +IfcBuildingStorey is defined using faceted B-Rep +capabilities (with or without voids), based on the +IfcFacetedBrep or on the +IfcFacetedBrepWithVoids.

                  +

                  The representation identifier and type of this representation +of IfcBuildingStorey is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'Brep'
                  • +
                  +

                  Since the building storey shape is usually described by the +exterior building elements, an independent shape representation +shall only be given, if the building storey is exposed +independently from its constituting elements.

                  + +
                  " +744;IfcSite;" +

                  Definition from ISO 6707-1:1989: Area where construction +works are undertaken.

                  +

                  A site is a defined area of land, possibly +covered with water, on which the project construction is to be +completed. A site may be used to erect building(s) or other AEC +products.

                  +

                  A site (IfcSite) may include a definition of the single +geographic reference point for this site (global position using +WGS84 with Longitude, Latitude and Elevation). +The precision is provided up to millionth of a second and it +provides an absolute placement in relation to the real world as +used in exchange with geospational information systems. If +asserted, the Longitude, Latitude and +Elevation establish the point in WGS84 where the point +0.,0.,0. of the LocalPlacement of IfcSite is +situated.

                  +

                  The geometrical placement of the site, defined by the +IfcLocalPlacement, shall be always relative to the spatial +structure element, in which this site is included, or absolute, +i.e. to the world coordinate system, as established by the +geometric representation context of the project. The world +coordinate system, established at the +IfcProject.RepresentationContexts, may include a definition +of the true north within the XY plane of the world coordinate +system, if provided, it can be obtained at +IfcGeometricRepresentationContext.TrueNorth.

                  +

                  A project may span over several connected or disconnected sites. +Therefore site complex provides for a collection of sites included +in a project. A site can also be decomposed in parts, where each +part defines a site section. This is defined by the composition +type attribute of the supertype IfcSpatialStructureElements +which is interpreted as follow:

                  +
                    +
                  • COMPLEX = site complex
                  • +
                  • ELEMENT = site
                  • +
                  • PARTIAL = site section
                  • +
                  +
                  HISTORY  New entity in IFC Release 1.0.
                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to the IfcSite are defined by +the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcSite are part of this IFC +release:

                  + + +

                  Quantity Use Definition

                  +

                  The quantities relating to the IfcSite are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following base +quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities, being subjected to local standard of measurement, can +be defined with another string value assigned to Name. In +this case a valid value for MethodOfMeasurement has to be +provided.

                  + + +

                  Spatial Structure Use Definition

                  +

                  The IfcSite is used to build the spatial structure of a +building (that serves as the primary project breakdown and is +required to be hierarchical). The spatial structure elements are +linked together by using the objectified relationship +IfcRelAggregates. The IfcSite references them by its +inverse relationships:

                  +
                    +
                  • IfcSite.Decomposes -- referencing (IfcProject || +IfcSite) by IfcRelAggregates.RelatingObject, If it +refers to another instance of IfcSite, the referenced +IfcSite needs to have a different and higher +CompositionType, i.e. COMPLEX (if the other IfcSite +has ELEMENT), or ELEMENT (if the other IfcSite has +PARTIAL).
                  • +
                  • IfcSite.IsDecomposedBy -- referencing (IfcSite || +IfcBuilding || IfcSpace) by +IfcRelAggregates.RelatedObjects. If it refers to another +instance of IfcSite, the referenced IfcSite needs to +have a different and lower CompositionType, i.e. ELEMENT (if the +other IfcSite has COMPLEX), or PARTIAL (if the other +IfcSite has ELEMENT).
                  • +
                  +

                  If there are building elements and/or other elements directly +related to the IfcSite (like a fence, or a shear wall), they +are associated with the IfcSite by using the objectified +relationship IfcRelContainedInSpatialStructure. The +IfcIfcSite references them by its inverse relationship:

                  +
                    +
                  • IfcSite.ContainsElements -- referencing any subtype of +IfcProduct (with the exception of other spatial structure +element) by +IfcRelContainedInSpatialStructure.RelatedElements.
                  • +
                  + +

                  Figure 51 shows the IfcSite as part of the spatial structure. In addition to the logical spatial structure, also the placement hierarchy is shown. In this example the spatial structure hierarchy and the placement hierarchy are identical.

                  +
                  NOTE Detailed requirements on mandatory element containment and placement structure relationships are given in view definitions and implementer agreements.
                  + + + + +

                  Figure 51 — Site composition

                  + +

                  Attribute Use Definition

                  +

                  Figure 52 describes the heights and elevations of the IfcSite. It is used to provide the geographic longitude, latitude, and height above sea level for the origin of the site. The origin of the site is the local placement.

                  +

                  The provision of longitude, latitude, height at the IfcSite for georeferencing is provided for upward compatibility reasons. It requires a single instance of IfcSite and WGS84 as coordinate reference system.

                  +

                  For exact georeferencing the new entities IfcCoordinateReferenceSystem and IfcMapConversion should be used.

                  +
                    +
                  • reference height of site is provided by: IfcSite.RefElevation, it is given according to the height datum used at this location.
                  • +
                  • the reference height of each building situated at the site is given againt the same height datum used at this location.
                  • +
                  • the elevations of each storey belonging to each building are given as local height relative to the reference height of the building.
                  • +
                  + + + + + + +
                   

                  Figure 52 — Site elevations

                  + +

                  Geometry Use Definitions

                  +

                  The geometric representation of IfcSite is given by the +IfcProductDefinitionShape and IfcLocalPlacement +allowing multiple geometric representations.

                  +

                  Local placement

                  +

                  The local placement for IfcSite is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                  +
                    +
                  • The PlacementRelTo relationship of +IfcLocalPlacement shall point to the +IfcSpatialStructureElement of type ""IfcSite"", if +relative placement is used (e.g. to position a site relative a a +site complex, or a site section to a site).
                  • +
                  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system. If there is only one +site object, then this is the default situation.
                  • +
                  +

                  Foot Print Representation

                  +

                  The foot print representation of IfcSite is given by +either a single 2D curve (such as IfcPolyline or +IfcCompositeCurve), or by a list of 2D curves (in case of +inner boundaries).

                  +

                  The representation identifier and type of this geometric +representation of IfcSite is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'FootPrint'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet', or 'Annotation2D'
                  • +
                  +

                  Survey Points Representation

                  +

                  The survey point representation of IfcSite is defined +using a set of survey points and optionally breaklines. The +breaklines are restricted to only connect points given in the set +of survey points. Breaklines, if given, are used to constrain the +triangulation.

                  +

                  The representation identifier and type of this geometric +representation of IfcSite is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'SurveyPoints'
                  • +
                  • IfcShapeRepresentation.RepresentationType = +'GeometricCurveSet'
                  • +
                  + +

                  Figure 53 shows a set of survey points, given as 3D Cartesian points within the object coordinate system of the site. Figure 54 shows the result after facetation.

                  +

                  The set of IfcCartesianPoint is included in the set of IfcGeometricCurveSet.Elements.

                  + + + + + + + + + + +

                  Figure 53 — Site survey points

                  Figure 54 — Site survey points facetation

                  + +

                  Figure 55 shows A set of survey points, given as 3D Cartesian points, and a set of break points, given as a set of lines, connecting some survey points, within the object coordinate system of the site. Figure 56 shows the result after facetation.

                  +

                  The set of IfcCartesianPoint and the set of IfcPolyline are included in the set of IfcGeometricCurveSet.Elements.

                  + + + + + + + + + + +

                  Figure 55 — Site breaklines

                  Figure 56 — Site breaklines facetation

                  + +
                  NOTE  The geometric representation of the site has been based on the ARM level description of the site_shape_representation given within the ISO 10303-225 ""Building Elements using explicit shape representation"".
                  + +

                  Body Representation

                  +

                  The body representation of IfcSite is defined using a +solid or surface model. Applicable solids are the +IfcFacetedBrep or on the IfcFacetedBrepWithVoids, +applicable surface models are the IfcFaceBasedSurfaceModel +and the IfcShellBasedSurfaceModel.

                  +

                  The representation identifier and type of this representation of +IfcSite is:

                  +
                    +
                  • IfcShapeRepresentation.RepresentationIdentifier = +'Body'
                  • +
                  • IfcShapeRepresentation.RepresentationType = 'Brep', or +'SurfaceModel'
                  • +
                  +
                  " +765;IfcElementQuantity;" +

                  Definition from IAI: An IfcElementQuantity +defines a set of derived measures of an element's physical +property. Elements could be spatial structure elements (like +buildings, storeys, or spaces) or building elements (like walls, +slabs, finishes). The IfcElementQuantity gets assigned to +the element by using the IfcRelDefinesByProperties +relationship.

                  +

                  The optional MethodOfMeasurement attribute defines the +code, e.g. from a standard method of measurement, which had been +used to calculate the element quantity.

                  +
                  +

                  NOTE The recognizable values for the name and the +method of measurement attributes have to be agreed upon in +further agreement documents, such as implementers agreements. +Some of these agreements might be limited to a certain region, to +which the method of measurement applies.

                  +
                  +

                  The name attribute, given at the individual Quantities +provides a recognizable semantic meaning of the element quantity. +Both information is needed to establish a precise meaning for the +measure value. An optional description may be assigned to each of +the Quantities. All quantities assigned by a single +instance of IfcElementQuantity are deemed to have been +generated according to the same method of measurement. However +several instances of IfcElementQuantity are assignable to +an element, thus allowing for an element having quantities +generated according to several methods of measurement.

                  +
                  +

                  EXAMPLE1 To exchange the net floor area of spaces in +the German region (as IfcSpace), the name might be +'Netto-Grundfläche' (net floor area), and the method of +measurement might be accordingly 'DIN277-2' (German industry norm +no. 277 edition 2)

                  +
                  +
                  +

                  EXAMPLE2 The same instance of IfcSpace may have +a different area measure assigned in the German region according +to a housing regulation, the name would be 'Wohnfläche' and +the method of measurement would be '2.BV'. It would be attached +to the IfcSpace by a separate +IfcRelDefinesByProperties relationship.

                  +
                  +

                  The IfcElementQuantity can have the following subtypes +of IfcPhysicalQuantity within its SET of +Quantities, which count for the basis measure types +used:

                  +
                    +
                  • count measure
                  • +
                  • weight measure
                  • +
                  • length measure
                  • +
                  • area measure
                  • +
                  • volume measure
                  • +
                  • time measure
                  • +
                  +
                  +

                  HISTORY New entity in IFC Release +2x. NOTE: It replaces the calcXxx attributes used in previous IFC +Releases.
                  +IFC2x4 CHANGE Subtyped from new +intermediate IfcPreDefinedPropertySet +supertype.

                  +
                  +

                  Quantity Use Defintion

                  +

                  Base quantities are quantity definitions that are independent +of a particular method of measurement and therefore +internationally applicable. Base quantities are defined as gross +and net values and provided by measurement of the correct +geometric shape representation of the element. The IFC +specification includes a set of base quantity definition. See +each subtype of IfcElement for applicable base +quantities.

                  +

                  The following general agreements apply for each base quantity +set

                  +
                    +
                  • IfcElementQuantity.Name = 'BaseQuantities'
                  • +
                  • IfcElementQuantity.MethodOfMeasurement = NIL
                  • +
                  • IfcElementQuantity.Quantities = SET of subtypes of +IfcPhysicalSimpleQuantity with values for the Name +attribute as published as part of the IFC specifciation.
                  • +
                  +
                  " +770;IfcRelAssociatesMaterial;" +

                  Definition from IAI: Objectified relationship between a +material definition and elements or element types to which this +material definition applies.

                  +

                  The material definition can be:

                  +
                    +
                  • assigned to an element occurrence as a specific usage of a +layer set or profile set
                  • +
                  • assigned to an element occurrence or element type as a layer +set, profile set, constituent set or a single material
                  • +
                  +

                  Materials can be arranged by layers and applied to layered +elements. Typical elements are walls and slabs.

                  +
                    +
                  • An IfcMaterialLayerSet, for layered elements with an +indication of the layering direction and individual layer +thicknesses
                  • +
                  • An IfcMaterialLayerSetUsage, i.e. a material layer set +with positioning information along the reference axis or surface +of the element. +
                    NOTE As a material layer set usage is an +occurrence based information, that applies to each individual +element, it cannot be assigned to an element +type.
                    +
                  • +
                  +

                  Material can be applied to profiles. Typical elements using +profile material are beam, column, member

                  +
                    +
                  • An IfcMaterialProfileSet, i.e. a set of material +assigned to a set of profiles, with a single material assigned to +a single profile as the default.
                  • +
                  • An IfcMaterialProfileSetUsage, i.e. a material profile +set with positioning information relative to the element axis, +also refered to as cardinal point. +
                    NOTE As a material profile set usage is an +occurrence based information, that applies to each individual +element, it cannot be assigned to an element +type.
                    +
                  • +
                  +

                  Materials can be arranged by identified parts of a component +based element. Typical elements are dorrs/windows (with +components such as lining, framing and glazing), or distribution +elements.

                  +
                    +
                  • An IfcMaterialConstituentSet, for component based +elements with an indication of the component by keyword to which +the material consituent applies. +
                    NOTE See the material use definitions at each +applicable subtype of IfcElement or IfcElementType +for a provision of these keywords.
                    +
                  • +
                  +

                  As a fallback, or in cases where only a single material +information is needed, material information can be directly +associated

                  +
                    +
                  • A single IfcMaterial for any element where the +material use definition does not prohibits its direct +association
                  • +
                  • An IfcMaterialList, e.g. for composite elements, +without an information, how the different materials are arranged. +
                    NOTE The use of +IfcMaterialList is deprecated in IFC2x4 onwards. Use +IfcMaterialConstituentSet +instead.
                    +
                  • +
                  +

                  The IfcRelAssociatesMaterial relationship is a special +type of the IfcRelAssociates relationship. It can be +applied to subtypes of IfcElement and subtypes of +IfcElementType.

                  +
                    +
                  • The IfcElement has an inverse relation to its material +definition by the HasAssociations attribute, inherited +from IfcObject.
                  • +
                  • The IfcElementType has an inverse relation to its +material definition by the HasAssociations attribute, +inherited from IfcPropertyDefinition.
                  • +
                  +

                  If both, the element occurrence (by an instance of +IfcElement) and the element type (by an instance of +IfcElementType, connected through +IfcRelDefinesByType) have an associated material, then the +material associated to the element occurrence overrides the +material associated to the element type.

                  +
                  +

                  HISTORY New entity in IFC Release +2.x.

                  +
                  +

                  Informal proposition

                  +
                    +
                  1. An IfcMaterialLayerSetUsage shall not be associated +with a subtype of IfcElementType, it should only be +associated with individual occurrences
                  2. +
                  3. An IfcMaterialProfileSetUsage shall not be associated +with a subtype of IfcElementType, it should only be +associated with individual occurrences
                  4. +
                  + +
                  " +776;IfcProduct;" + +

                  Any object that relates to a +geometric or spatial context. Subtypes of IfcProduct +usually hold a shape representation and a object placement within +the project structure.

                  +

                  This includes manufactured, supplied or created objects +(referred to as elements) for incorporation into an AEC/FM +project. This also includes objects that are created indirectly +by other products, as spaces are defined by bounding elements. +Products can be designated for permanent use or temporary use, an +example for the latter is formwork. Products are defined by their +properties and representations.

                  +

                  In addition to physical products (covered by the subtype +IfcElement) and spatial items (covered by the subtype +IfcSpatialElement) the IfcProduct also includes +non-physical items, that relate to a geometric or spatial +contexts, such as grid, port, annotation, structural actions, +etc.

                  +

                  The inherited ObjectType attribute can be used to +designate a particular type of the product instance. If subtypes +of IfcProduct have a PredefinedType defined, the +ObjectType is used to provide the user defined, particular +type of the product instance, if the PredefinedType is set +to USERDEFINED.

                  + +
                  +HISTORY New Entity in IFC Release 1.0 +
                  + +

                  Relationship use definition

                  +

                  On a generic level products can be assigned to processes, +controls, resources, project by using the relationship objects +that refer to the corresponding object:

                  +
                    +
                  • Having a control applied: assigned using +IfcRelAssignsToControl linking the IfcProduct to an +IfcControl +
                      +
                    • An example of this +relationship is the assignment of a performance history to a +distribution element.
                    • +
                    +
                  • +
                  • Being assigned to a process: assigned using +IfcRelAssignsToProcess linking the IfcProduct to an +IfcProcess +
                      +
                    • An example of this +relationship is the assignment of products like wall, slab, +column to a contruction task for construction +planning.
                    • +
                    +
                  • +
                  • Being assigned to a resource: assigned using +IfcRelAssignsToResource linking the IfcProduct to +an IfcResource +
                      +
                    • An example of this +relationship is the assignment of products to a construction +resource that consumes the product.
                    • +
                    +
                  • +
                  +

                  Type use definition

                  +

                  Any instance of IfcProduct defines a particular +occurrence of a product, the common type information, that +relates to many similar (or identical) occurrences of +IfcProduct, is handled by the IfcTypeProduct (and +its subtypes), assigned to one or many occurrences of +IfcProduct by using the objectified relationship +IfcRelDefinesByType. The IfcTypeProduct may +provide, in addition to common properties, also a common +geometric representation for all occurrences.

                  +
                  See IfcTypeProduct for how to use a +common geometric representation and IfcRelDefinesByType +for using and overriding common properties.
                  + +

                  Representation use definition

                  +

                  An IfcProduct occurs at a specific location in space if +it has a geometric representation assigned. It can be placed +relatively to other products, but ultimately relative to the +world coordinate system defined for this project. The +ObjectPlacement attribute establishes the coordinate +system in which all points and directions used by the geometric +representation items under Representation are +founded. The placement can either be:

                  +
                    +
                  • a relative placement: by IfcLocalPlacement with +PlacementRelTo pointing to a parent placement
                  • +
                  • an absolute placement: by IfcLocalPlacement +with PlacementRelTo being NIL
                  • +
                  • a placement relative to a grid: by +IfcGridPlacement
                  • +
                  +

                  The Representation is provided by an +IfcProductDefinitionShape being either a geometric shape +representation, or a topology representation (with or without +underlying geometry of the topological items).

                  + +
                  " +782;IfcObject;" + +

                  An IfcObject is the +generalization of any semantically treated thing or process. +Objects are things as they appear - i.e. occurrences.

                  +
                  NOTE Examples of IfcObject include +physically tangible items, such as wall, beam or covering, +physically existing items, such as spaces, or conceptual items, +such as grids or virtual boundaries. It also stands for +processes, such as work tasks, for controls, such as cost items, +for actors, such as persons involved in the design process, +etc.
                  +

                  Objects can be named, using the inherited Name +attribute, which should be a user recognizable label for the +object occurrance. Further explanations to the object can be +given using the inherited Description attribute. The +ObjectType attribute is used:

                  +
                    +
                  • to store the user defined value for all subtypes of +IfcObject, where a PredefinedType attribute is +given, and its value is set to USERDEFINED.
                  • +
                  • to provide a type information (could be seen as a very +lightweight classifier) of the subtype of IfcObject, if no +PredefinedType attribute is given. This is often the case, +if no comprehensive list of predefined types is available.
                  • +
                  +

                  Objects are independent pieces of information that might +contain or reference other pieces of information. There are +several relationships in which objects can be involved:

                  +
                    +
                  • Association to external/internal resource information +- an association relationship that refers to external/internal +sources of information. See supertype IfcObjectDefinition +for more information.
                  • +
                  • Assignment of other objects - an assignment +relationship that refers to other types of objects. See supertype +IfcObjectDefinition for more information.
                  • +
                  • Aggregation of other objects - an aggregation +relationship that establishes a whole/part relation. Objects can +either be a whole, or a part, or both. See supertype +IfcObjectDefinition for more information.
                    +
                  • +
                  • Assignment of a type : IsTypedBy - a definition +relationship IfcRelDefinesByType that uses a type +definition to define the common characteristics of this +occurrences, potentially including the common shape +representation and common properties of all object occurrences +assigned to this type. It is a specific - occurrence relationship +with implied dependencies (as the occurrence properties depend on +the properties of the type, but may override them).
                  • +
                  • +
                    NOTE See IfcRelDefinesByType for an +explanatory figure. Also see for how to override type properties +by occurrence properties
                    +
                  • +
                  • Assignment of a partial type : IsDeclaredBy, +Declares - a definition relationship +IfcRelDefinesByObject that uses a component of a type +definition (a part of a type, called the ""declaring part"") to +define a component of an occurence (part of occurrence, called +the ""reflected part""). This is also refered to as a ""deep copy"". +The common characteristics of all parts in the occurrence are +defined by parts in the type. It is a specific - occurrence +relationship with implied dependencies (as the occurrence +properties depend on the properties of the type, but may override +them).
                  • +
                  • +
                    NOTE See IfcRelDefinesByObject for an +explanatory figure.
                    +
                  • +
                  • Assignment of property sets : IsDefinedBy - a +definition relationship IfcRelDefinesByProperties that +assignes property set definitions to the object occurrence.
                  • +
                  + +
                  +HISTORY New Entity in IFC Release 1.0 +
                  + +
                  +IFC2x4 CHANGE The inverse relationships Declares, IsDeclaredBy, and IsTypedBy have been added, types are not longer included in the IsDefinesBy relationship. IfcProject has been promoted to be a subtype of IfcObjectDefinition -> IfcContext. +
                  + +

                  Informal Proposition

                  +
                    +
                  1. A partial type assignment, i.e. the inverse attribute +IsDeclaredBy, or Declares shall only be used, if +the object is part of a decomposition, i.e. if either +IsDecomposedBy, or Decomposes is exerted.
                  2. +
                  + +
                  " +794;IfcObjectDefinition;" + +

                  An IfcObjectDefinition is the generalization of any +semantically treated thing or process, either being a type or an +occurrences. Object defintions can be named, using the inherited +Name attribute, which should be a user recognizable label +for the object occurrance. Further explanations to the object can +be given using the inherited Description attribute. A +context is a specific kind of object definition as it provides the +project or library context in which object types and object +occurrences are defined.

                  +

                  Objects are independent pieces of information that might contain +or reference other pieces of information. There are four essential +kinds of relationships in which object definitons (by their +instantiable subtypes) can be involved:

                  +
                    +
                  • Assignment of other objects - an assignment relationship +(IfcRelAssigns) that refers to other types of objects and +creates a bi-directional association. The semantic of the +assignment is established at the level of the subtypes of the +general IfcRelAssigns relationship. There is no dependency +implied a priori by the assignment.
                  • +
                  • Association to external resources - an association +relationship (IfcRelAssociates) that refers to external +sources of information (most notably a classification or document) +and creates a uni-directional association. There is no dependency +implied by the association.
                  • +
                  • Aggregation of other objects - an aggregation +relationship (IfcRelAggregates) that establishes an +unordered, spatial whole/part relation and creates a bi-directional +relation. There is an implied dependency established.
                  • +
                  • Nesting of other objects - a nesting relationship +(IfcRelNests) that establishes an ordered, non-spatial +whole/part relation and creates a bi-directional relation. There is +an implied dependency established.
                  • +
                  • Declaration within a context - a relationship +(IfcRelDeclares) of the uppermost object definition within +the object definition tree (e.g. the summary object within an +object nesting tree) to the context (a project or project library). +It applies the units, representation context and other context +information to this object definition and all dependent ones. +
                      +
                    • EXCEPTION  The link +between the uppermost object in the spatial structure tree, that is +IfcSite or ifcBuilding, and the context provided +by IfcProject is created using the +IfcRelAggregates relationship. See IfcProject for +more information.
                    • +
                    +
                  • +
                  + +
                  +HISTORY New abstract entity in IFC2x3. +
                  + +
                  +IFC2x4 CHANGE The new subtype IfcContext and the relationship to context HasContext has been added . The decomposition relationship is split into ordered nesting (Nests, IsNestedBy) and un-ordered aggregating (Decomposes, IsDecomposedBy). +
                  + +
                  " +805;IfcRoot;" + +

                  IfcRoot is the most abstract and root class for all IFC entity definitions that roots in the kernel or in subsequent layers of the IFC object model. It is therefore the common supertype of all IFC entities, beside those defined in an IFC resource schema. All entities that are subtypes of IfcRoot can be used independently, whereas resource schema entities, that are not subtypes of IfcRoot, are not supposed to be independent entities.

                  + +

                  IfcRoot assigns the globally unique ID, and the ownership and history information to the entity. In addition it may provide for a name and a description about the concept.

                  + +
                  +NOTE View definitions and implementation agreement may impose additional restrictions on the use of the OwnerHistory to handle object versioning. +
                  + +
                  +HISTORY New entity in IFC Release 1.0 +
                  + +
                  +IFC2x4 CHANGE The attribute OwnerHistory has been made OPTIONAL. +
                  + +
                  " +815;IfcPropertyDefinition;" + +

                  IfcPropertyDefinition defines the generalization of +all characteristics (i.e. a grouping of individual properties), +that may be assigned to objects. Currently, subtypes of +IfcPropertyDefinition include property set occurrences, +property set templates, and property templates.

                  +
                  +

                  Property set template - +IfcPropertySetTemplate, a collection of property templates +that determine the definition of properties used within a project +context.

                  +

                  Property template - +IfcPropertyTemplate, a single template that determines the +definition of a particular property used in the same project +context. The template may determine the name, description, data +type, the unit, or a standard expression for each property that is +based on that template.

                  +

                  Property set occurrence - +IfcPropertySet, a set of individual properties (that may +or may not be determined by a property template) holding individual +values, measure types and units, and are associated to an object +occurrence or object type.

                  +
                  + +
                  +NOTE 1  The subtype hierarchy of IfcPropertyDefinition also includes statically defined property sets as IfcPreDefinedPropertySet. Those are rarely used collections of fixed attributes combined in an entity definition. The IfcPreDefinedPropertySet can not be determined by an IfcPropertySetTemplate. +
                  + +
                  +NOTE 2  Individual properties, (subtypes of IfcProperty), are currently not included in the subtype hierarchy of IfcPropertyDefinition. This anomaly is due to upward compatibility reasons with earlier releases of this +standard. +
                  + +
                  +HISTORY  New Entity in IFC2.0 +
                  + +

                  Relationship use definition

                  +

                  Property definitions define information that is shared among +multiple instances of objects, either object occurrences or object +types. IfcPropertyDefinition's (by their instantiable +subtypes) can participated within the following relationships:

                  +
                    +
                  • Assignment to a project context - an +HasContext relationship to IfcRelDeclares that +establishes the project context in which this property definition +is declared. This relationship is predominately applicable to +subtypes of IfcPropertyTemplateDefinition.
                  • +
                  • Association to external resources - an +HasAssociation relationship to IfcRelAssociates +that refers to external sources of information (most notably a +classification or document) and creates a uni-directional +association. There is no dependency implied by the +association.
                  • +
                  +

                  Subtypes are included in more specific relationships, see +IfcPropertySetDefinition and +IfcPropertyTemplateDefinition for details.

                  + +
                  " +820;IfcPropertySetDefinition;" + +

                  IfcPropertySetDefinition is a generalization of all +individual property sets that can be assigned to an object or type +object. The property set definition can be either:

                  +
                  +

                  Dynamically extendable property sets - +IfcPropertySet, a set of properties for which the IFC +model only provides a kind of ""meta model"", to be further declared +by agreement. This means no entity definition of the properties +exists within the IFC model. The declaration is done by assigning a +significant string value to the Name attribute of the +entity as defined in the entity IfcPropertySet and at each +subtype of IfcProperty, referenced by the property set. +Dynamically defined property sets may have an underlying template +provided by IfcPropertySetTemplate.

                  +

                  Statically defined property sets - +IfcPreDefinedPropertySet, a property set entity that +exists within the IFC specification. The semantic meaning of each +statically defined property set is declared by its entity type and +the meaning of the properties is defined by the name and data type +of the explicit attribute representing it.

                  +
                  + +
                  +HISTORY  New Entity in IFC Release 2x +
                  + +
                  +IFC2x4 CHANGE  The subtype IfcPreDefinedPropertySet has been added. +
                  + +

                  Relationship use definition

                  +

                  Property set definitions define information that is shared among +multiple instances of objects, either object occurrences or object +types. IfcPropertySetDefinition's (by their instantiable +subtypes) can participated within the following relationships:

                  +
                    +
                  • Assignment to object types - an +DefinesType direct relationship to IfcTypeObject +that applies the property set, with all included properties, to the +object type. Those properties apply to all object occurrences +having the same object type.
                  • +
                  • Assignment to object occurrences - an +DefinesOccurrence relationship to +IfcRelDefinesByProperties that applies the property set, +with all included properties, to the object occurrence.
                  • +
                  + +
                  +NOTE  Properties assigned to object occurrences may override properties assigned to the object type. See IfcRelDefinesByType for further information. +
                  + +
                  " +825;IfcPropertySet;" + +

                  IfcPropertySet defines all dynamically extensible +properties. The property set is a container class that holds +properties within a property tree. These properties are interpreted +according to their name attribute.

                  +

                  The same IfcPropertySet can be assignd to multiple +object occurrences, it should then be assigned by a single instance +of IfcRelDefinedByProperties to a set of related objects. +Those property sets are referred to as shared property sets. It can +also be assigned to an object type.

                  +

                  The underlying structure, i.e. the required name, the applicable +object or object types to which the property set can be attached +and the individual properties that maybe included can be assigned +using the property set template.

                  + +
                  +NOTE  See IfcRelDefinesByType for how to override property sets assigned to an object type within the object occurrence. +
                  + +
                  +HISTORY  New Entity in IFC Release 1.0 +
                  + +
                  +IFC2x4 CHANGE  All statically defined property set entities are no longer subtypes of +IfcPropertySet. +
                  + +

                  Relationship use definition

                  +

                  Property sets are related to other objects by using the +relationship object that refers to the corresponding object:

                  +
                    +
                  • Occurrence Object: IfcRelDefinesByProperties +using the inverse attribute DefinesOccurrence.
                  • +
                  • Type Object: using a direct link by inverse attribute +DefinesType.
                  • +
                  • External reference: subtypes of +IfcRelAssociates are used to provide a link to a +classification system, or external library providing further +reference to the property set. Accessible by inverse attribute +HasAssociations.
                  • +
                  • Underlying template: IfcRelDefinesByTemplate +using the inverse attribute IsDefinedBy.
                  • +
                  + +

                  Attribute use definition

                  +

                  Instances of IfcPropertySet are used to assign named +sets of individual properties (complex or single properties). Each +individual property has a significant name string. Some property +sets are included in the IFC specification and have a +predefined set of properties indicated by assigning a significant +name. These property sets are listed under ""property sets"" main +menu item within this specification and from the object +documentation sheet for those object to which they are applicable. +The naming convention ""Pset_Xxx"" applies to all those property sets +that are defined as part of the IFC specification and it shall be +used as the value of the Name attribute.

                  +

                  In addition any user defined property set can be captured. +Property sets that are not declared as part of the IFC +specification shall have a Name value not including the +""Pset_"" prefix.

                  + +
                  " +830;IfcRelDefinesByTemplate;" + +

                  The objectified relationship +IfcRelDefinesByTemplate defines the relationships between +property set template and property sets. Common information about +property sets, e.g. the applicable name, description, contained +properties, is defined by the property set template and assigned +to all property sets.

                  +

                  The IfcRelDefinesByTemplate is a 1-to-N relationship, +as it allows for the assignment of one property set template to a +single or to many property sets. Those property sets then share +the same property set template definition.

                  + +
                  +HISTORY New Entity in IFC2x4. +
                  + +
                  " +833;IfcRelDefines;" + +

                  A generic and abstract relationship which subtypes are used to:

                  +
                    +
                  • assign a object type to an object occurrence
                  • +
                  • assign a property set to an object instance
                  • +
                  • assign a property set template to a property set
                  • +
                  +
                  EXAMPLE ÿSeveral instances of windows within +the IFC project model may be of the same (catalogue or +manufacturer) type. Thereby they share the same properties. This +relationship is established by the subtype +IfcRelDefinesByType of IfcRelDefines relationship +assigning an IfcWindowStyle to multiple occurrences +IfcWindow.
                  +
                  +EXAMPLE ÿThe (same) property set, e.g.ÿ +Pset_ProductManufacturerInfo, keeping the manufacturer name, +label and production year of a product, can be assigned to one, +or many instances of furnishing. This relationship is established +by the subtype IfcRelDefinesByProperties of +IfcRelDefines relationship assigning an +IfcPropertySet to one or more instances of +IfcFurnishingElement.
                  + +
                  +HISTORY New entity in IFC2x. +
                  + +
                  +IFC2x4 CHANGE The attribute RelatedObjects had been demoted to the subtypes IfcRelDefinesByProperties and +IfcRelDefinesByType. +
                  + +
                  " +838;IfcRelationship;" + +

                  IfcRelationship is the abstract generalization of all objectified relationships in IFC. Objectified relationships are the preferred way to handle relationships among objects. This allows to keep relationship specific properties directly at the relationship and opens the possibility to later handle relationship specific behavior.

                  + +

                  There are two different types of relationships, 1-to-1 relationships and 1-to-many relationship. used within the subtypes of IfcRelationship. The following convention applies to all subtypes:

                  + +
                    +
                  • The two sides of the objectified relationship are named
                    - Relating+<name of relating object> and
                    - Related+<name of related object>
                  • +
                  • In case of the 1-to-many relationship, the related side of the relationship shall be an aggregate SET 1:N
                  • +
                  + +
                  +HISTORY: New entity in IFC Release 1.0. +
                  + +
                  " +845;IfcRelAssigns;" + +

                  The assignment relationship, IfcRelAssigns, is a generalization of ""link"" relationships among instances of IfcObject and its various 1st level subtypes. A link denotes the specific association through which one object (the client) applies the services of other objects (the suppliers), or through which one object may navigate to other objects.

                  + +

                  The client is denoted as the relating object and is established at the level of the specific, instantiable subtypes of IfcRelAssigns. The suppliers are denoted as the related objects and they are established by the RelatedObjects attribute.

                  + +
                  +NOTE: The terms ""client"" and ""supplier"" are used in a general concept and do not imply any meaning for implementations of systems (like client-server). +
                  + +
                  +EXAMPLE: A resource may receive information about its nature of representing real building products by establishing a link between IfcResource and IfcBuildingElement (subtype of IfcProduct) through the assignment relationship IfcRelAssignsToResource. The resource is then the client that applies the services of other objects (here building elements) to express the particular view of elements to be consumed as a resource in a process. +
                  + +

                  The assignment relationship establishs a bi-directional relationship among the participating objects and does not imply any dependency. The subtypes of IfcRelAssigns establishes the particular semantic meaning of the assignment relationship.

                  + +
                  +HISTORY: New entity in IFC Release 2x. +
                  + +
                  " +855;IfcRelAssignsToProcess;" + +

                  The objectified relationship IfcRelAssignsToProcess handles the assignment of one or many objects to a process or activity. An object can be a product that is the item the process operates on. Processes and activities can operate on things other than products, and can operate in ways other than input and output.

                  + +
                  EXAMPLE It may be common to define processes +during estimating or scheduling that describe design tasks +(resulting in documents), procurement tasks (resulting in +construction materials), planning tasks (resulting in processes), +etc. Furthermore, the ways in which process can operate on +something might include ""installs"", ""finishes"", ""transports"", +""removes"", etc. The ways are described as operation +types.
                  +

                  The inherited attribute RelatedObjects gives the +references to the objects, or object type, which the process +operates on. The RelatingProcess is the process or process +type, that operates on the object. The operation types are +captured in the inherited attribute Name.

                  +
                  NOTE The agreement on valid and recognizable +values for the Name attribute is part of view definitions +and implementer agreements.
                  + +
                  +HISTORY New entity in IFC Release 1.5. Has been renamed from IfcRelProcessOperatesOn in IFC Release 2x. +
                  + +
                  +IFC2x4 CHANGE The data type RelatingProcess has been extended to cover also IfcTypeProcess +
                  + +
                  " +862;IfcProcess;" + +

                  Definition from ISO9000: A process is a set of +activities that are interrelated or that interact with one +another. Processes use resources to transform inputs into +outputs. Processes are interconnected because the output from one +process becomes the input for another process. In effect, +processes are ""glued"" together by means of such input output +relationships.

                  + +

                  IfcProcess is defined as +one individual activity or event, that is ordered in time, that +has sequence relationships with other processes, which transforms +input in output, and may connect to other other processes through +input output relationships. An IfcProcess can be an +activity (or task), or an event. It takes usually place in +building construction with the intent of designing, costing, +acquiring, constructing, or maintaining products or other and +similar tasks or procedures.

                  + + + + + + + +
                  +

                  Figure 2 — Process relationships and the ICON process diagram.

                  +
                  + +
                  +HISTORY New entity in IFC Release 1.0. +
                  + +
                  +IFC2x PLATFORM CHANGE The attribute Productivity has been removed. +
                  + +
                  +IFC2x4 CHANGE The attribute Identification has been promoted from subtypes IfcTask and others. +
                  + +

                  Relationship use definition

                  +

                  Process information relates to other objects by establishing the following relationships:

                  +
                    +
                  • Nesting of processes : IfcRelNests - A process can contain sub processes and thereby be nested.
                  • +
                  • Sequencing of processes : IfcRelSequence - Processes can be placed in sequence (including overlapping for parallel tasks), and have predecessors and successors.
                  • +
                  • Assigning process to schedules : IfcRelAssignsToControl - Activities such as tasks, and predominately summary tasks, are assigned to a work schedule.
                  • +
                  • Having a product assigned to the process as input : +IfcRelAssignsToProcess - Products can be assigned as input to a process, such as for construction process planning.
                  • +
                  • Having a product assigned to the process as output : +IfcRelAssignsToProduct - Products can be assigned as output to a process, such as for construction process planning.
                  • +
                  • Having a control assigned to the process as process control : IfcRelAssignsToProcess - Items that act as a +control onto the process can be assigned to a process, such as for cost management (a cost item assigned to a work task).
                  • +
                  • Having a resource assigned to the process as consumed by the process : IfcRelAssignsToProcess - Items that act +as a mechanism to a process, such as labor, material and equipment in cost calculations.
                  • +
                  + +
                  " +868;IfcTypeProcess;" + +

                  IfcTypeProcess defines a +specific (or type) definition of a process or activity without +being assigned to a schedule or a time.ÿIt is used to define a +process or activity specification, that is, the specific process or +activity information that is common to all occurrences that are +defined for that process or activity type.

                  + +

                  An IfcTypeProcess may have a list of property set +attached. Values of these properties are common to all +occurrences of that process or activity type. The type occurrence +relationship is realized using the objectified relationship +IfcRelDefinesByType.

                  + +

                  Subtypes of IfcTypeProcess may be exchanged without +being already assigned to subtypes of IfcProcess.

                  + +
                  +HISTORY New entity in IFC2x4. +
                  + +

                  Property set use definition

                  +

                  An IfcTypeProcess may have a list of property sets +attached, accessible by the attribute +SELF\IfcTypeObject.HasPropertySets. Currently there are no +predefined property sets defined as part of the IFC +specification.

                  +
                  NOTE: For property sets, a property within an +occurrence property set that is assigned at the process +occurrence, overrides the same property assigned to the process +type.
                  + +
                  " +873;IfcTypeObject;" + +

                  The object type defines the +specific information about a type, being common to all +occurrences of this type. It refers to the specific level of the +well recognized generic - specific - occurrance modeling +paradigm. The IfcTypeObject gets assigned to the +individual object instances (the occurrences) via the +IfcRelDefinesByType relationship.

                  +
                  NOTE The terms 'Type' and 'Style' are often +used interchangeably.
                  +

                  The object type is represented by a set of property set +definitions. The attached property sets describe the available +alpha-numeric information about the object type. and are used to +define all common properties that apply to all object occurrences +of that type.

                  +
                  NOTE If a property having having the same name +is used within the IfcPropertySet assigned to an +IfcTypeObject (and subtypes) and to an occurrence of that +type, then the occurrence property overrides the type property. +See IfcRelDefinesByType for an explanatory +figure.
                  +

                  Object types may be exchanged without being already assigned +to objects. An object type may have an indication of the library +(or catalogue) from which its definition originates. This +association is handled by the inherited HasAssociations +relationship pointing to IfcRelAssociatesLibrary.

                  + +
                  +HISTORY New entity in IFC Release 2x +
                  + +
                  +IFC2x3 CHANGE The IfcTypeObject is now subtyped from the new supertype IfcObjectDefinition, and the attribute HasPropertySets has been changed from a LIST into a SET. +
                  + +
                  +IFC2x4 CHANGE (1) The entity IfcTypeObject shall not be instantiated from IFC2x4 onwards. It will be changed into an ABSTRACT supertype in future releases of IFC. (2) The inverse attribute Types has been renamed from ObjectTypeOf. +
                  + +
                  " +881;IfcTypeProduct;" + +

                  IfcTypeProduct defines a type +definition of a product without being already inserted into a +project structure (without having a placement), and not being +included into the geometric representation context of the +project.ÿIt is used to define a product specification, that is, the +specific product information that is common to all occurrences +of that product type.

                  + +

                  An IfcTypeProduct may have a list of property set +attached and an optional set of product representations. Values +of these properties and the representation maps are common to all +occurrencesÿof that product type.ÿThe type occurrence +relationship is realized using the objectified relationship +IfcRelDefinesByType.

                  + +
                  NOTE 1ÿ The product representations are +defined as representation maps, which gets assigned by a product +instance through the representation item(s) being an +IfcShapeRepresentation and having Items of +typeÿIfcMappedItem.
                  +
                  NOTE 2 ÿThe representations at the occurrence +level (represented by subtypes of IfcProduct) can override +the specific representations at the type level, ÿ
                  +
                  +
                    +
                  1. for geometric representations: a Cartesian +transformation operator can be applied at the occurrence level, +andÿ
                  2. +
                  3. for property sets: A property within an occurrence +property set, assigned at the product occurrence, overrides the +same property assigned to the product type.
                  4. +
                  +
                  +
                  +

                  An IfcTypeProduct may be exchanged without being +already assigned to subtypes of IfcProduct.

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  + +
                  +IFC2x4 CHANGE The entity IfcTypeProduct shall not be instantiated from IFC2x4 onwards. It will be changed into an ABSTRACT supertype in future releases of IFC. +
                  + +

                  Geometry use definition

                  +

                  The RepresentationMaps define the type product shape +and multiple geometric representations can be assigned. If a +product occurrence is assigned to the type by using the +IfcRelDefinesByType relationship, then these occurrences +have to reference the representation maps. The reference is +created by one or multiple IfcShapeRepresentation's having +an IfcMappedItem as Items, that places the +IfcRepresentationMap of the type product into the spatial +contexts, i.e. by using an Cartesian transformation operator to +transform the IfcRepresentationMap into the object +coordinate system of the product occurrence.

                  + +

                  Figure 10 illustrates an example of referencing a representation map by +the shape representation of a product occurrence. Here the +Cartesian transformation operator only uses translation, but no +rotation, mirroring, or scaling.

                  + + + + +

                  Figure 10 — Product type geometry with single placement

                  + +

                  Figure 11 illustrates an example of referencing a representation +multiple times map by the shape representation of a product +occurrence. Here the Cartesian transformation operator only uses +translation, but no rotation, mirroring, or scaling. The +different translation values determine the pattern of the +multiple placement.

                  + + + + +

                  Figure 11 — Product type geometry with multiple placement

                  + +
                  " +886;IfcRelAssignsToProduct;" +

                  The objectified relationshipÿIfcRelAssignsToProduct handles the assignment of objects (subtypes of IfcObject) to a product (subtypes of IfcProduct). The Name attribute should be used to classify the usage of the IfcRelAssignsToProduct objectified relationship. The following Name values are proposed:

                  +
                    +
                  • 'Context' : Assignment of a context specific representation, such as of structural members to a different context representation (with potentially different decomposition breakdown) such as of building elementsÿfor a specificÿcontext specific representation.ÿ
                  • +
                  • 'View' : Assignment of a product (via RelatingProduct) that is decomposed according to a discipline view, to another product (via RelatedObjects) that is decomposed according to a different discipline view. An example is the assignment of the architectural slab to a different decomposition of the pre manufactured sections of a slab (under a precast concrete discipline view).
                  • +
                  + +
                  +HISTORY New Entity in IFC Release 2x +
                  + +
                  +IFC2x3 CHANGE ÿThe reference of a product within a spatial structure is now handled by a new relationship object IfcRelReferencedInSpatialStructure. The IfcRelAssignsToProduct shall not be used to represent this relation from IFC2x3 onwards. +
                  + +
                  " +892;IfcTypeResource;" + +

                  IfcTypeResource defines a specific (or type) definition of a resource.ÿIt is used to define a resource specification (the specific resource, that is common to all occurrences that are defined for that resource) and could act as a resource template.

                  + +

                  An IfcTypeResource may have a list of property sets attached. Values of these properties are common to all occurrences of that resource type. The type occurrence relationship is realized using the objectified relationship IfcRelDefinesByType.

                  + +

                  Subtypes of IfcTypeResource may be exchanged without being already assigned to subtypes of IfcResource.

                  + +
                  +HISTORY New entity in IFC2x4. +
                  + +

                  Property set use definition

                  +

                  An IfcTypeResource may have a list of property sets attached, accessible by the attribute SELF\IfcTypeObject.HasPropertySets. Currently there are no predefined property sets defined as part of the IFC specification.

                  + +
                  +NOTE: For property sets, a property within an occurrence property set that is assigned at the resource occurrence, overrides the same property assigned to the resource type. +
                  + +
                  " +897;IfcRelAssignsToResource;" + +

                  The objectified relationship IfcRelAssignsToResource handles the assignment of objects +(as subtypes of IfcObject), acting as a resource usage or consumption, to a resource (as subtypes of IfcResource).

                  + +
                  +EXAMPLE The assignment of a resource usage to a construction resource is an application of this generic relationship. It could be an actor, as person or organization assigned to a labor resource, or a raw product assigned to a construction product or material resource). +
                  + +
                  +HISTORY New Entity in IFC Release 2x. +
                  + +
                  " +903;IfcResource;" + +

                  IfcResource contains the information needed to represent the costs, schedule, and other impacts from the use of a thing in a process. It is not intended to use IfcResource to model the general properties of the things themselves, while an optional linkage from IfcResource to the things to be used can be specified (specifically, the relationship from subtypes of IfcResource to IfcProduct through the IfcRelAssignsToResource relationship).

                  + +

                  There are two basic intended uses of IfcResource. First, if the attributes of the thing are not needed for the purpose of the use of IfcResource, or the types of things are not explicitly modeled in IFC yet, then the linkage between the resource and the thing doesn't have to be instantiated in the system. That is, the attributes of IfcResource (or its subtypes) alone are sufficient to represent the use of the thing as a resource for the purpose of the project.

                  + +
                  +EXAMPLE: construction equipment such as earth-moving vehicles or tools are not currently modeled within the IFC. For the purpose of estimating and scheduling, these can be represented using subtypes of IfcResource alone. +
                  + +

                  Second, if the attributes of the thing are needed for the use of IfcResource objects, and they are modeled explicitly as objects, then the IfcResource instances can be linked to the instances of the type of the things being referenced. Things that might be used as resources and that are already modeled in the IFC include physical products, people and organizations, and materials. The relationship object IfcRelAssignsToResource is provided for this approach.

                  + +

                  The inherited attribute ObjectType is used as a textual code that identifies the resource type.

                  + +
                  +HISTORY New entity in IFC Release 1.0 +
                  + +
                  +IFC2x PLATFORM CHANGE: The attributes BaseUnit and ResourceConsumption have been removed from the abstract entity; they are reintroduced at a lower level in the hierarchy. +
                  + +
                  " +907;IfcRelDefinesByType;" +

                  The objectified relationship +IfcRelDefinesByType defines the relationship between an +object type and object occurrences.

                  +

                  The IfcRelDefinesByType is a 1-to-N relationship, as it +allows for the assignment of one type information to a single or +to many objects. Those objects then share the same object type, +and the property sets and properties assigned to the object +type.

                  + +
                  +HISTORY New entity in IFC2x. +
                  + +
                  +IFC2x4 CHANGE The attribute RelatedObjects had been demoted from the supertype IfcRelDefines to IfcRelDefinesByType. +
                  + +

                  Relationship use definition

                  + +

                  The IfcRelDefinesByType links the object type +definition with the object occurrence. Both may define properties +by assigning an IfcPropertySet, including one or many +subtypes of IfcProperty to either the object type or +object occurrence, as shown in Figure 8.

                  +

                  There are several scenarios to define the same property +set on the object type definition and object occurrence +side:

                  +
                    +
                  1. All properties for all object occurrences of a common +object type have the same value - then only the object type +definition has a property set assigned.
                  2. +
                  3. All properties for all object occurrences are +different, that is there are no common property values for the +object type definition - then each of the object occurrence has a +property set assigned.
                  4. +
                  5. Some properties within the same property set have +common values and are assigned to the object type definition and +some are occurrence specific and assigned (with potentially +different values) to the object occurrences - then: +
                      +
                    • The sum of all properties within a given property set +applicable to an object occurrence is the union of properties +assigned to the object type definition plus the properties +assigned to the object occurrence.
                    • +
                    • If the object occurrence has a property with the same +IfcProperty.Name in an IfcPropertySet, as the +corresponding object type definition, then the occurrence +property value overrides the type property value.
                    • +
                    +
                  6. +
                  + + + + +

                  Figure 8 — Type definition relationships

                  + +

                  The following table provides an example of assigning

                  + + + + + + + + + + + + + + + + + + + + + + + + + + +
                  properties assigned to +IfcWallproperties assigned to +IfcWallTyperesulting property value for individual +wall
                  Pset_WallCommonPset_WallCommonÿ
                  ÿ-ÿExtendToStructure = TRUEÿTRUE
                  ÿÿ-ÿThermalTransmittance = 0.3750.375
                  ÿ-ÿExtendToStructure = FALSEÿ-ÿExtendToStructure = TRUEFALSE
                  +
                  " +910;IfcRelAssignsToControl;" + +

                  The objectified relationship IfcRelAssignsToControl handles the assignment of a control (represented by subtypes of IfcControl) to other objects (represented by subtypes of IfcObject, with the exception of controls).

                  + +
                  +EXAMPLEÿ The assignment of a performance history (as subtype of IfcControl) for a building service element (as subtype of IfcObject) is an application of this generic relationship. +
                  + +
                  +HISTORYÿ New Entity in IFC Release 2.0. Has been renamed from IfcRelControls in IFC Release 2x. +
                  + +
                  " +913;IfcControl;" + +

                  IfcControl is the abstract generalization of all concepts that control or constrain the utilization of products, processes, or resources in general. It can be seen as a regulation, cost schedule, request or order, or other requirements applied to a product, process or resource whose requirements and provisions must be fulfilled.

                  + +
                  +EXAMPLE Controls include action requests, cost schedules, project orders, work plans, and work calendars. +
                  + +
                  +HISTORY New entity in IFC Release 1.0. +
                  + +
                  +IFC2x4 CHANGE Attribute Identification added. +
                  + +

                  Relationship use definition

                  +

                  Controls have assignments from products, processes, or other objects by using the relationship object IfcRelAssignsToControl.

                  + +
                  " +916;IfcRelAssignsToActor;" + +

                  The objectified relationship IfcRelAssignsToActor handles the assignment of objects (subtypes of IfcObject) to an actor (subtypes of IfcActor).

                  + +

                  The IfcRelAssignsToActor objectified relationship defines a relationship between an IfcActor and one or many objects. A particular role of the actor played in that relationship can be associated. If specified, it takes priority over the role that may be directly assigned to the person or organization.

                  + +
                  EXAMPLE: An occupant (as an actor) may rent a flat (as a collection of spaces or a zone). This would be an application of this generic relationship. +
                  + +

                  Reference to the objects (or single object) on which the actor acts upon in a certain role (if given) is specified in the inherited RelatedObjects attribute.

                  + +
                  +HISTORY New Entity in IFC Release 2.0. Has been renamed from IfcRelActsUpon in IFC Release 2x. +
                  + +
                  " +920;IfcActor;" + +

                  The IfcActor defines all actors or human agents involved in a project during its full life cycle. It facilitates the use of person and organization definitions in the resource part of the IFC object model. This includes name, address, telecommunication addresses, and roles.

                  + +
                  +HISTORY New Entity in IFC Release 2.0 +
                  + +

                  Relationship use definition

                  +

                  Actors are assigned (such as to a process or a resource) by the relationship object that refers to the corresponding object:

                  +
                    +
                  • Process: assigned using IfcRelAssignsToProcess
                  • +
                  • Resource: assigned using IfcRelAssignsToResource
                  • +
                  + +

                  Property set use definition

                  +

                  The property sets relating to the IfcActor are defined by IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. They are accessible by the inverse IsDefinedBy relationship. The following property set definitions specific to IfcActor are part of this IFC release:

                  + + +
                  " +923;IfcRelAssignsToGroup;" +

                  The objectified relationship IfcRelAssignsToGroup handles the assignment of object definitions (individual object occurrences as subtypes of IfcObject, and object types as subtypes of IfcTypeObject) to a group (subtypes of IfcGroup).

                  + +

                  The relationship handles the assignment of group members to the group object. It allows for grouping arbitrary objects within a group, including other groups. The grouping relationship can be applied in a recursive manner. The resulting group is of type IfcGroup.

                  + +
                  +NOTE Examples of groups include zones as a grouping of spaces, distribution systems as a grouping of building service components, or structural analysis models as a grouping of structural items. +
                  + +

                  The inherited attribute RelatedObjects gives the references to the objects, which are the elements within the group. The RelatingGroup is the group that comprises all elements. The same object or object type can be included in zero, one or many groups. Grouping relationships are not hierarchical.

                  + +

                  Informal proposition:

                  +
                    +
                  1. The group assignment relationship shall be acyclic, that is, a group shall not participate in its own grouping relationship.
                  2. +
                  + +
                  +HISTORY New entity in IFC Release 1.0. It has been renamed from IfcRelGroups in IFC Release 2x. +
                  + +
                  " +927;IfcRelAssignsToGroupByFactor;" + +

                  The objectified relationship IfcRelAssignsToGroupByFactor is a specialization of the general grouping mechanism. It allows to add a factor to define the ratio that applies to the assignment of object definitions (individual object occurrences as subtypes of IfcObject and object types as subtypes of IfcTypeObject) to a group (subtypes of IfcGroup).

                  + +

                  The ratio can be used to define a percentage assignment. For example, a Factor of 0.8 would indicate that the object is assigned by 80% to the group, or a Factor of 2.5 would indicate the object is assigned with a weight factor of 2.5 to the group.

                  + +
                  +NOTE Examples of factored groups include the assignment of load cases in a load combination in structural analysis, or the assignment of spaces by percentage to different rental zones. +
                  + +

                  The same object or object type may be included with the same or different Factor values to many groups. Grouping relationships are not hierarchical.

                  + +
                  +HISTORY New entity in IFC2x4. +
                  + +
                  " +929;IfcGroup;" + +

                  IfcGroup is an generalization of any arbitrary group. A group is a logical collection of objects. It does not have its own position, nor can it hold its own shape representation. Therefore a group is an aggregation under some non-geometrical / topological grouping aspects.

                  + +
                  +NOTE Use IfcRelDecomposes together with the appropriate subtypes of IfcProduct to define an aggregation of products that may have its own position and shape representation. +
                  + +
                  +EXAMPLE An example for a group is a system, since it groups elements under the aspect of their role, regardless of their position in a building.
                  + +

                  A group can hold any collection of objects (beingÿproducts, processes, controls, resources, actors or other groups). Thus groups can be nested. An object can be part of zero, one, or many groups. Grouping relationships are not required to be hierarchical nor do they imply a dependency.

                  + +
                  NOTE Use IfcRelDecomposes together with the appropriate subtypes of IfcProduct to define an hierarchical aggregation of products.
                  + +

                  A group can be exchanged without having already objects within the group collection.

                  + +
                  +HISTORY New entity in IFC Release 1.0. +
                  + +
                  +IFC2x4 CHANGE The inverse IsGroupedBy relationship is set to 0..n +
                  + +

                  Relationship use definition

                  +

                  The group collection is handled by an instance of IfcRelAssignsToGroup, which assigns all group members to the IfcGroup.

                  +
                    +
                  • Objects: included in group using IfcRelAssignsToGroup
                  • +
                  +

                  Groups are assigned to other objects (such as a process or a resource) by the relationship object that refers to the corresponding +object:

                  +
                    +
                  • Process: assigned using IfcRelAssignsToProcess
                  • +
                  • Resource: assigned using IfcRelAssignsToResource
                  • +
                  +

                  Groups can be subjected to a control. The control information is then assigned:

                  +
                    +
                  • Controls: affecting the group using IfcRelAssignsToControl
                  • +
                  + +
                  " +940;IfcRelDecomposes;" + +

                  The decomposition relationship, +IfcRelDecomposes, defines the general concept of elements +being composed or decomposed. The decomposition relationship +denotes a whole/part hierarchy with the ability to navigate from +the whole (the composition) to the parts and vice versa.

                  +

                  Decompositions may be constrained by requiring both, the whole +and its parts, to be of the same type - thus establishing a +nesting relationship. Or they may require some form of physical +containment, thus establishing special types of aggregation +relationships.

                  +
                  NOTE There are two special names for +decomposition, which are linguistically distinguished, nesting +and aggregation. The subtypes of IfcRelDecomposes will +introduce either the nesting or aggregation convention (see +IfcRelNests and +IfcRelAggregates).
                  +
                  EXAMPLE A cost element is a nest of other cost +elements. Or a structural frame is an aggregation of beams and +columns. Both are applications of decomposition +relationship.
                  +

                  Decompositions imply a dependency, i.e. the definition of the +whole depends on the definition of the parts and the parts depend +on the existence of the whole. The decomposition relationship can +be applied in a recursive manner, i.e. a decomposed element can +be part in another decomposition. Cyclic references have to be +prevented at application level.

                  + +
                  +HISTORY New entity in IFC Release 1.5, it is a generalisation of the IFC2.0 entity IfcRelNests. +
                  + +
                  +IFC2x4 CHANGE The differentiation between the aggregation and nesting is determined to be a non-ordered or an ordered collection of parts. The attributes RelatingObject and RelatedObjects have been demoted to the subtypes. +
                  + +
                  " +943;IfcRelAggregates;" + +

                  The aggregation relationship +IfcRelAggregates is a special type of the general +composition/decomposition (or whole/part) relationship +IfcRelDecomposes. The aggregation relationship can be +applied to all subtypes of IfcObjectDefinition.

                  +

                  In cases of aggregation of physical elements into a physical +aggregate the shape representation of the whole (within the same +representation identifier) can be taken from the sum of the shape +representations of the parts.

                  +
                  EXAMPLE A roof is the aggregation of the roof +elements, such as roof slabs, rafters, purlins, etc. Within the +same representation identifier, e.g. the body geometric +representation, the shape representation of the roof is given by +the shape representation of its parts
                  +

                  Decompositions imply a dependency, i.e. the definition of the +whole depends on the definition of the parts and the parts depend +on the existence of the whole. The behaviour that is implied from +the dependency has to be established inside the applications.

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  + +
                  +IFC2x4 CHANGE The attributes RelatingObject and RelatedObjects are demoted from the supertype IfcRelDecomposes. +
                  + +" +947;IfcRelNests;" + +

                  The nesting relationship +IfcRelNests is a special type of the general +composition/decomposition (or whole/part) relationship +IfcRelDecomposes. The nesting relationship can be applied +to all non physical subtypes of object and object types, namely +processes, controls (like cost items), and resources. The nesting +implies an order among the nested parts.

                  +
                  EXAMPLE1 A nesting of costs items in a cost +schedule is the composition of complex cost items from other cost +items. The order of the nested cost items underneath the parent +cost item is determined by the order of the list of +RelatedObjects.
                  +
                  EXAMPLE2 A nesting of work tasks within a work +schedule is the composition of a parent work task from more +specific sub work tasks. The order of the sub tasks underneath +the parent task is determined by the order of the list of +RelatedObjects..
                  +

                  Decompositions imply a dependency, i.e. the definition of the +whole depends on the definition of the parts and the parts depend +on the existence of the whole. The behaviour that is implied from +the dependency has to be established inside the applications.

                  + +
                  +HISTORY New entity in IFC Release 2.0 +
                  + +
                  +IFC2x4 CHANGE The attributes RelatingObject and RelatedObjects are demoted from the supertype IfcRelDecomposes, and RelatedObjects is refined to be a list. The use of IfcRelNests is repurposed to be a nesting of an ordered collections of parts. +
                  + +
                  " +951;IfcRelAssociates;" +

                  + The association relationship + IfcRelAssociates refers to external sources of + information (most notably a classification, library or + document). There is no dependency implied by the + association. +

                  +
                  + EXAMPLE Further information may be given + to the tank equipment (as subtype of IfcProduct) in + terms of its classification and instruction documents, the + source of the additional information is held external to + the IFC project model. +
                  +

                  + Association relationships can be established to objects + (occurrences as subtypes of IfcObject) or to types + (as subtypes of IfcTypeObject). +

                  +
                  + EXAMPLE 1 The classification information + for the storage tank equipment may be associated to the + IfcTankType (subtype of IfcTypeObject), + defining the specific information for all occurencies of + that tank in the project. Therefore the association of the + (e.g.) Uniclass notation 'L6814' may be associated by a + subtype of IfcRelAssociates to the type + information. +
                  +
                  + EXAMPLE 2 The classification information + for a particular space within a building may the associated + to the IfcSpace object (subtype of + IfcObject), defining a particular occurrence of + space. Therefore the association of the (e.g.) DIN notation + 'HNF 1.5' may be associated by a subtype of + IfcRelAssociates to the object. +
                  +

                  + The association relationship establishs a uni-directional + association. The subtypes of IfcRelAssociates + establishes the particular semantic meaning of the + association relationship. +

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  + +
                  +IFC2x4 CHANGE Entity has been changed into an ABSTRACT supertype +
                  + +
                  " +956;IfcRelAssociatesClassification;" +

                  The objectified relationship +IfcRelAssociatesClassification handles the assignment of a +classification item (items of the select +IfcClassificationSelect) to objects occurrences (subtypes of +IfcObject) or object types (subtypes of +IfcTypeObject).

                  +

                  The relationship is used to assign a classification item, or a +classification system itself to objects. Depending on the type of +the RelatingClassification it is either:

                  +
                    +
                  • a reference to an classification item within an external +classification system, or
                  • +
                  • a reference to the classification system itself
                  • +
                  +
                  +

                  NOTE  The reference to a classification item +includes a link to the classification system within which the item +is declared. It assigns the meaning of the classification item to +the object (ocurrence or type). The reference to the classification +system provides the information that the object (occurrence or +type) is governed by the classification system but no assignment of +a particular items has been done yet.

                  +
                  +

                  The inherited attribute RelatedObjects define the objects +or object types to which the classification is applied. The +attribute RelatingClassification is the reference to a +classification, applied to the object(s). A single +RelatingClassification can thereby be applied to one or +multiple objects.

                  + +
                  +HISTORY New entity in IFC Release 2x. +
                  + +
                  " +958;IfcRelAssociatesDocument;" + +

                  The objectified relationship (IfcRelAssociatesDocument) handles the assignment of a document information (items of the select IfcDocumentSelect) to objects occurrences (subtypes of IfcObject) or object types (subtypes of IfcTypeObject).

                  + +

                  The relationship is used to assign a document reference or a more detailed document information to objects. A single document reference can be applied to multiple objects.

                  + +

                  The inherited attribute RelatedObjects define the objects to which the document association is applied. The attribute RelatingDocument is the reference to a document reference, applied to the object(s).

                  + +
                  +HISTORY: New entity in IFC Release 2x. +
                  + +
                  " +960;IfcRelAssociatesLibrary;" + +

                  The objectified relationship (IfcRelAssociatesLibrary) handles the assignment of a library item (items of the select IfcLibrarySelect) to subtypes of IfcObjectDefinition or IfcPropertyDefinition.

                  + +

                  The relationship is used to assign a library reference or a more detailed link to a library information to objects, property sets or types. A single library reference can be applied to multiple items.

                  + +

                  The inherited attribute RelatedObjects define the items to which the library association is applied. The attribute RelatingLibrary is the reference to a library reference, applied to the item(s).

                  + +
                  +HISTORY: New entity in IFC Release 2x. +
                  + +
                  " +965;IfcRelConnects;" + +

                  IfcRelConnects is a connectivity relationship that connects objects under some criteria. As a general connectivity it does not imply constraints, however subtypes of the relationship define the applicable object types for the connectivity relationship and the semantics of the particular connectivity.

                  + +
                  +HISTORY: New entity in IFC Release 2x. +
                  + +
                  " +966;IfcRelDeclares;" + +

                  The objectified relationship IfcRelDeclares handles the declaration of objects (subtypes of IfcObject) or properties (subtypes of IfcPropertyDefinition) to a project or project library (represented by IfcProject, or IfcProjectLibrary).

                  + +

                  The relationship handles the assignment of other objects, like IfcActor, or IfcTypeObject to the project, or project libary. The attribute RelatedDefinitions provides the references to the first level objects, that are the elements within the context. All other objects that relate to the first level objects are also defined in the context.

                  + +
                  +

                  NOTE 1  Every object (as subtype of IfcObject) has to be declared within the context of a single IfcProject, or of a IfcProjectLibrary assigned to a single IfcProject. This declaration is transitive. For example: the IfcWorkPlan as first level object is declared within the context of IfcProject via IfcRelDeclares, all related IfcWorkSchedule's are related to the context in a transitive way through IfcWorkPlan.

                  + +
                  + +
                  +

                  NOTE 2  The assignment excludes subtypes of IfcProduct's, these are assigned to the IfcProject using the spatial structure approach through IfcSpatialStructureElement(s), where the outer container element such as IfcSite or IfcBuilding has an IfcRelAggregates relationship with the IfcProject.

                  +
                  + +

                  The RelatingContext is the project, or project library that comprises all elements. The unit assignments and the presentation contexts defined at IfcProject or IfcProjectLibrary apply to all these elements.

                  + +
                  +HISTORY New entity in Release IFC2x4. +
                  + +
                  " +970;IfcContext;" + +

                  IfcContext is the generalization of a project context in which objects, type objects, property sets, and properties are defined. The IfcProject as subtype of IfcContext provides the context for all information on a construction project, it may include one or several IfcProjectLibrary as subtype of IfcContext to register the included libraries for the project.

                  + +

                  Context definitions can be named, using the inherited Name attribute, which should be a user recognizable key or number for the context. The LongName can add a full name. Further explanations to the context can be given using the inherited Description attribute.

                  + +
                  +HISTORY  New abstract entity in IFC2x4. +
                  + +

                  Relationship use definition

                  +

                  Contexts are declared by the relationship object that refers to the corresponding object:

                  +
                    +
                  • Project library to project: IfcProjectLibrary is assigned to IfcProject (both subtypes of using +IfcContext) by using IfcRelDeclares
                  • +
                  +

                  More specific relationships are introduced at the level of subtypes.

                  + +
                  " +979;IfcProject;" + +

                  IfcProject indicates the undertaking of some design, engineering, construction, or +maintenance activities leading towards a product. The project establishes the context for information to be exchanged or shared, and it may represent a construction project but does not have to. The IfcProject's main purpose in an exchange structure is to provide the root instance and the context for all other information items included.

                  +

                  The context provided by the IfcProject includes:

                  +
                    +
                  • the default units
                  • +
                  • the geometric representation context for exchange structures including shape representations +
                      +
                    • the world coordinate system
                    • +
                    • the coordinate space dimension
                    • +
                    • the precision used within the geometric representations, and
                    • +
                    • optionally the indication of the true north relative to the world coordinate system
                    • +
                    +
                  • +
                  + +
                  HISTORY  New Entity in IFC Release 1.0
                  + +
                  +IFC2x4 CHANGE  The attributes RepresentationContexts and UnitsInContext are made optional and are promoted to supertype IfcContext. +
                  + +

                  Relationship use definition

                  +

                  The IfcProject is used to reference the root of the spatial structure of a building (that serves as the primary project breakdown and is required to be hierarchical). The spatial structure elements are linked together, and to the IfcProject, by using the objectified relationship IfcRelAggregates. The IfcProject references them by its inverse relationship:

                  +
                    +
                  • IfcProject.Decomposes -- it shall be NIL, i.e. the +IfcProject shall not be decomposed into any parts.
                  • +
                  • IfcProject.IsDecomposedBy -- referencing +(IfcSite || IfcBuilding) by +IfcRelAggregates.RelatingObject. The IfcSite or +IfcBuilding referenced shall be the root of the spatial +structure.
                  • +
                  +

                  The IfcProject is also the context for other information about the construction project such as a work plan. Non-product structures are assigned by their first level object to IfcProject using the IfcRelDeclares relationship.

                  + +

                  The IfcProject provides the context for spatial elements and the associated products, and for work plans (or other non-product based) descriptions of the construction project. It is handled by two distinct relationship objects as shown in Figure 3.

                  +
                  NOTE   The spatial structure and the schedule structure can be decomposed. For example the IfcBuilding can be decomposed into IfcBuildingStorey's, and the IfcWorkPlan can be decomposed into IfcWorkSchedule's.
                  +
                  NOTE   The products and tasks can be decomposed further. For example the IfcCurtainWall can be decomposed into IfcMember and IfcPlate, the IfcTask can be decomposed into other IfcTask's.
                  +
                  NOTE   The products and tasks can have direct linking relationships. For example the IfcCurtainWall can be assigned to a IfcTask as an input or output for a construction schedule.
                  +
                  NOTE   The anomaly to use the composition structure through IfcRelAggregates for assigning the uppermost spatial container to IfcProject is due to upward compatibility reasons with earlier releases of this standard.
                  + + + + +
                  +

                  Figure 3 — Project spatial and work plan structure

                  + +

                  As shown in Figure 4, the IfcProject provides the context for project libraries that in return provide a context to the library items assigned to it. Product types are an example for items that can be included in a project library.

                  + + + + +

                  Figure 4 — Project spatial structure, products and product type library

                  + +

                  Informal propositions:

                  +
                    +
                  1. There shall only be one project within the exchange context. This is enforced by the global rule IfcSingleProjectInstance.
                  2. +
                  + +
                  " +984;IfcProjectLibrary;" +

                  IfcProjectLibrary collects all library elements that are included within a referenced project data set.

                  + +

                  Examples for project libraries include:

                  +
                    +
                  • type libraries (also called style or family libraries): a collection of subtypes of IfcTypeObject
                  • +
                  • property definition libraries: a collections of IfcPropertySetTemplate or IfcPropertyTemplates
                  • +
                  + +
                  +HISTORY New entity in IFC2x4. +
                  + +

                  Attribute use definition

                  +
                  +
                  SELF\IfcContext.RepresentationContext
                  +
                  Context of the representations used within the project library. When the project library includes shape representations for its library type objects, one or several geometric representation contexts need to be included that define the coordinate system, the coordinate space dimensions, and/or the precision factor.
                  +
                  +
                  SELF\IfcContext.UnitsInContext
                  +
                  Units locally assigned to measure types used within the context of this project library. + +
                  NOTE  It is generally discouraged to use a different length measure and plane angle measure in an included project library compared with the project itself. It may lead to unexpected results for the shape representation of items included in the project library.
                  + +
                  +
                  + +

                  Relationship use definition

                  + +

                  Instances of IfcProjectLibrary are assigned to the project context using the IfcRelDeclares relationship and accessible through the inverse attribute HasContext. Individual object types and property (set) templates are assigned to the IfcProjectLibrary using the IfcRelDeclares relationship and are accessible through the inverse attribute Declares.

                  + +

                  An IfcProjectLibrary may be decomposed into sub libraries using the relationship IfcRelNests. Sub libraries are accessed by the IfcProjectLibrary through the inverse attribute IsNestedBy.

                  + +
                  " +985;IfcRelDefinesByProperties;" + +

                  The objectified relationship +IfcRelDefinesByProperties defines the relationships +between property set definitions and objects. Properties are +aggregated in property sets. Property sets can be either directly +assigned to occurrence objects using this relationship, or +assigned to an object type and assigned via that type to +occurrence objects.

                  +

                  The IfcRelDefinesByProperties is a 1-to-N relationship, +as it allows for the assignment of one property set to a single +or to many objects. Those objects then share the same property +definition.

                  + +
                  +HISTORY New Entity in IFC Release 2.0. Has been renamed from IfcRelAssignsProperties in IFC Release 2x. +
                  + +
                  +IFC2x4 CHANGE The attribute RelatedObjects had been demoted from the supertype IfcRelDefines to IfcRelDefinesByProperties. +
                  + +
                  " +988;IfcRelDefinesByObject;" + +

                  The objectified relationship IfcRelDefinesByObject defines the relationship between an object taking part in an object type decomposition and an object occurrences taking part in an occurrence decomposition of that type.

                  +

                  The IfcRelDefinesByObject is a 1-to-N relationship, as it allows for the assignment of one declaring object information to a single or to many reflected objects. Those objects then share the same object property sets and, for subtypes of IfcProduct, the eventually assigned representation maps.

                  +

                  Only objects that take part in a type decomposition and in an occurrence decomposition of the same type can be connected by the IfcRelDefinesByObject relationship.

                  + +
                  +HISTORY New entity in IFC2x4. +
                  + +

                  Relationship use definition

                  + +

                  The IfcRelDefinesByObject links the decomposed object type part, also called the ""declaring part"" with the occurrence of that part inside the occurrence of the decomposed type, also called the ""reflected part"", as shown in Figure 6.

                  + + + + +

                  Figure 6 — Part definition relationships

                  + +

                  The IfcRelDefinesByObject can be used together with the shape representations of the product type as shown in Figure 7. The IfcShapeRepresentation of the ""declaring part"" is referenced by the ""reflected part"". The IfcObjectPlacement of the model occurrence (the whole) determines the position within the project context.

                  + + + + +

                  Figure 7 — Part definition relationships with shape representation

                  + +
                  " +991;IfcPropertySetTemplate;" + +

                  IfcPropertySetTemplate defines the template for all +dynamically extensible property sets represented by +IfcPropertySet. The property set template is a container +of property templates within a property tree. The individual +property templates are interpreted according to their Name +attribute and shall have no values assigned.

                  +
                  NOTE  By +convention an IfcPropertySetTemplate can also be used as a +template for an IfcElementQuantity, being a particular +type of a property set definition.
                  +

                  Property set templates can form part of a property library used +and declared within a project. Depending on the +TemplateType the IfcPropertySetTemplate defines a +template for:

                  +
                    +
                  • ""Pset_"" - occurrences of IfcPropertySet
                  • +
                  • ""QTO_"" - occurrences of IfcElementQuantity
                  • +
                  + +
                  +HISTORY New Entity in IFC2x4. +
                  + +

                  Relationship use definition

                  + +

                  The inherited HasContext inverse relation to IfcRelDeclares is used to declare the IfcPropertySetTemplate within a project library. If included in an exchange data set it can then be traversed through the IfcProjectLibrary.

                  + +

                  The Defines inverse relation to IfcRelDefinesByTemplate is provided to keep the definition relationship between the IfcPropertySetTemplate and the one to many IfcPropertySet's, for which it provides the template.

                  + +

                  Between IfcProperty's within the HasProperties set of IfcPropertySet having the same Name attribute value as the IfcPropertyTemplate's within the HasPropertyTemplates set of IfcPropertySetTemplate an implicit definition relationship is established that assigns the template to the individual properties.

                  + +

                  Figure 5 illustrates relationships used for property set templates.

                  + + + + + + + +
                  +""property

                  Figure 5 — Property set template relationships

                  +
                  " +998;IfcPropertyTemplateDefinition;" + +

                  IfcPropertyTemplateDefinition is a generalization of +all property and property set templates. Templates define the +collection, types, names, applicable measure types and units of +individual properties used in a project. The property template +definition can be either:

                  +
                  +

                  Property set template - +IfcPropertySetTemplate, a collection of property templates +that determine the definition of properties used within a project +context.

                  +

                  Property template - +IfcPropertyTemplate, a single template that determines the +definition of a particular property used in the same project +context. The template may determine the name, description, data +type, the unit, or a standard expression for each property that is +based on that template.

                  +
                  +

                  The subtypes of IfcPropertyTemplateDefinition are +declared within a project context. The uppermost template +definition (e.g. the IfcPropertySetTemplate including +several IfcPropertyTemplate's) should be related to the +context, either IfcProject, or IfcProjectLibrary, +using the inherited HasContext inverse attribute.

                  + +
                  +HISTORY  New Entity in IFC2x4. +
                  + +
                  " +1001;IfcPropertyTemplate;" + +

                  The IfcPropertyTemplate is an abstract supertype +comprising the templates for all dynamically extensible properties, +either as an IfcComplexPropertyTemplate, or an +IfcSimplePropertyTemplate. These templates determine the +structure of:

                  +
                    +
                  • in case of IfcComplexPropertyTemplate +
                      +
                    • an IfcComplexProperty
                    • +
                    • an IfcPhysicalComplexQuantity
                    • +
                    +
                  • +
                  • in case of IfcSimplePropertyTemplate +
                      +
                    • a subtype of IfcSimpleProperty
                    • +
                    • a subtype of IfcPhysicalSimpleQuantity
                    • +
                    +
                  • +
                  +

                  The individual property templates are interpreted according to +their Name attribute and may have a predefined property +type, property unit, and property data type. A template however +shall not have measure values, or quantity values assigned. .

                  + +
                  +NOTE Property templates can form part of a property library used and attached as part of a project library. In general the IfcPropertySetTemplate, containing the subtypes of IfcPropertyTemplate would be directly linked to the IfcProjectLibrary. +
                  + +
                  +HISTORY New Entity in IFC2x4. +
                  + +
                  " +1006;IfcComplexPropertyTemplate;" +

                  The IfcComplexPropertyTemplate defines the template for +all complex properties, either the IfcComplexProperty's, +or the IfcPhysicalComplexQuantity's. The individual +complex property templates are interpreted according to their +Name attribute and and optional UsageName +attribute.

                  + +
                  +HISTORY  New entity in IFC2x4. +
                  + +
                  " +1015;IfcSimplePropertyTemplate;" + +

                  The IfcSimplePropertyTemplate defines the template for +all dynamically extensible properties, either the subtypes of +IfcSimpleProperty, or the subtypes of +IfcPhysicalSimpleQuantity. The individual property +templates are interpreted according to their Name +attribute and may have a predefined template type, property units, +and property data types. The correct interpretation of the +attributes:

                  +
                    +
                  • PrimaryUnit
                  • +
                  • SecondaryUnit
                  • +
                  • PrimaryDataType
                  • +
                  • SecondaryDataType
                  • +
                  +

                  is determined by the TemplateType. The +TemplateType also controls, which subtype of either +IfcSimpleProperty or IfcPhysicalSimpleQuantity +shall be used for property occurrences corresponding to this +template.

                  + +
                  +HISTORY  New entity in IFC2x4. +
                  + +

                  Relationship use definition

                  +

                  The IfcSimplePropertyTemplate is part of the set of +templates included in the IfcPropertySetTemplate. The +template can be accessed throught the inverse attribute +PartOfPsetTemplate The IfcPropertySetTemplate may +define one or several instances of IfcPropertySet (or +IfcElementQuantity). The definition assignment is +established by the objectified relationship +IfcRelDefinesByTemplate.

                  +

                  There is no direct link between an +IfcSimplePropertyTemplate and a subtype of either +IfcSimpleProperty or IfcPhysicalSimpleQuantity. +The definition relationship between the template and the individual +properties (or quantities) is established by the Name +attributes.

                  +
                  +

                  Constraints at +IfcPropertySetTemplate and IfcPropertySet (and +IfcElementQuantity) guarantee that the Name +attributes of included property templates and individual properties +are unique.

                  +
                  + + + + +
                  +""IfcSimplePropertyTemplate

                  Figure 9 — Property template relationships

                  + +
                  " +1045;IfcPreDefinedPropertySet;" + +

                  IfcPreDefinedPropertySet +is a generalization of all statically defined property sets that +are assigned to an object or type object. The statically or +pre-defined property sets are entities with a fixed list of +attributes having particular defined data types.

                  + +

                  IfcPreDefinedPropertySet's can be assigned to objects +and object types but do not have a defining property set +template.

                  + +
                  +HISTORY New Entity in IFC2x4 +
                  + +

                  Relationship use definition

                  +

                  Property sets are related to other objects by using the +relationship object that refers to the corresponding object:

                  +
                    +
                  • Occurrence Object: IfcRelDefinesByProperties +using the inverse attribute DefinesOccurrence.
                  • +
                  • Type Object: using a direct link by inverse attribute +DefinesType.
                  • +
                  + +
                  " +1046;IfcProxy;" + +

                  IfcProxy is intended to be a kind of a container for wrapping objects which are defined by associated properties, which may or may not have a geometric representation and placement in space. A proxy may have a semantic meaning, defined by the Name attribute, and property definitions, attached through the property assignment relationship, which definition may be outside of the definitions given by the current release of IFC.

                  + +

                  The ProxyType may give an indication to which high level semantic breakdown of object the semantic definition of the proxy relates to. the Tag attribute may be used to assign a human or system interpretable identifier (such as a serial number or bar code).

                  + +
                  +

                  NOTE 1  Given that only a +limited number of semantic constructs can be formally defined within +IFC (and it will never be possible to define all), there has to be a +mechanism for capturing those constructs that are not (yet) defined by +IFC.
                  +
                  +NOTE 2  Product proxies are a +mechanism that allows to exchange data that is part of the project but +not necessarily part of the IFC model. Those proxies may have geometric +representations assigned.

                  +
                  + +
                  +HISTORY  New entity in IFC Release 1.5. +
                  + +
                  " +1055;IfcRelFlowControlElements;" + +

                  Objectified relationship between a distribution flow element occurrence instance and one-to-many control element occurrence instances indicating that the control element(s) sense or control some aspect of the flow element. It is applied to IfcDistributionFlowElement and IfcDistributionControlElement.

                  + +

                  This relationship may be used to indicate an operation relationship such as an actuator operating a valve, damper, or switch. It may also be used to indicate a sensing relationship such as a sensor detecting conditions of fluid flow.

                  + +

                  This relationship implies a sensing or controlling relationship; if elements are merely connected without any control relationship, then IfcRelConnectsElements should be used.

                  +
                  + + HISTORY: New entity in IFC R2x.
                  +
                  +
                  +
                  " +1058;IfcDistributionControlElement;" +

                  The distribution element IfcDistributionControlElement defines occurrence elements of a building automation control system that are used to impart control over elements of a distribution system.

                  + +

                  This class defines elements of a building automation control system. These are typically used to control distribution system elements to maintain variables such as temperature, humidity, pressure, flow, power, or lighting levels, through the modulation, staging or sequencing of mechanical or electrical devices. The three general functional categories of control elements are as follows:

                  + +
                    +
                  • Impart control over flow control elements (IfcFlowController) in a distribution system such as dampers, valves, or relays, typically through the use of actuation (IfcActuator).
                  • +
                  • Sensing elements (IfcSensor) that measure changes in the controlled variable such as temperature, humidity, pressure, or flow.
                  • +
                  • Controllers (IfcController) typically classified according to the control action they seek to perform and generally responsible for making decisions about the elements under control.
                  • +
                  + +

                  Since this class and its subtypes typically relate to many different distribution flow elements (IfcDistributionFlowElement), the objectified relationship IfcRelFlowControlElements has been provided to relate control and flow elements as required.

                  + +
                  +IFC2x4 CHANGE: ControlElementId attribute deleted; replaced by classification usage. +HISTORY: New entity in IFC R2.0.
                  +
                  + +

                  Type Use Definition

                  +

                  IfcDistributionControlElement defines the occurrence of any distribution control element; common information about distribution control element types is handled by IfcDistributionControlElementType. The IfcDistributionControlElementType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. The IfcDistributionControlElementType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. If the IfcDistributionControlElementType has ports or aggregated elements, such objects are reflected at the IfcDistributionControlElement occurrence using the IfcRelDefinesByObject relationship. Direct instantiation of IfcDistributionControlElement with IfcObject.ObjectType asserted provides the meaning of a distribution control element proxy.

                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Property sets may also be specified at the IfcDistributionControlElementType, defining the common property data for all occurrences of the same type. They are then accessible by the IsTypedBy inverse attribute pointing to IfcDistributionControlElementType.HasPropertySets. If both are given, then the properties directly defined at IfcDistributionControlElement override the properties defined at IfcDistributionControlElementType. Refer to the documentation at the supertype IfcDistributionElement and ancestors for inherited property set definitions.

                  + +

                  Classification Use Definition

                  +

                  In addition to general product and project classification (UniFormat, etc.), classifications may also be applied to indicate a device address or addressing scheme using IfcRelAssociatesClassification where RelatedObjects contains the IfcDistributionControlElement and RelatingClassification refers to an IfcClassification or IfcClassificationReference.

                  +
                    +
                  • IfcClassification: Indicates an addressing scheme managed by the device where ReferenceTokens defines the format of the address to be specified at IfcClassificationReference.ItemReference. A classification hierarchy may optionally be provided indicating detected or provisioned device addresses.
                  • +
                  • IfcClassificationReference: Indicates the address of the control element where Identification uniquely identifies the element within the control system as determined by the ClassificationSource. Several examples are illustrated: +
                      +
                    • 'BACnet': BACnetObjectIdentifier in the decimal form '12.15' (Digital Input #15) indicating type ID and instance ID.
                    • +
                    • 'IP': IP Address in the decimal form '192.168.1.2' such as for an IPv4 network.
                    • +
                    • 'OPC': Hierarchical ItemID in the alphanumeric form 'B204.Tank2.Temperature'
                    • +
                    • 'X-10': Alphabetic and numeric code in the form 'B12' (House B, Device 12) indicating House Code and Device Code.
                    • +
                    +
                  • +
                  +

                  Figure 147 illustrates classification usage.

                  + + + +

                  Figure 147 — Distribution control classification

                  + +

                  Composition Use Definition

                  +

                  The IfcDistributionControlElement may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcDistributionControlElement and RelatedObjects contains one or more components. Likewise, a control element may be aggregated within another element. For example, a thermostat may contain temperature sensors, and a programmable logic controller may contain virtual (software-based) control elements. Standard types for composition are defined at subtypes.

                  + +

                  Connection Use Definition

                  +

                  The IfcDistributionControlElement may be connected to other objects as follows using the indicated relationship:

                  +
                    +
                  • IfcSpatialStructureElement (IfcRelContainedInSpatialStructure) : Indicates the spatial location containing the element. If an element is aggregated within another element, then only the top-level element participates in this relationship.
                  • +
                  • IfcElement (IfcRelConnectsElements) : Indicates physical connectivity with another element (but not embedding or flow control), such as a sensor attached to a wall. IfcRelConnectsElements.RelatingElement refers to the anchored side (for example, wall hosting sensor).
                  • +
                  • IfcDistributionPort (IfcRelConnectsPortToElement) : Indicates ports on the element which may be connected to other elements for control signal transmission or electric power. Standard port names, types, and directions are defined at subtypes.
                  • +
                  • IfcDistributionFlowElement (IfcRelFlowControlElements) : Indicates a flow element is sensed or controlled by the control element, such as a tank for a level sensor or a valve for an actuator.
                  • +
                  + +

                  Assignment Use Definition

                  +

                  The IfcDistributionControlElement may be assigned to the following entities using relationships as indicated:

                  + +

                  The IfcDistributionControlElement may have assignments of its own using the IfcRelAssignsToProduct relationship where RelatingProduct refers to the IfcDistributionControlElement and RelatedObjects contains one or more objects of the following types:

                  +
                    +
                  • IfcTask: Indicates tasks used to purchase, install, renovate, demolish, operate, or otherwise act upon the element. If the element has a type, available task types are assigned to the element type.
                  • +
                  • IfcProcedure: Indicates procedures used to operate the element. If the element has a type, available procedure types are assigned to the element type.
                  • +
                  • IfcEvent: Indicates events raised by the element, sequenced by procedures to be followed. If the element has a type, available event types are assigned to the element type.
                  • +
                  + +

                  Material Use Definition

                  +

                  The material of the IfcDistributionControlElement is defined using one of the following entities:

                  +
                    + +
                  • IfcMaterialConstituentSet: For elements containing multiple materials, this indicates materials at named aspects. +
                  • + +
                  • IfcMaterial: For elements comprised of a single material, this indicates the material.
                  • +
                  + +

                  The material is attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDistributionControlElementType, defining the common attribute data for all occurrences of the same type. Standard names and material types are defined at subtypes.

                  + +

                  Representation Use Definition

                  +

                  The following shape representations are supported for subtypes of IfcDistributionControlElement, distinguished by IfcShapeRepresentation.RepresentationIdentifier:

                  + +
                    +
                  • 'Footprint': Represents the 2D footprint outline of the item having IfcShapeRepresentation.RepresentationType of 'GeometricCurveSet' and containing a single IfcGeometricCurveSet consisting of one or more IfcCurve subtypes such as IfcPolyline, IfcTrimmedCurve, IfcCompositeCurve, or IfcCircle.
                  • + +
                  • 'Body': Represents the 3D shape of the item having IfcShapeRepresentation.RepresentationType of 'SurfaceModel', 'SolidModel', or any solid model specializations including 'Brep', 'AdvancedBrep', 'SweptSolid', 'AdvancedSweptSolid', 'CSG', 'Clipping', or 'SectionedSpine').
                  • + +
                  • 'Clearance': Represents the 3D clearance volume of the item having RepresentationType of 'Surface3D'. Such clearance region indicates space that should not intersect with the 'Body' representation of other elements, though may intersect with the 'Clearance' representation of other elements. The particular use of clearance space may be for safety, maintenance, or other purpose.
                  • +
                  + +

                  For all representations, if a IfcDistributionControlElement occurrence is defined by a IfcDistributionControlElementType having a representation of the same identifier, then 'MappedRepresentation' should be used at the occurrence unless overridden.

                  + +

                  If materials are defined, geometry of each representation (most typically the 'Body' representation) may be organized into shape aspects where styles may be derived by correlating IfcShapeAspect.Name to a corresponding material (IfcMaterialConstituent.Name).

                  + +
                  " +1060;IfcDistributionPort;" + +

                  A distribution port is an inlet or outlet of a product through which a particular substance may flow.

                  + +

                  Distribution ports are used for passage of solid, liquid, or gas substances, as well as electricity for power or communications. Flow segments (pipes, ducts, cables) may be used to connect ports across products. Distribution ports are defined by system type and flow direction such that for two ports to be connected, they must share the same system type and have opposite flow directions (one side being a SOURCE and the other being a SINK). Ports are similar to openings in that they do not have any visible geometry; such geometry is captured at the shape representation of the enclosing element or element type. Ports may have shape representations that indicate the position, orientation, and cross-section of the connection.

                  + +
                  HISTORY: New entity in IFC2x2
                  + +

                  Property Set Use Definition

                  +

                  The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Refer to the documentation at the supertype IfcPort and ancestors for inherited property set definitions.

                  +

                  The following property set definitions are applicable to this entity:

                  + +

                  The following property set definitions are applicable to this entity according to the PredefinedType attribute:

                  + +

                  The following property set definitions are applicable to IfcPerformanceHistory, for which objects are assigned:

                  + + +

                  Material Use Definition

                  +

                  The material of the IfcDistributionPort is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

                  +
                    +
                  • 'Media': The solid, liquid, or gas media passing through the port.
                  • +
                  + +

                  Composition Use Definition

                  +

                  The IfcDistributionPort may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcDistributionPort and RelatedObjects contains one or more components. Composition use is defined for the following predefined types: +

                    +
                  • AUDIOVISUAL: May contain IfcDistributionPort components having PredefinedType AUDIOVISUAL. If needed, audio-visual ports may be aggregated into specific streams (channels).
                  • CONTROL: May contain IfcDistributionPort components having PredefinedType SIGNAL. If needed, control ports may be aggregated into signal lines for indicating pinout specification.
                  • DATA: May contain IfcDistributionPort components having PredefinedType SIGNAL. If needed, data ports may be aggregated into signal lines for indicating pinout specification.
                  • ELECTRICAL: May contain IfcDistributionPort components having PredefinedType SIGNAL. If needed, electrical ports may be aggregated into modulated signals for data or lighting control.
                  • ELECTROACCOUSTIC: May contain IfcDistributionPort components having PredefinedType ELECTROACCOUSTIC. If needed, speaker ports may be aggregated into streams (channels) for each speaker.
                  • TELEPHONE: May contain IfcDistributionPort components having PredefinedType TELEPHONE. If needed, telephone ports may be aggregated for each line.
                  + +

                  Connection Use Definition

                  +

                  The IfcDistributionPort may be connected to other objects as follows using the indicated relationship:

                  +
                    +
                  • IfcDistributionElement (IfcRelConnectsPortToElement) : Indicates the host element or element type containing the port.
                  • +
                  • IfcDistributionPort (IfcRelConnectsPorts) : Indicates a connection to another port having the same type and opposite flow direction. +For port connections between elements, +the RelatingPort is set to a port having FlowDirection=SOURCE and +the RelatedPort is set to a port having FlowDirection=SINK. +For aggregation scenarios, ports on a device may be mapped to aggregated devices within, +in which case ports on the outer device indicate a single FlowDirection but have an additional connection internally +to a port on an aggregated inner device. +Refer to IfcUnitaryEquipment for an example.
                  • +
                  + +

                  Figure 149 illustrates distribution port connectivity.

                  + + + + +

                  Figure 149 — Distribution port connectivity

                  + +

                  Assignment Use Definition

                  +

                  The IfcDistributionPort may be assigned to the following entities using relationships as indicated:

                  + +

                  The IfcDistributionPort may have assignments of its own using the IfcRelAssignsToProduct relationship where RelatingProduct refers to the IfcDistributionPort and RelatedObjects contains one or more objects of the following types:

                  + +

                  Representation Use Definition

                  +

                  The representation of IfcDistributionPort is given by IfcProductDefinitionShape, allowing multiple shape and topology representations. Included are:

                  +
                    +
                  • IfcShapeRepresentation: The optional shape representation describes the connection volume and supports indication of the port position and orientation. The position is typically the midpoint of the physical connection, and the orientation points in the flow direction normal to the physical connection. Upon connecting elements through ports with rigid connections, each object is aligned such that the effective Location, Axis, and RefDirection of each port is aligned to be equal. +
                      +
                    • 'Body': The shape of the port.
                    • +
                    +
                  • +
                  + +
                  " +1106;IfcDistributionControlElementType;" +

                  The element type IfcDistributionControlElementType defines a list of commonly shared property set definitions of an element and an optional set of product representations. It is used to define an element specification (the specific product information that is common to all occurrences of that product type).

                  + +

                  Distribution control element types (or the instantiable subtypes) may be exchanged without being already assigned to occurrences.

                  + +

                  The occurrences of the IfcDistributionControlElementType are represented by instances of IfcDistributionControlElement or its subtypes.

                  + +
                  +HISTORY: New entity in IFC Release 2x2.
                  +
                  + + +

                  Declaration Use Definition

                  +

                  The IfcDistributionControlElementType may be declared within a project or project library using IfcRelDeclares where RelatingContext refers to the project or library and RelatedDefinitions includes the element type. Inclusion within IfcProject indicates the type is editable within the direct project and may be available to other referencing projects that may incorporate the type. Inclusion within IfcProjectLibrary indicates the type is incorporated from a referenced project. Default units and coordinate systems (used for representations, materials, and property sets) are indicated by the declaring project or library.

                  + +

                  Classification Use Definition

                  +

                  The IfcDistributionControlElementType may be classified using IfcRelAssociatesClassification where RelatingClassification refers to an IfcClassificationReference indicating a classification notation. Classifications may refer to industry standards such as MasterFormat, OmniFormat, or UniFormat. Classifications may also refer to organization-specific, project-specific, or system-specific designations. Classification reference identification schemes are described by IfcClassification.ReferenceTokens.

                  + +

                  Document Use Definition

                  +

                  The IfcDistributionControlElementType may be documented using IfcRelAssociatesDocument where RelatingDocument refers to an IfcDocumentReference indicating content within a document, or IfcDocumentInformation indicating an entire document. Document information may refer to arbitrary attachments such as text or multimedia, while document references may refer to items within particular formats (such as XML element IDs) where there is need to synchronize document information with model information. Document reference identification schemes depend on the particular document format.

                  + +

                  Library Use Definition

                  +

                  The IfcDistributionControlElementType may be published to a model server using IfcRelAssociatesLibrary where RelatingLibrary refers to an IfcLibraryReference indicating the unique identification within the published project. If the published project is IFC format, then IfcLibraryReference.Identification shall match IfcRoot.GlobalID of the published (master) project, using the same encoding as described for IfcGloballyUniqueId. Multiple library references may be provided to indicate alternate names and descriptions for particular languages. If the element type is declared within IfcProject, then IfcLibraryInformation.Location and IfcLibraryInformation.Version indicate the URL and version as last published. If the element type is declared within IfcProjectLibrary, then the library information indicates the location and version of the definition as last retrieved.

                  + +

                  Composition Use Definition

                  +

                  The IfcDistributionControlElementType may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcDistributionFlowElementType and RelatedObjects contains one or more components. For example, a thermostat type may be decomposed into temperature sensors. Standard types for composition are defined at occurrences for subtypes.

                  + +

                  Connection Use Definition

                  +

                  The IfcDistributionControlElementType may be connected to other objects as follows using the indicated relationship:

                  + + +

                  Assignment Use Definition

                  +

                  The IfcDistributionControlElementType may have assignments of its own using the IfcRelAssignsToProduct relationship where RelatingProduct refers to the IfcDistributionControlElementType and RelatedObjects contains one or more objects of the following types:

                  +
                    +
                  • IfcTaskType: Indicates task types available to purchase, install, renovate, demolish, operate, or otherwise act upon occurrences of the element type. Such task types may be instantiated as task occurrences assigned to occurrences of the element type. Prices (such as for purchasing or shipping) may be established by resource types assigned to task types.
                  • +
                  • IfcProcedureType: Indicates procedure types available to operate occurrences of the element type. Such procedure types may be instantiated as procedure occurrences assigned to occurrences of the element type.
                  • +
                  • IfcEventType: Indicates event types available to be raised by occurrences of the element, sequenced by procedures to be followed. Such event types may be instantiated as event occurrences assigned to occurrences of the element type.
                  • +
                  + +

                  Material Use Definition

                  +

                  The material of the IfcDistributionControlElementType is defined using one of the following entities:

                  +
                    +
                  • IfcMaterialConstituentSet: For elements containing multiple materials, this indicates materials at named aspects. +
                  • +
                  • IfcMaterial: For elements comprised of a single material, this indicates the material.
                  • +
                  +

                  The material is attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute.

                  + +

                  Representation Use Definition

                  +

                  The following shape representations are supported for subtypes of IfcDistributionControlElementType, distinguished by IfcShapeRepresentation.RepresentationIdentifier:

                  +
                    + +
                  • 'Footprint': Represents the 2D footprint outline of the item having IfcShapeRepresentation.RepresentationType of 'GeometricCurveSet' and containing a single IfcGeometricCurveSet consisting of one or more IfcCurve subtypes such as IfcPolyline, IfcTrimmedCurve, IfcCompositeCurve, or IfcCircle.
                  • + +
                  • 'Body': Represents the 3D shape of the item having IfcShapeRepresentation.RepresentationType of 'SurfaceModel', 'SolidModel', or any solid model specializations including 'Brep', 'AdvancedBrep', 'SweptSolid', 'AdvancedSweptSolid', 'CSG', 'Clipping', or 'SectionedSpine').
                  • + +
                  • 'Clearance': Represents the 3D clearance volume of the item having RepresentationType of 'Surface3D'. Such clearance region indicates space that should not intersect with the 'Body' representation between element occurrences, though may intersect with the 'Clearance' representation of other element occurrences. The particular use of clearance space may be for safety, maintenance, or other purpose.
                  • +
                  + +
                  + +NOTE: The product representations are defined as representation maps (at the level of the supertype IfcTypeProduct, which get assigned by an element occurrence instance through the IfcShapeRepresentation.Item[1] being an IfcMappedItem. + +
                  + + + +
                  " +1107;IfcDistributionFlowElementType;" +

                  The element type IfcDistributionFlowElementType defines a list of commonly shared property set definitions of an element and an optional set of product representations. It is used to define an element specification (the specific product information that is common to all occurrences of that product type).

                  + +

                  Distribution flow element types (orthe instantiable subtypes) may be exchanged without being already assigned to occurrences.

                  + +

                  The occurrences of the IfcDistributionFlowElementType are represented by instances of IfcDistributionFlowElement or its subtypes.

                  + +
                  HISTORY: New entity in IFC Release 2x2.
                  + +

                  Declaration Use Definition

                  +

                  The IfcDistributionFlowElementType may be declared within a project or project library using IfcRelDeclares where RelatingContext refers to the project or library and RelatedDefinitions includes the element type. Inclusion within IfcProject indicates the type is editable within the direct project and may be available to other referencing projects that may incorporate the type. Inclusion within IfcProjectLibrary indicates the type is incorporated from a referenced project. Default units and coordinate systems (used for representations, materials, and property sets) are indicated by the declaring project or library.

                  + +

                  Classification Use Definition

                  +

                  The IfcDistributionFlowElementType may be classified using IfcRelAssociatesClassification where RelatingClassification refers to an IfcClassificationReference indicating a classification notation. Classifications may refer to industry standards such as MasterFormat, OmniFormat, or UniFormat. Classifications may also refer to organization-specific, project-specific, or system-specific designations. Classification reference identification schemes are described by IfcClassification.ReferenceTokens.

                  + +

                  Document Use Definition

                  +

                  The IfcDistributionFlowElementType may be documented using IfcRelAssociatesDocument where RelatingDocument refers to an IfcDocumentReference indicating content within a document, or IfcDocumentInformation indicating an entire document. Document information may refer to arbitrary attachments such as text or multimedia, while document references may refer to items within particular formats (such as XML element IDs) where there is need to synchronize document information with model information. Document reference identification schemes depend on the particular document format.

                  + +

                  Library Use Definition

                  +

                  The IfcDistributionFlowElementType may be published to a model server using IfcRelAssociatesLibrary where RelatingLibrary refers to an IfcLibraryReference indicating the unique identification within the published project. If the published project is IFC format, then IfcLibraryReference.Identification shall match IfcRoot.GlobalID of the published (master) project, using the same encoding as described for IfcGloballyUniqueId. Multiple library references may be provided to indicate alternate names and descriptions for particular languages. If the element type is declared within IfcProject, then IfcLibraryInformation.Location and IfcLibraryInformation.Version indicate the URL and version as last published. If the element type is declared within IfcProjectLibrary, then the library information indicates the location and version of the definition as last retrieved.

                  + +

                  Figure 148 illustrates a project containing a light fixture in a building, where the definition of the light fixture is obtained from an external project.

                  + + + + +

                  Figure 148 — Distribution flow element library

                  + +

                  Composition Use Definition

                  +

                  The IfcDistributionFlowElementType may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcDistributionFlowElementType and RelatedObjects contains one or more components. For example, a cable type may be decomposed into wires. Standard types for composition are defined at occurrences for subtypes.

                  + +

                  Connection Use Definition

                  +

                  The IfcDistributionFlowElementType may be connected to other objects as follows using the indicated relationship:

                  + + +

                  Assignment Use Definition

                  +

                  The IfcDistributionFlowElementType may have assignments of its own using the IfcRelAssignsToProduct relationship where RelatingProduct refers to the IfcDistributionFlowElementType and RelatedObjects contains one or more objects of the following types:

                  +
                    +
                  • IfcTaskType: Indicates task types available to purchase, install, renovate, demolish, operate, or otherwise act upon occurrences of the element type. Such task types may be instantiated as task occurrences assigned to occurrences of the element type. Prices (such as for purchasing or shipping) may be established by resource types assigned to task types.
                  • +
                  • IfcProcedureType: Indicates procedure types available to operate occurrences of the element type. Such procedure types may be instantiated as procedure occurrences assigned to occurrences of the element type.
                  • +
                  • IfcEventType: Indicates event types available to be raised by occurrences of the element, sequenced by procedures to be followed. Such event types may be instantiated as event occurrences assigned to occurrences of the element type.
                  • +
                  + +

                  Material Use Definition

                  +

                  The material of the IfcDistributionFlowElementType is defined using one of the following entities:

                  +
                    +
                  • IfcMaterialProfileSet: For elements having a constant cross-section, this defines the material profile which may be used to generate the 'Body' representation at occurrences (for parametric definitions not having representation), or for analysis purposes.
                  • +
                  • IfcMaterialConstituentSet: For elements containing multiple materials, this indicates materials at named aspects. +
                  • +
                  • IfcMaterial: For elements comprised of a single material, this indicates the material.
                  • +
                  +

                  The material is attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute.

                  + + +

                  Representation Use Definition

                  +

                  The following shape representations are supported for subtypes of IfcDistributionFlowElementType, distinguished by IfcShapeRepresentation.RepresentationIdentifier:

                  + +
                    + +
                  • 'Axis': Represents the 3D flow path of the item having IfcShapeRepresentation.RepresentationType of 'Curve3D' and containing a single IfcBoundedCurve subtype such as IfcPolyline, IfcTrimmedCurve, or IfcCompositeCurve. For elements containing directional ports (IfcDistributionPort with FlowDirection of SOURCE or SINK), the direction of the curve indicates direction of flow where a SINK port is positioned at the start of the curve and a SOURCE port is positioned at the end of the curve. This representation is most applicable to flow segment types (pipes, ducts, cables), however may be used at other elements to define a primary flow path if applicable.
                  • + +
                  • 'Footprint': Represents the 2D footprint outline of the item having IfcShapeRepresentation.RepresentationType of 'GeometricCurveSet' and containing a single IfcGeometricCurveSet consisting of one or more IfcCurve subtypes such as IfcPolyline, IfcTrimmedCurve, IfcCompositeCurve, or IfcCircle.
                  • + +
                  • 'Body': Represents the 3D shape of the item having IfcShapeRepresentation.RepresentationType of 'SurfaceModel', 'SolidModel', or any solid model specializations including 'Brep', 'AdvancedBrep', 'SweptSolid', 'AdvancedSweptSolid', 'CSG', 'Clipping', or 'SectionedSpine').
                  • + +
                  • 'Clearance': Represents the 3D clearance volume of the item having RepresentationType of 'Surface3D'. Such clearance region indicates space that should not intersect with the 'Body' representation between element occurrences, though may intersect with the 'Clearance' representation of other element occurrences. The particular use of clearance space may be for safety, maintenance, or other purpose.
                  • +
                  + +
                • 'Lighting': Represents the light emission of the item having IfcShapeRepresentation.RepresentationType of 'LightSource' and containing one or more IfcLightSource subtypes. This representation is most applicable to lamps and light fixtures, however may be used at other elements that emit light. +
                + +

                If an element type is defined parametrically (such as a flow segment type defining common material profile but no particular length or path), then no representations shall be asserted at the type.

                + +
                + +NOTE: The product representations are defined as representation maps (at the level of the supertype IfcTypeProduct, which get assigned by an element occurrence instance through the IfcShapeRepresentation.Item[1] being an IfcMappedItem. + +
                + + +" +1117;IfcEnergyConversionDeviceType;" +

                The element type IfcEnergyConversionType defines a list of commonly shared property + set definitions of an energy conversion device and an optional set of product representations. + It is used to define an energy conversion device specification (i.e. the specific product + information, that is common to all occurrences of that product type).

                + +
                + + NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + get assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. + +
                + +

                A energy conversion type is used to define the common properties of a + energy conversion device that may be applied to many occurrences of that type. +An energy conversion device is a building systems device that converts energy from one form into another such +as a boiler (i.e., combusting gas to heat water), chiller (i.e., using a refrigeration cycle to cool a +liquid), or a cooling coil (i.e., using the phase-change characteristics of a refrigerant to cool air). + Energy conversion types (or the instantiable subtypes) may be exchanged + without being already assigned to occurrences.

                + +

                The occurrences of the IfcEnergyConversionType are represented + by instances of IfcEnergyConversionDevice.

                + +
                + + HISTORY: New entity in IFC Release 2x2.
                +
                +
                + +
                " +1118;IfcFlowMovingDeviceType;" +

                The element type IfcFlowMovingDeviceType defines a list of commonly shared property + set definitions of a flow moving device and an optional set of product representations. + It is used to define a flow moving device specification (i.e. the specific product + information, that is common to all occurrences of that product type).

                + +
                + + NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + get assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. + +
                + +

                A flow moving type is used to define the common properties of a + flow moving device that may be applied to many occurrences of that type. +A flow moving device is a device that is used to produce a pressure differential in a distribution system, +such as a pump, fan, compressor, etc. + Flow moving types (or the instantiable subtypes) may be exchanged + without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowMovingDeviceType are represented + by instances of IfcFlowMovingDevice.

                + +
                + + HISTORY: New entity in IFC Release 2x2.
                +
                +
                + +
                " +1119;IfcFlowControllerType;" +

                The element type IfcFlowControllerType defines a list of commonly shared property + set definitions of a flow controller and an optional set of product representations. + It is used to define a flow controller specification (i.e. the specific product + information, that is common to all occurrences of that product type).

                + +
                + + NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + get assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. + +
                + +

                A flow controller type is used to define the common properties of a + flow controller that may be applied to many occurrences of that type. +A flow controller is a device that regulates flow within a distribution system, such as a valve in a piping +system, modulating damper in an air distribution system, or electrical switch in an electrical distribution +system. Flow controller types (or the instantiable subtypes) may be exchanged + without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowControllerType are represented + by instances of IfcFlowController or its subtypes.

                + +
                + + HISTORY: New entity in IFC Release 2x2.
                +
                +
                + +
                " +1120;IfcFlowSegmentType;" +

                The element type IfcFlowSegmentType defines a list of commonly shared property + set definitions of a flow segment and an optional set of product representations. + It is used to define a flow segment specification (i.e. the specific product + information, that is common to all occurrences of that product type).

                + +
                + + NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + get assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. + +
                + +

                A flow segment type is used to define the common properties of a + flow segment that may be applied to many occurrences of that type. +A flow segment is a section of a distribution system, such as a duct, pipe, conduit, etc. that typically has +only two ports. + Flow segment types (or the instantiable subtypes) may be exchanged + without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowSegmentType are represented + by instances of IfcFlowSegment or its subtypes.

                + +
                + + HISTORY: New entity in IFC Release 2x2.
                +
                +
                + + +

                Material Use Definition

                +

                The material of the IfcDistributionFlowSegmentType is defined using one of the following entities:

                +
                  + +
                • IfcMaterialProfileSet : This defines the material cross section which may be used to generate the 'Body' representation at occurrences (for parametric definitions not having representation), or for analysis purposes.
                • + +
                • IfcMaterialConstituentSet : For elements containing multiple materials where profiles are not applicable, this indicates materials at named aspects. +
                • + +
                • IfcMaterial : For elements comprised of a single material where profiles are not applicable, this indicates the material.
                • +
                + + +
                " +1121;IfcFlowFittingType;" +

                The element type IfcFlowFittingType defines a list of commonly shared property + set definitions of a flow fitting and an optional set of product representations. + It is used to define a flow fitting specification (i.e. the specific product + information, that is common to all occurrences of that product type).

                + +
                + + NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + get assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. + +
                + +

                A flow fitting type is used to define the common properties of a + flow fitting that may be applied to many occurrences of that type. +A flow fitting is a device that is used to interconnect flow segments or other fittings within a distribution +system, such as a tee in a ducted system that branches flow into two directions, a junction box in an +electrical distribution system, etc. + Flow fitting types (or the instantiable subtypes) may be exchanged + without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowFittingType are represented + by instances of IfcFlowFitting or its subtypes.

                + +
                + + HISTORY: New entity in IFC Release 2x2.
                +
                +
                + +
                " +1122;IfcFlowStorageDeviceType;" +

                The element type IfcFlowStorageDeviceType defines a list of commonly shared property set definitions of a flow storage device and an optional set of product representations. It is used to define a flow storage device specification (the specific product information that is common to all occurrences of that product type).

                + +

                A flow storage device is a device used for the temporary storage of a fluid (such as a tank) or the voltage potential induced by the induced electron flow (such as a battery). Flow storage types (or the instantiable subtypes) may be exchanged without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowStorageDeviceType are represented by instances of IfcFlowStorageDevice or its subtypes.

                + +
                + +HISTORY: New entity in IFC Release 2x2.
                +
                +
                + +
                " +1123;IfcFlowTreatmentDeviceType;" +

                The element type IfcFlowTreatmentDeviceType defines a list of commonly shared property set definitions of a flow treatment device and an optional set of product representations. It is used to define a flow treatment device specification (the specific product information that is common to all occurrences of that product type).

                + +

                A flow treatment device is a device used to change the physical properties of the medium, such as an air, oil +or water filter (used to remove particulates from the fluid), or a duct silencer (used to attenuate noise). Flow treatment types (or the instantiable subtypes) may be exchanged without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowTreatmentDeviceType are represented by instances of IfcFlowTreatmentDevice or its subtypes.

                + +
                +HISTORY: New entity in IFC Release 2x2.
                +
                + +
                " +1124;IfcFlowTerminalType;" +

                The element type IfcFlowTerminalType defines a list of commonly shared property set definitions of a flow terminal and an optional set of product representations. It is used to define a flow terminal specification (the specific product information that is common to all occurrences of that product type).

                + +

                A flow terminal type is used to define the common properties of a flow terminal that may be applied to many occurrences of that type. A flow terminal acts as a terminus or beginning element in a distribution system such as a ceiling register in a ducted air distribution system, a sink in a waste-water system, or a light fixture in an electrical lighting system. Flow terminal types (or the instantiable subtypes) may be exchanged without being already assigned to occurrences.

                + +

                The occurrences of the IfcFlowTerminalType are represented by instances of IfcFlowTerminal or its subtypes.

                + +
                +HISTORY: New entity in IFC Release 2x2.
                +
                + +
                " +1125;IfcDistributionChamberElementType;" + +

                The distribution flow element type IfcDistributionChamberElementType defines commonly shared information for occurrences of distribution chamber elements. The set of shared information may include:

                +
                  +
                • common properties with shared property sets
                • +
                • common materials
                • +
                • common ports
                • +
                • common composition of elements
                • +
                • common assignment of process types
                • +
                • common representations of shape and style
                • +
                +

                It is used to define a distribution chamber element specification (i.e. the specific product information, that is common to all occurrences of that product type). Distribution Chamber Element types may be exchanged without being already assigned to occurrences. + Occurrences of IfcDistributionChamberElementType are represented by instances of IfcDistributionChamberElement.

                +

                + +
                HISTORY: New entity in IFC2x2
                + +

                Property Set Use Definition

                +

                The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionFlowElementType and ancestors for inherited property set definitions.

                +

                The following property set definitions are applicable to this entity:

                +The following property set definitions are applicable to this entity according to the PredefinedType attribute:

                + + +

                Material Use Definition

                +

                The material of the IfcDistributionChamberElementType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

                +
                  +
                • 'Base': The material from which the base of the duct is constructed.
                • +
                • 'Cover': The material from which the access cover to the chamber is constructed.
                • +
                • 'Fill': The material that is used to fill the duct (where used).
                • +
                • 'Wall': The material from which the wall of the duct is constructed.
                • +
                + +
                + " +1139;IfcDistributionSystem;" +

                A distribution system is a network designed to receive, store, maintain, distribute, or control the flow of a distribution media. A common example is a heating hot water system that consists of a pump, a tank, and an interconnected piping system for distributing hot water to terminals.

                + +
                HISTORY New entity in IFC 2x4.
                + +

                The group IfcDistributionSystem +defines the occurrence of a specialized system for use within the context of building services.

                + +
                + +NOTE: For electrical power systems, IfcElectricalCircuit has been used for low-voltage (12-1000 V) power systems and has been deprecated in IFC2x4; IfcDistributionSystem with PredefinedType 'ELECTRICAL' should now be used instead. + +
                + +

                Important functionalities for the description of a distribution system are derived from existing IFC entities:

                + +
                • From IfcSystem it inherits the ability to couple the distribution system via IfcRelServicesBuildings to one or more IfcSpatialElement subtypes as necessary.
                + +
                • From IfcGroup it inherits the inverse attribute IsGroupedBy, pointing to the relationship class IfcRelAssignsToGroup. This allows to group distribution elements (instances of IfcDistributionElement subtypes), and in special cases ports directly (instances of IfcDistributionPort).
                + +
                • From IfcObject it inherits the inverse attribute IsDecomposedBy pointing to the relationship class IfcRelAggregates. It provides the hierarchy between the separate (partial) distribution systems. For example, an electrical main circuit may be aggregated into branch circuits.
                + + +

                Property Set Use Definition:

                + +

                The property sets relating to this entity are defined by the IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. It is accessible by the inverse IsDefinedBy relationship. The following property set definitions specific to this entity are part of this IFC release: +

                + + + +

                Assignment Use Definition:

                + +

                For the most common case of an IfcDistributionElement subtype containing ports of a particular PredefinedType that all belong to the same distribution system, the IfcDistributionElement is assigned to the IfcDistributionSystem via the IfcRelAssignsToGroup relationship, where IfcDistributionPort's are implied as part of the corresponding system based on their PredefinedType. An IfcDistributionElement may belong to multiple systems, however only one IfcDistributionSystem of a particular PredefinedType.

                + +

                For rare cases where an IfcDistributionElement subtype contains ports of the same PredefinedType yet different ports belong to different systems, alternatively each IfcDistributionPort may be directly assigned to a single IfcDistributionSystem via the IfcRelAssignsToGroup relationship, where the PredefinedType must match. Such assignment indicates that the IfcDistributionSystem assigned from the IfcDistributionPort overrides any such system of the same PredefinedType assigned from the containing IfcDistributionElement, if any.

                + +

                Additionally, an IfcDistributionSystem may in turn be assigned to an IfcDistributionPort indicating the host or origination of the system using IfcRelAssignsToProduct.

                + +
                + +EXAMPLE: A gas-powered hot water heater may have three ports: GAS, DOMESTICCOLDWATER, and DOMESTICHOTWATER. The heater is a member of two systems (GAS and DOMESTICCOLDWATER), and hosts one system (DOMESTICHOTWATER) at the corresponding port. + +
                + +

                Figure 150 illustrates a distribution system for an electrical circuit.

                + + + + +

                Figure 150 — Distribution system assignment

                + +

                + +
                " +1142;IfcDistributionFlowElement;" +

                The distribution element IfcDistributionFlowElement defines occurrence elements of a distribution system that facilitate the distribution of energy or matter, such as air, water or power.

                + +
                +EXAMPLEs of distribution flow elements are ducts, pipes, wires, fittings, and equipment. +
                + +
                +HISTORY: New entity in IFC R2.0.
                +
                + + +

                Type Use Definition

                +

                IfcDistributionFlowElement defines the occurrence of any distribution flow element; common information about distribution flow element types is handled by IfcDistributionFlowElementType. The IfcDistributionFlowElementType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. The IfcDistributionFlowElementType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. If the IfcDistributionFlowElementType has ports or aggregated elements, such objects are reflected at the IfcDistributionFlowElement occurrence using the IfcRelDefinesByObject relationship. Direct instantiation of IfcDistributionFlowElement with IfcObject.ObjectType asserted provides the meaning of a distribution flow element proxy.

                + +

                Property Set Use Definition

                +

                The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Property sets may also be specified at the IfcDistributionFlowElementType, defining the common property data for all occurrences of the same type. They are then accessible by the IsTypedBy inverse attribute pointing to IfcDistributionFlowElementType.HasPropertySets. If both are given, then the properties directly defined at IfcDistributionFlowElement override the properties defined at IfcDistributionFlowElementType. Refer to the documentation at the supertype IfcDistributionElement and ancestors for inherited property set definitions.

                + +

                Composition Use Definition

                +

                The IfcDistributionFlowElement may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcDistributionFlowElement and RelatedObjects contains one or more components. For example, a cable may be decomposed into wires. Standard types for composition are defined at subtypes.

                + +

                Connection Use Definition

                +

                The IfcDistributionFlowElement may be connected to other objects as follows using the indicated relationship:

                +
                  +
                • IfcSpatialStructureElement (IfcRelContainedInSpatialStructure) : Indicates the spatial location containing the element.
                • +
                • IfcElement (IfcRelConnectsElements) : Indicates physical connectivity with another element (but not embedding or flow transmission), such as a light fixture hanging from a ceiling (IfcCovering), or a junction box having a cover plate (IfcDiscreteAccessory). IfcRelConnectsElements.RelatingElement refers to the anchored side (ceiling for fixture, junction box for cover).
                • +
                • IfcElement (IfcRelInterferesElements) : Indicates interference with another element and precedence, such as a pipe going through a wall.
                • +
                • IfcOpening (IfcRelFillsElement) : Indicates embedding an element within another element (implying a cutout), such as an air terminal or junction box embedded within a wall.
                • +
                • IfcDistributionPort (IfcRelConnectsPortToElement) : Indicates ports on the element which may be connected to other elements for flow distribution of solids, liquids, gas, or electricity. Standard port names, types, and directions are defined at subtypes.
                • +
                • IfcDistributionControlElement (IfcRelFlowControlElements) : Indicates a control element that senses or controls some aspect of the flow element, such as a level sensor for a tank or an actuator for a valve.
                • +
                + +

                Assignment Use Definition

                +

                The IfcDistributionFlowElement may be assigned to the following entities using relationships as indicated:

                + +

                The IfcDistributionFlowElement may have assignments of its own using the IfcRelAssignsToProduct relationship where RelatingProduct refers to the IfcDistributionFlowElement and RelatedObjects contains one or more objects of the following types:

                +
                  +
                • IfcTask: Indicates tasks used to purchase, install, renovate, demolish, operate, or otherwise act upon the element. If the element has a type, available task types are assigned to the element type.
                • +
                • IfcProcedure: Indicates procedures used to operate the element. If the element has a type, available procedure types are assigned to the element type.
                • +
                • IfcEvent: Indicates events raised by the element, sequenced by procedures to be followed. If the element has a type, available event types are assigned to the element type.
                • +
                + +

                Material Use Definition

                +

                The material of the IfcDistributionFlowElement is defined using one of the following entities:

                +
                  + +
                • IfcMaterialProfileSetUsage: For parametric segments, this defines the cross section and alignment to the 'Axis' representation, from which the 'Body' representation may be generated.
                • + +
                • IfcMaterialProfileSet: For non-parametric segments (having fixed length or path), this may define the cross section for analysis purposes, however the 'Body' representation is independently generated.
                • + +
                • IfcMaterialConstituentSet: For elements containing multiple materials, this indicates materials at named aspects. +
                • + +
                • IfcMaterial: For elements comprised of a single material, this indicates the material.
                • +
                + +

                The material is attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDistributionFlowElementType, defining the common attribute data for all occurrences of the same type. Standard names and material types are defined at subtypes.

                + +

                Representation Use Definition

                +

                The following shape representations are supported for subtypes of IfcDistributionFlowElement, distinguished by IfcShapeRepresentation.RepresentationIdentifier:

                + +
                  +
                • 'Axis': Represents the 3D flow path of the item having IfcShapeRepresentation.RepresentationType of 'Curve3D' and containing a single IfcBoundedCurve subtype such as IfcPolyline, IfcTrimmedCurve, or IfcCompositeCurve. For elements containing directional ports (IfcDistributionPort with FlowDirection of SOURCE or SINK), the direction of the curve indicates direction of flow where a SINK port is positioned at the start of the curve and a SOURCE port is positioned at the end of the curve. This representation is most applicable to flow segments (pipes, ducts, cables), however may be used at other elements to define a primary flow path if applicable.
                • + +
                • 'Footprint': Represents the 2D footprint outline of the item having IfcShapeRepresentation.RepresentationType of 'GeometricCurveSet' and containing a single IfcGeometricCurveSet consisting of one or more IfcCurve subtypes such as IfcPolyline, IfcTrimmedCurve, IfcCompositeCurve, or IfcCircle.
                • + +
                • 'Body': Represents the 3D shape of the item having IfcShapeRepresentation.RepresentationType of 'SurfaceModel', 'SolidModel', or any solid model specializations including 'Brep', 'AdvancedBrep', 'SweptSolid', 'AdvancedSweptSolid', 'CSG', 'Clipping', or 'SectionedSpine').
                • + +
                • 'Clearance': Represents the 3D clearance volume of the item having RepresentationType of 'Surface3D'. Such clearance region indicates space that should not intersect with the 'Body' representation of other elements, though may intersect with the 'Clearance' representation of other elements. The particular use of clearance space may be for safety, maintenance, or other purpose.
                • + +
                • 'Lighting': Represents the light emission of the item having IfcShapeRepresentation.RepresentationType of 'LightSource' and containing one or more IfcLightSource subtypes. This representation is most applicable to lamps and light fixtures, however may be used at other elements that emit light. +
                + +

                For all representations, if a IfcDistributionFlowElement occurrence is defined by a IfcDistributionFlowElementType having a representation of the same identifier, then 'MappedRepresentation' should be used at the occurrence unless overridden.

                + +

                If materials are defined, geometry of each representation (most typically the 'Body' representation) may be organized into shape aspects where styles may be derived by correlating IfcShapeAspect.Name to a corresponding material (IfcMaterialConstituent.Name or IfcMaterialProfile.Name).

                + +

                Representations are further defined at subtypes; for example, parametric flow segments align material profiles with the 'Axis' representation.

                + +
                " +1153;IfcFlowFitting;" +

                The distribution flow element IfcFlowFitting defines the occurrence of a junction or transition in a flow distribution system, such as an elbow or tee. Its type is defined by IfcFlowFittingType or its subtypes.

                + +
                + + HISTORY: New entity in IFC R2.0.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + + +
                " +1154;IfcFlowSegment;" +

                The distribution flow element IfcFlowSegment defines the occurrence of a segment of a flow distribution system.

                + +
                +HISTORY: New entity in IFC R2.0.
                +IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                + +

                The IfcFlowSegment defines a particular occurrence of a segment inserted in the spatial context of a project. The parameters defining the type of the segment and/or its shape are defined by the IfcFlowSegmentType, which is related by the inverse relationship IsDefinedBy pointing to IfcRelDefinesByType. + +

                Material Use Definition

                +

                The material of the IfcFlowSegment is defined using one of the following entities:

                +
                  + +
                • IfcMaterialProfileSetUsage : for parametric segments, this defines the cross section and alignment to the 'Axis' representation, from which the 'Body' representation may be generated.
                • + +
                • IfcMaterialProfileSet : for non-parametric segments (having fixed length or path), this may define the cross section for analysis purposes, however the 'Body' representation is independently generated.
                • + +
                • IfcMaterialConstituentSet : for elements containing multiple materials where profiles are not applicable, this indicates materials at named parts. +
                • + +
                • IfcMaterial : for elements comprised of a single material where profiles are not applicable, this indicates the material.
                • +
                + +

                The material is attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFlowSegmentType, defining the common attribute data for all occurrences of the same type. Standard names and material types are defined at subtypes.

                + + +

                Representation Use Definition

                +

                +Standard representations are defined at the supertype IfcDistrubutionFlowElement. For parametric flow segments where IfcMaterialProfileSetUsage is defined and an 'Axis' representation is defined, then the 'Body' representation may be generated using the 'SweptSolid' or 'AdvancedSweptSolid' representation types by sweeping the profile(s) along the axis. +

                + +
                " +1155;IfcFlowController;" +

                The distribution flow element IfcFlowController defines + the occurrence of elements of a distribution system that + are used to regulate flow through a distribution system. + Examples include dampers, valves, switches, and relays. Its type is defined by + IfcFlowControllerType or subtypes.

                + +
                + +HISTORY: New entity in IFC R2.0.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + +
                " +1156;IfcFlowTerminal;" +

                The distribution flow element IfcFlowTerminal defines the + occurrence of a permanently attached element that acts as a terminus or + beginning of a distribution system (e.g., air outlet, drain, + water closet, sink, etc.). A terminal is typically a point + at which a system interfaces with an external environment. + Its type is defined by IfcFlowTerminalType or + its subtypes.

                + +
                + +HISTORY: New entity in IFC R2.0.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + + +
                " +1157;IfcFlowMovingDevice;" +

                The distribution flow element IfcFlowMovingDevice defines the occurrence of an apparatus used to distribute, circulate or perform conveyance of fluids, including liquids and gases (such as a pump or fan), and typically participates in a flow distribution system. Its type is defined by IfcFlowMovingDeviceType or its subtypes.

                + +
                + +HISTORY: New entity in IFC R2x.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + + +
                " +1158;IfcEnergyConversionDevice;" +

                The distribution flow element IfcEnergyConversionDevice defines + the occurrence of a device used to perform + energy conversion or heat transfer and typically participates + in a flow distribution system. Its type is defined by IfcEnergyConversionDeviceType + or its subtypes.

                + + +
                + + HISTORY: New entity in IFC R2.0.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + +
                " +1159;IfcFlowStorageDevice;" +

                The distribution flow element IfcFlowStorageDevice defines + the occurrence of a device that participates in a distribution + system and is used for temporary storage of a fluid + such as a liquid or a gas (e.g., tank). Its type is defined by + IfcFlowStorageDeviceType or its subtypes.

                + +
                + +HISTORY: New entity in IFC R2x.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + + +
                " +1160;IfcFlowTreatmentDevice;" +

                The distribution flow element IfcFlowTreatmentDevice defines the occurrence of a device typically used to remove unwanted matter from a fluid, either liquid or gas, and typically participates in a flow distribution system. Its type is defined by IfcFlowTreatmentDeviceType or its subtypes.

                + +
                + + HISTORY: New entity in IFC R2x.
                +
                + + IFC 2x4 NOTE: This entity has been deprecated for instantiation and will become ABSTRACT in a future release; new subtypes should now be used instead.
                +
                +
                + +
                " +1161;IfcDistributionChamberElement;" + +

                A distribution chamber element defines a place at which distribution systems and their constituent elements may be inspected or through which they may travel.

                + +

                An IfcDistributionChamberElement is a formed volume used in a distribution system, such as a sump, trench or manhole. Instances of IfcDistributionSystem or IfcDistributionFlowElement may be related to the IfcDistributionChamberElement enabling their location in or at the chamber to be determined.

                + +
                HISTORY: New entity in IFC2x2
                + +

                Type Use Definition

                +

                IfcDistributionChamberElement defines the occurrence of any distribution chamber element; common information about distribution chamber element types is handled by IfcDistributionChamberElementType. The IfcDistributionChamberElementType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. The IfcDistributionChamberElementType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. If the IfcDistributionChamberElementType has ports or aggregated elements, such objects are reflected at the IfcDistributionChamberElement occurrence using the IfcRelDefinesByObject relationship.

                + +

                Property Set Use Definition

                +

                The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Property sets may also be specified at the IfcDistributionChamberElementType, defining the common property data for all occurrences of the same type. They are then accessible by the IsTypedBy inverse attribute pointing to IfcDistributionChamberElementType.HasPropertySets. If both are given, then the properties directly defined at IfcDistributionChamberElement override the properties defined at IfcDistributionChamberElementType. Refer to the documentation at the supertype IfcDistributionFlowElement and ancestors for inherited property set definitions.

                +

                The following property set definitions are applicable to this entity:

                +The following property set definitions are applicable to this entity according to the PredefinedType attribute:

                + +

                Material Use Definition

                +

                The material of the IfcDistributionChamberElement is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDistributionChamberElementType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

                +
                  +
                • 'Base': The material from which the base of the duct is constructed.
                • +
                • 'Cover': The material from which the access cover to the chamber is constructed.
                • +
                • 'Fill': The material that is used to fill the duct (where used).
                • +
                • 'Wall': The material from which the wall of the duct is constructed.
                • +
                + +
                + " +1166;IfcDiscreteAccessory;" + +

                Definition from IAI: Representation of different kinds of + accessories included in or added to elements.

                +
                HISTORY New entity in IFC + Release 2x2
                + +
                IFC 2x4 change: +Attribute PredefinedType added. +
                + +

                General usage

                +

                The exact type information of the IfcDiscreteAccessory is given + in the ObjectType attribute inherited from IfcObject. Standard + type designations are provided for guideline below. The list is not exhaustive + and the list of definitions may be extended based on local national extensions. +

                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                Accessory typeStandard type designationDescription
                Shading devices:'Shading device'Elements specifically designed to provide shading, often fixed + externally and sometimes moving (e.g. by rotation)
                Corbels as separate components:'Hidden steel corbel'Corbel system made from steel components embedded into the master + element
                'Visible steel corbel'Corbel system made from steel components protruding from the master + element
                'Visible concrete corbel'Corbel system made as a separate precast concrete component added + to the master element
                'Ladder truss connector'A fixing device in truss form with straight cross bars in ladder + form holding two precast conrete panels together in a sandwich wall panel.
                'Panel suspender'A straight fixing device holding two precast conrete panels + together in a sandwich wall panel.
                Electrical accessories for precast concrete elements:'Protective plug'Protective plug used in element for protecting electrical + accessories during manufacturing, transportation and assembly.
                Fixing parts:'Standard fixing plate'Standard fixing plate.
                'Edge fixing plate'Fixing plate attached to the edge of an element.
                'Corner fixing plate'Fixing plate attached to the corner of an element.
                'Slab fixing plate'Fixing plate for slabs.
                'Balcony hinge'Accessory supporting and fixing balconies.
                'Frame shoe'Fixing shoe for frames.
                'Thermo frame'Thermo frame.
                'Column shoe'Fixing shoe for columns.
                'Wall shoe'Fixing shoe for walls.
                'Fixing socket'Fixing socket.
                Joint accessories:'Neoprene bearing plate'Rubber plate used as a bearing in, for example, joints between + column corbels and beams.
                'Working joint reinforcement'Reinforcement accessory used in working joints.
                'Expansion joint reinforcement'Reinforcement accessory used in expansion joints.
                'Ribbed steel bar extension'Extension accessory made of a ribbed (reinforcement) bar used in + joints.
                'Steel pin bolt'Pin bolt used to join together, for example, columns and + beams.
                'Concrete dowel'Dowel pin used in joints.
                'Concrete groove'A groove made in a joint.
                'Steel plate'A steel plate used as an accessory in a joint.
                'Wire loop'A joint connector accessory made from a wire loop.
                'Steel loop'A joint connector accessory made from a steel bar loop.
                'Sealing strip'A strip sealing the joint.
                'Sealing compound'Sealing compound protecting and sealing the joint.
                Lifting accessories:'Wire lifting hook'A lifting aid in the form of a wire loop.
                'Steel lifting hook'A lifting aid in the form of a steel bar loop.
                'Lifting socket'A lifting aid in the form of a socket.
                'Steel lifting anchor'A lifting aid in the form of a steel lifting anchor.
                'Lifting hole'A lifting aid in the form of a hole.
                Accessories mainly used in the building services domain:'Antivibration'An isolating device to prevent other elements to be effected by + vibrations.
                'Drop rod'A length of material providing a hanging support to a bracket. Note + that a drop rod is considered to include nuts and washers required for + securing.
                'Duct foot'A base support used to receive a vertical pipe (BS6100 330 3309 - + duct foot).
                'Framing'A frame placed around a penetration to prevent scraping against the + building surface or structure.
                'Grommet'An element placed within a penetration that seals the penetration + for a particular reason.
                'Rack'A set of shelving for the purposes of storage that may be + freestanding or bolted to a structure.
                'Safety part'A part, typically installed in vertical shafts at each level, to + ensure safety from falling when entering the shaft.
                'Sleeve'A thin barrier placed between a penetration and a penetrating + element.
                'Support section'A section of material that is used as an intermediate support upon + which multiple brackets can be mounted.
                + +
                " +1170;IfcElementComponent;" + +

                +An element component is a representation for minor items included in, added to or connecting to or between + elements, which usually are not of interest from the overall building structure viewpoint. + However, these small parts may have vital and load carrying functions within the construction. + These items do not provide any actual space boundaries. + Typical examples of IfcElementComponents include different kinds of fasteners and various accessories. +

                + +
                HISTORY New entity in IFC Release 2x2
                + +

                It is often desirable to model a number of same-shaped element components by means of a single +occurrence object, e.g. several bolts within a connection or a row of reinforcement elements. +In this IFC release, this is possible by means of multiple mapped representation as documented below.

                + +

                To express the multiplicity of element components also on a higher semantic level, +an IfcElementQuantity should be provided via IfcRelDefinesByProperties. +The quantity should contain an IfcQuantityCount named 'Count' with the number of components.

                + +

                Geometry Use Definition

                + +

                + The geometric representation of IfcElementComponent is given by the IfcProductDefinitionShape, + allowing multiple geometric representations. Included are: +

                + +

                Local Placement
                + The local placement for IfcElementComponent is defined in its supertype IfcProduct. + It is defined by the IfcLocalPlacement, which defines the local coordinate system that is + referenced by all geometric representations. +

                + +
                  +
                • The PlacementRelTo relationship of IfcLocalPlacement shall point (if given) to + the local placement of the same IfcElement or IfcElementAssembly, which is + used in the Decomposes inverse attribute, i.e. the local placement is defined relative to + the local placement of the element or element assembly in which the component is contained. +
                • If the relative placement is not used, the absolute placement is defined within the world coordinate system. +
                + +

                Surface Model Representation

                +

                + Any IfcElementComponent (if no further constraints are defined at the level of its subtypes) + may be represented as a single or multiple surface models, based on either shell or face based models. + The following attribute values for the IfcShapeRepresentation holding this geometric representation + shall be used: +

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SurfaceModel'
                • +
                + +

                +Brep Representation

                +

                + Any IfcElementComponent (if no further constraints are defined at the level of its subtypes) + may be represented as a single or multiple Boundary Representation elements (which are restricted to faceted + Brep with or without voids). The Brep representation allows for the representation of complex element shape. + The following attribute values for the IfcShapeRepresentation holding this geometric representation + shall be used: +

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Brep'
                • +
                + +

                Mapped Representation

                +

                + The mapped item, IfcMappedItem, should be used if appropriate as it allows for reusing the geometry + definition of a type at occurrences of the same type. + The following attribute values for the IfcShapeRepresentation holding this geometric representation + shall be used: +

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'MappedRepresentation'
                • +
                + +

                Multiple Mapped Representation

                + +

                A single instance of a subtype of IfcElementComponent can stand for several +actual element components at once. In this case, the IfcShapeRepresentation +contains as many mapped items as there are element components combined within this +occurrence object:

                + +

                Figure 151 illustrates multiple components modeled as a single occurrence object (here: IfcFastener)

                + + + +

                Figure 151 — Element component mapped representation

                + +

                Representation identifier and type are the same as in single mapped representation. +The number of mapped items in the representation corresponds with the count of +element components in the IfcElementQuantity.

                + +
                " +1175;IfcElementComponentType;" +

                Definition from IAI: + The element type (IfcElementComponentType) represents the supertype for element + types which define lists of commonly shared property set definitions of various small parts and accessories and an optional set of product + representations. It is used to define a supporting element mainly within + structural and building services domains (i.e. the specific type information + common to all occurrences of that type).

                + +
                HISTORY New entity in IFC + Release 2x2 +
                +
                " +1180;IfcBuildingElementPartType;" +

                Definition from IAI: The building element part type defines +lists of commonly shared property set definitions and representation maps of parts of a building element.

                + +
                +HISTORY New entity in IFC Release 2x4 +
                + +
                " +1188;IfcDiscreteAccessoryType;" + +

                Definition from IAI: The element type + (IfcDiscreteAccessoryType) defines a list of commonly shared property + set definitions of a discrete accessory and an optional set of product + representations. It is used to define a supporting element mainly within + structural and building services domains (i.e. the specific type information + common to all occurrences of that type).

                +

                The occurrences of the IfcDiscreteAccessoryType are represented + by instances of IfcDiscreteAccessory.

                +

                The IfcDiscreteAccessoryType is a specialization of the general + building element component type to represent different type of structural and + building service related auxiliary elements.

                +
                HISTORY New entity in IFC + Release 2x2
                + +
                IFC 2x4 change: +Attribute PredefinedType added. +
                + +

                General usage

                +

                The exact type information of the IfcDiscreteAccessoryType is + given in the ElementType attribute inherited from IfcElementType. + Standard type designations are provided for guideline below. The list is not + exhaustive and the list of definitions may be extended based on local national + extensions.

                + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
                Accessory typeStandard type designationDescription
                Shading devices:'Shading device'Elements specifically designed to provide shading, often fixed + externally and sometimes moving (e.g. by rotation)
                Corbels as separate components:'Hidden steel corbel'Corbel system made from steel components embedded into the master + element
                'Visible steel corbel'Corbel system made from steel components protruding from the master + element
                'Visible concrete corbel'Corbel system made as a separate precast concrete component added + to the master element
                Connecting accessories, for example for sandwich wall panels:'Diagonal truss connector'A fixing device in truss form with diagonal cross bars holding two + precast conrete panels together in a sandwich wall panel.
                'Ladder truss connector'A fixing device in truss form with straight cross bars in ladder + form holding two precast conrete panels together in a sandwich wall panel.
                'Panel suspender'A straight fixing device holding two precast conrete panels + together in a sandwich wall panel.
                Electrical accessories for precast concrete elements:'Protective plug'Protective plug used in element for protecting electrical + accessories during manufacturing, transportation and assembly.
                Fixing parts:'Standard fixing plate'Standard fixing plate.
                'Edge fixing plate'Fixing plate attached to the edge of an element.
                'Corner fixing plate'Fixing plate attached to the corner of an element.
                'Slab fixing plate'Fixing plate for slabs.
                'Balcony hinge'Accessory supporting and fixing balconies.
                'Frame shoe'Fixing shoe for frames.
                'Thermo frame'Thermo frame.
                'Column shoe'Fixing shoe for columns.
                'Wall shoe'Fixing shoe for walls.
                'Fixing socket'Fixing socket.
                Joint accessories:'Neoprene bearing plate'Rubber plate used as a bearing in, for example, joints between + column corbels and beams.
                'Working joint reinforcement'Reinforcement accessory used in working joints.
                'Expansion joint reinforcement'Reinforcement accessory used in expansion joints.
                'Ribbed steel bar extension'Extension accessory made of a ribbed (reinforcement) bar used in + joints.
                'Steel pin bolt'Pin bolt used to join together, for example, columns and + beams.
                'Concrete dowel'Dowel pin used in joints.
                'Concrete groove'A groove made in a joint.
                'Steel plate'A steel plate used as an accessory in a joint.
                'Wire loop'A joint connector accessory made from a wire loop.
                'Steel loop'A joint connector accessory made from a steel bar loop.
                'Sealing strip'A strip sealing the joint.
                'Sealing compound'Sealing compound protecting and sealing the joint.
                Lifting accessories:'Wire lifting hook'A lifting aid in the form of a wire loop.
                'Steel lifting hook'A lifting aid in the form of a steel bar loop.
                'Lifting socket'A lifting aid in the form of a socket.
                'Steel lifting anchor'A lifting aid in the form of a steel lifting anchor.
                'Lifting hole'A lifting aid in the form of a hole.
                Accessories mainly used in the building services domain:'Antivibration'An isolating device to prevent other elements to be effected by + vibrations.
                'Drop rod'A length of material providing a hanging support to a bracket. Note + that a drop rod is considered to include nuts and washers required for + securing.
                'Duct foot'A base support used to receive a vertical pipe (BS6100 330 3309 - + duct foot).
                'Framing'A frame placed around a penetration to prevent scraping against the + building surface or structure.
                'Grommet'An element placed within a penetration that seals the penetration + for a particular reason.
                'Rack'A set of shelving for the purposes of storage that may be + freestanding or bolted to a structure.
                'Safety part'A part, typically installed in vertical shafts at each level, to + ensure safety from falling when entering the shaft.
                'Sleeve'A thin barrier placed between a penetration and a penetrating + element.
                'Support section'A section of material that is used as an intermediate support upon + which multiple brackets can be mounted.
                + + + +
                " +1197;IfcFastenerType;" +

                Definition from IAI: + The element type (IfcFastenerType) defines a list of commonly shared + property set definitions of a fastener and an optional set of product + representations. It is used to define fasteners mainly within + structural and building services domains (i.e. the specific type information + common to all occurrences of that type).

                + +

                + The occurrences of the IfcFastenerType are represented by + instances of IfcFastener. +

                + +
                + HISTORY New entity in IFC Release 2x2 +
                + +
                IFC 2x4 change: +Attribute PredefinedType added. +Subtype IfcMechanicalFastenerType redefined as direct subtype of IfcElementComponentType. +
                + +

                Property Set Use Definition

                + +

                The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute.

                + +

                The following property set definitions are applicable to this entity according to the PredefinedType attribute:

                + + +
                " +1206;IfcMechanicalFastenerType;" + +

                Definition from IAI: The element type (IfcMechanicalFastenerType) defines a list of commonly shared property set definitions of a fastener and an optional set of product representations. It is used to define mechanical fasteners mainly within structural and building services domains (i.e. the specific type information common to all occurrences of that type).

                + +

                The occurrences of the IfcMechanicalFastenerType are represented by instances of IfcMechanicalFastener.

                + +
                HISTORY New entity in IFC Release 2x2
                + +
                IFC 2x4 change: +Supertype changed from IfcFastenerType to IfcElementComponentType. +Attributes PredefinedType, NominalDiameter, NominalLength added. +
                + +

                Mechanical fasteners, especially bolts, are often standardized. To refer to a formal fastener +designation according to a standard (a product norm), IfcRelAssociatesClassification together +with IfcClassificationReference should be used.

                +
                  +
                • IfcClassificationReference.ItemReference +contains a machine-readable form of the formal fastener designation from the norm. +Example: 'M16X80-10.9-HV' for a high-strength structural bolting assembly for preloading with +hexagon bolt and nut. (On the other hand, IfcMechanicalFastenerType.Name contains a +displayable name which may not necessarily be the same as the formal designation.)
                • +
                • IfcClassificationReference.Name carries the short name of the fastener norm. +Example: 'EN 14399-4' as the respective European standard for high-strength hexagon bolts.
                • +
                • Optionally, the norm can be further described by +IfcClassificationReference.ReferencedSource, including information like publisher and +date of issue of the norm.
                • +
                + +

                Furthermore, IfcRelAssociatesLibrary together with IfcLibraryReference may be +used to refer to a library which contains fastener definitions.

                + +

                Property Set Use Definition

                + +

                The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute.

                + +

                The following property set definitions are applicable to this entity according to the PredefinedType attribute:

                + + +
                " +1224;IfcFastener;" +

                +Definition from IAI: + Representations of fixing parts which are used as fasteners to connect or join elements with + other elements. +

                + +
                + HISTORY New entity in IFC Release 2x2 +
                + +
                IFC 2x4 change: +Attribute PredefinedType added. +
                + +
                " +1228;IfcBuildingElementPart;" +

                Definition from IAI: Layers or major components as subordinate +parts of a building element. Typical usage examples include precast concrete +sandwich walls, where the layers may have different geometry representations. +In this case the layered material representation does not sufficiently describe +the element. Each layer is represented by an own instance of the +IfcBuildingElementPart with its own geometry description.

                + +

                The kind of building element part is further specified by a +corresponding instance of IfcBuildingElementPartType, +referred to by IfcRelDefinesByType.

                + +
                +HISTORY New entity in IFC Release 2x2 +
                + +
                IFC 2x4 change: +Moved from from IfcStructuralElementsDomain schema to +IfcSharedComponentElements schema, compatible change of supertype, +attribute PredefinedType added. +
                + +
                " +1232;IfcMechanicalFastener;" + +

                Definition from IAI: Fasteners connecting building elements mechanically. A single instance of this class may represent one or many of actual mechanical fasteners, for example an array of bolts or a row of nails.

                + +
                HISTORY New entity in IFC Release 2x2
                + +
                IFC 2x4 change: +Supertype changed from IfcFastener to IfcElementComponent. +Attribute PredefinedType added. +Attributes NominalDiameter and NominalLength moved to IfcMechanicalFastenerType. +
                + +

                Geometry Use Definition

                + +

                See definitions at the supertype IfcElementComponent.

                + +

                In addition, a symbolic representation is defined for a row of fasteners or several rows of +fasteners within a single instance of IfcMechanicalFastener. Such rows or arrays may +contain possibly large numbers of individual pieces. The product definition shape consists of +an IfcShapeRepresentation with the attribute values

                +
                  +
                • RepresentationIdentifier : 'Row'
                • +
                • RepresentationType : 'GeometricCurveSet'
                • +
                +

                and one or several curves as geometric items. The curves represent where the heads of the fasteners +are located. The local placement of the IfcMechanicalFastener shall be located and oriented such +that the local z axis is parallel with the axes of the fasteners (bolts, nails, staples or similar).

                + +

                In case of such a symbolic 'Row' representation, an IfcElementQuantity should be attached to +the IfcMechanicalFastener via IfcRelDefinesByProperties. The quantity should contain an +IfcQuantityCount named 'Count' with the number of fasteners and an IfcQuantityLength +named 'Spacing' which expresses the center-to-center distances of fasteners.

                + +
                " +1237;IfcRelCoversSpaces;" +

                + Definition from IAI: The objectified relationship, + IfcRelCoversSpace, relatesÿa space object to one or + many coverings, which faces (or is assigned to) the space. +

                +
                +

                + NOTE Particularly floorings, ceilings and wall + coverings, such as claddings or tiling are often + considered as space coverings, rather then wall or slab + coverings. In some life cycle phases, such as the + operation phase, the relationship is always made to the + space. +

                +
                +

                + The IFC specification provides two relationships: +

                +
                  +
                • + IfcRelCoversBldgElements to assign coverings to + elements, and +
                • +
                • + IfcRelCoversSpaces to assign coverings to spaces +
                • +
                +

                + Which relationship should be applied has to be determined + by the context of the project or application . +

                +
                +

                + NOTE View definition may determine the necessity + to use either of the two relationship elements +

                +
                +
                + HISTORYÿ New Entity in Release + IFC 2x Edition 3. +
                +
                " +1240;IfcRelConnectsPathElements;" +

                The +IfcRelConnectsPathElements relationship provides the connectivity information between two elements, which have path information.

                + +

                The objectified relationship provides the additional +information required to describe the connection between two path +based elements that might have single or multiple layers of +material. The connection type specifies where at the path based +element a connection is given (at the start, in the middle or at +the end).

                + +

                The connection is described by a connection geometry, given +within the object coordinate systems of the +RelatingElement and of the RelatedElement. In case +of IfcWallStandardCase as the RelatingElement and +RelatedElement the connection geometry is provided by the +subtype IfcConnectionCurveGeometry. Both curves indicate +the so called ""end cap"", i.e. the curve that trims the wall outer +edges (being parallel along the wall axis) at the end.

                +
                HISTORY New entity in IFC Release 1.5.
                + +

                Figure 115 shows the application of IfcRelConnectsPathElements with the ConnectionGeometry of type IfcConnectionCurveGeometry. The example shows the connection relationship between two instances of IfcWallStandardCase using the IfcRelConnectsPathElements relationship. The ConnectionCurveGeometry defines the CurveOnReleatingElement and CurveOnRelatedElement, both are of type IfcPolyline.

                + + + + +

                Figure 115 — Path connection geometry

                + +

                Figure 116 illustrates using the IfcRelConnectsPathElements for a ""T"" type connection between two instances of IfcWallStandardCase.

                +

                Figure 117 illustrates using the IfcRelConnectsPathElements for a ""L"" type connection between two instances of IfcWallStandardCase.

                +
                NOTE  The two wall axes connect in each case.
                + + + + + + + + + + +
                ÿ

                Figure 116 — Path connection T-Type

                Figure 117 — Path connection L-Type

                + +
                " +1250;IfcBeam;" + +

                Definition from ISO 6707-1:1989: Structural member designed to carry loads between or beyond points of support, usually narrow in relation to its length and horizontal or nearly so.

                + +

                An IfcBeam is a horizontal, or nearly horizontal, structural member that is capable of withstanding load primarily by resisting bending. It represents such a member from an architectural point of view. It is not required to be load bearing.

                + +
                NOTE  The representation of a beam in a structural analysis model is provided by +IfcStructuralCurveMember being part of an IfcStructuralAnalysisModel.
                + +
                NOTE  For any longitudial structural member, not constrained to be predominately horizontal nor vertical, or where this semantic information is irrelevant, the entity IfcMember should be used.
                + +

                The IFC specification provides two entities for beam occurrences:

                +
                  +
                • IfcBeamStandardCase used for all occurrences of beams, that have a profile defined that is swept along a directrix. The profile might be changed uniformly by a taper definition along the directrix. The profile parameter and its cardinal point of insertion can be fully described by the IfcMaterialProfileSetUsage. These beams are always represented geometricly by an 'Axis' and a 'SweptSolid' or 'AdvancedSweptSolid' shape representation (or by a 'Clipping' geometry based on the swept solid), if a 3D geometric representation is assigned. In addition they have to have a corresponding IfcMaterialProfileSetUsage assigned. +
                  NOTE  View definitions and implementer agreements may further constrain the applicable geometry types, for example, by excluding tapering from an IfcBeamStandardCase implementation.
                  +
                • +
                • IfcBeam used for all other occurrences of beams, particularly for beams with changing profile sizes along the extrusion, or beams defined by non-linear extrusion, or beams having only 'Brep', or 'SurfaceModel' geometry.
                • +
                + +
                HISTORY New entity in IFC Release 1.0
                + +

                Type Use Definition

                +

                IfcBeam defines the occuurence of any beam, common +information about beam types (or styles) is handled by +IfcBeamType. The IfcBeamType (if present) may +establish the common type name, usage (or predefined) type, +common material layer set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcBeamType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                +

                If no IfcBeamType is attached (i.e. if only occurrence +information is given) the PredefinedType should be provided. +If set to .USERDEFINED. a user defined value can be provided by the +ObjectType attribute.

                +

                Material Use Definition

                +

                The material of the IfcBeam is defined by the +IfcMaterialProfileSet or as fallback by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

                +
                Note It is illegal to assign an +IfcMaterialProfileSetUsage to an IfcBeam. Only the +subtype IfcBeamStandardCase supports this +concept.
                +

                Material information can also be given at the +IfcBeamType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the inverse +IsTypedBy relationship pointing +to IfcBeamType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterialProfileSet or IfcMaterial. If both are +given, then the material directly assigned to IfcBeam +overrides the material assigned to IfcBeamType.

                +

                Property Set Use Definition

                +

                The property sets relating to the IfcBeam are defined by +the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcBeam are part of this IFC +release:

                + +

                Property sets can also be given at the IfcBeamType, +defining the common property data for all occurrences of the same +type. It is then accessible by the inverse IsTypedBy relationship pointing to +IfcBeamType.HasPropertySets. If both are given, then the +properties directly assigned to IfcBeam overrides the +properties assigned to IfcBeamType.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcBeam are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following base +quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other quantities +can be defined being subjected to local standard of measurement +with another string value assigned to MethodOfMeasurement. +Quanties shall be never assigned to the IfcBeamType.

                + + +

                Containment Use Definition

                +

                The IfcBeam, as any subtype of IfcBuildingElement, +may participate in two different containment relationships. The +first (and in most implementation scenarios mandatory) relationship +is the hierachical spatial containment, the second (optional) +relationship is the aggregation within an element assembly.

                +
                  +
                • The IfcBeam is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcBeam may be aggregated into an element assembly +using the objectified relationship IfcRelAggregates, +refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this case +it should not be additionally contained in the project spatial +hierarchy, i.e. SELF\IfcElement.ContainedInStructure should +be NIL.
                • +
                + +

                Geometry Use Definition

                +

                The geometric representation of IfcBeam is given by the +IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local Placement

                +

                The local placement for IfcBeam is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to a +spatial structure element at a higher level, referenced by that. +
                    +
                  • Exception: If the IfcBeam is part of an assembly, the +PlacementRelTo relationship of IfcLocalPlacement +shall point to the local placement of the container element, e.g. +IfcElementAssembly,
                  • +
                  +
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Axis', 'Body', and +'Box' representations are supported. The 'Box' representation +includes the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +

                Axis Representation

                +

                The axis geometric representation of IfcBeam is defined +using the 'Axis' representation.

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D', 'Curve3D'
                • +
                +
                The 'Axis' can be used to represent the system +axis and length of a beam that may extent the body +length.
                +

                Body Representation

                +

                The body representation of IfcBeam can be represented +using the representation types 'SweptSolid', 'Clipping', +'AdvancedSweptSolid', 'MappedRepresentation', 'SurfaceModel', and +'Brep'. The representation types 'SurfaceModel' and 'Brep' are +explained at IfcBuildingElement.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation type:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Profile: all subtypes of IfcProfileDef (with +exception of IfcArbitraryOpenProfileDef)
                • +
                • Extrusion:  All extrusion directions shall be +supported.
                • +
                + +

                Figure 71 illustrates the 'SweptSolid' geometric representation. There are no restrictions or conventions on how to use the local placement (black), solid of extrusion placement (red) and profile placement (green).

                + + + + +

                Figure 71 — Beam swept solid

                + +

                Figure 72 illustrates the use of non-perpendicular extrusion to create the IfcExtrudedAreaSolid.

                + + + + +

                Figure 72 — Beam non-perpendicular extrusion

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the advanced +representation:

                +
                  +
                • Solid: see 'SweptSolid' geometric representation
                • +
                • Profile: see 'SweptSolid' geometric representation
                • +
                • Extrusion: see 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or its subtypes).
                • +
                + +

                Figure 73 illustrates use of IfcBooleanClippingResult between an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body.

                + + + + +

                Figure 73 — Beam clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer agreement +can further constrain the allowed swept solid +types.
                  +
                • +
                • Profile: see 'SweptSolid' geometric representation
                • +
                • Extrusion: not applicable
                • +
                +

                MappedRepresentation Representation Type

                +

                The 'MappedRepresentation' representation is supported as it +allows for reusing the geometry definition of the beam type at all +occurrences of the same type. The following attribute values for +the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'MappedRepresentation'
                • +
                +

                The same constraints, as given for the 'SweptSolid', 'Clipping', +'AdvancedSweptSolid', 'SurfaceModel', and 'Brep' geometric +representation, shall apply to the MappedRepresentation of +the IfcRepresentationMap.

                +
                " +1255;IfcBeamStandardCase;" +

                The standard beam, +IfcBeamStandardCase, defines a beam with certain constraints +for the provision of material usage, parameters and with certain +constraints for the geometric representation. The +IfcBeamStandardCase handles all cases of beams, that:

                +
                  +
                • have a reference to the IfcMaterialProfileSetUsage +defining the material profile association of the beam with the +cardinal point of its insertion relative to the local +placement.
                • +
                • are consistent in using the correct cardinal point offset of +the profile as compared to the 'Axis' and 'Body' shape +representation
                • +
                • are based on a sweep of a planar profile, or set of profiles, +as defined by the IfcMaterialProfileSet
                • +
                • have an 'Axis' shape representation with constraints provided +below in the geometry use definition
                • +
                • have a 'Body' shape representation with constraints provided +below in the geometry use definition +
                    +
                  • are extruded perpendicular to the profile definition plane
                  • +
                  • have a start profile, or set of profiles, that is swept
                  • +
                  • the sweeping operation can be linear extrusion, circular +rotation, or a sweep along a directrix
                  • +
                  • the start profile, or set of profiles can be swept unchanged, +or might be changed uniformly by a taper definition
                  • +
                  +
                • +
                • +
                  NOTE  View definitions and implementer +agreements may further constrain the applicable geometry types, +e.g. by excluding tapering from an IfcBeamStandardCase +implementation.
                  +
                • +
                +
                HISTORY New entity in IFC2x4.
                + +

                Type Use Definition

                +

                IfcBeam defines the occurrence of any beam, common +information about beam types (or styles) is handled by +IfcBeamType. The IfcBeamType (if present) may +establish the common type name, usage (or predefined) type, common +set of properties, and common material profile set (combining +profiles and material of profile). The IfcBeamType is +attached using the IfcRelDefinedByType.RelatingType +objectified relationship and is accessible by the inverse +IsTypedBy attribute.

                +

                The IfcBeamStandardCase defines in addition that the +IfcBeamType should have a unique +IfcMaterialProfileSet, that is referenced by the +IfcMaterialProfileSetUsage that is assigned to all +occurrences of this beam type.

                + +

                Figure 74 illustrates assignment of IfcMaterialProfileSetUsage and IfcMaterialProfileSet to the IfcBeamStandardCase as the beam occurrence and to the IfcBeamType. The same IfcMaterialProfileSet shall be shared by many occurrences of IfcMaterialProfileSetUsage. This relationship shall be consistent to the relationship between the IfcBeamType and the IfcBeamStandardCase.

                + + + + +

                Figure 74 — Beam profile usage

                + +

                Figure 75 illustrates alignment of cardinal points.

                +
                NOTE  It has to be guaranteed that the use of IfcCardinalPointEnum is consistent to the placement of the extrusion body provided by IfcExtrudedAreaSolid.Position
                +
                NOTE  The cardinal points 8 (top centre) and 6 (mid-depth right) are assigned according to the definition at IfcCardinalPointReference
                + + + + +

                Figure 75 — Beam cardinal points

                + +

                Figure 76 illustrates assignment of a composite profile by using IfcCompositeProfile for geometric representation and several IfcMaterialProfile's within the IfcMaterialProfileSet.

                + + + + +

                Figure 76 — Beam composite profiles

                + +

                Material Use Definition

                +

                The material of the IfcBeamStandardCase is defined by +IfcMaterialProfileSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Composite profile beams can be represented by refering to several +IfcMaterialProfile's within the IfcMaterialProfileSet +that is referenced from the IfcMaterialProfileSetUsage. See +Type Use Definition for additional agreements for material +assignement to IfcBeamStandardCase and +IfcBeamType.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcBeamStandardCase are +defined at the supertype IfcBeam.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcBeamStandardCase are +defined at the supertype IfcBeam.

                +

                Containment Use Definition

                +

                The containment use definitions relating to the +IfcBeamStandardCase are defined at the supertype +IfcBeam.

                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcBeamStandardCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representations. Included are:

                +

                Local Placement

                +

                The general use of local placement is defined at the supertype +IfcBeam. The following restriction is imposed:

                +
                  +
                • The local placement shall provide the location and directions +for the standard beam, the x/y plane is the plane for the start +profile, and the z-axis is the extrusion axis for the beam body (in +case of rotation, the tangent direction).
                • +
                +

                Geometric Representations

                +

                The geometric representation of IfcBeamStandardCase is +defined using the following multiple shape representations for its +definition:

                +
                  +
                • Axis: A three dimensional open curve (subtype of +IfcBoundedCurve) defining the axis for the standard beam. +The cardinal point is determined by the beam axis.
                • +
                • Body: A Swept Solid Representation or a CSG clipping +representation defining the 3D shape of the standard beam.
                • +
                +
                NOTE It is invalid to exchange a 'SurfaceModel', +'Brep', or 'MappedRepresentation' representation for the 'Body' +shape representation of an +IfcBeamStandardCase.
                +

                Axis Representation

                +

                The axis geometric representation of IfcBeamStandardCase +is defined using the 'Axis' representation. The following attribute +values for the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve3D'
                • +
                +

                The following additional constraints apply to the 'Axis' +representation, if the 'Body' shape representation has the +RepresentationType : 'SweptSolid':

                +
                  +
                • Axis : +
                    +
                  • IfcPolyline having two Points, or +IfcTrimmedCurve with BasisCurve of Type +IfcLine for 'SweptSolid' provided as +IfcExtrudedAreaSolid. The axis curve lies on the z axis of +the object coordinate system.
                  • +
                  • IfcTrimmedCurve with BasisCurve of Type +IfcCircle for 'SweptSolid' provided as +IfcRevolvedAreaSolid. The axis curve lies on the x/z plane +of the object coordinate system, the tangent at the start is along +the positive z-axis.
                  • +
                  +
                • +
                + +

                As shown in Figure 77, the axis shall be defined along the z axis of the object coordinate system. The axis representation can be used to represent the system length of a beam that may extent the body length of the beam.

                + + + + +

                Figure 77 — Beam axis representation

                + +

                As shown in Figure 78, the axis representation shall be used to represent the cardinal point as the offset between the 'Axis' and the extrusion path of the beam. The extrusion path is provided as IfcExtrudedAreaSolid.ExtrudedDirection and should be parallel to the 'Axis' and the z axis. It has to be guaranteed that the value provided by +IfcMaterialProfileSetUsage.CardinalPoint is consistent to the IfcExtrudedAreaSolid.Position.

                + + + + +

                Figure 78 — Beam axis cardinal point

                + +

                Body Representation

                +

                The body representation of IfcBeamStandardCase can be +represented using the representation types 'SweptSolid', +'Clipping', or 'AdvancedSweptSolid'.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Solid Position : The IfcSweptAreaSolid.Position +shall exclusively been used to correspond to the cardinal point. +The x/y offset of the Position represents the cardinal +point offset of the profile against the axis. No rotation shall be +allowed.
                • +
                • Profile: All subtypes of +IfcParameterizedProfileDef
                • +
                • Profile Position : For all single profiles, the +IfcParameterizedProfileDef.Position shall be NIL, or having +Location = 0.,0. and RefDirection = 1.,0.
                • +
                • Extrusion: Perpendicular to the profile direction. +The IfcExtrudedAreaSolid.ExtrudedDirection shall be +[0.,0.,1.].
                • +
                • Orientation: The y-axis of the profile, as determined by +IfcSweptAreaSolid.Position.P[2] shall point upwards. It +indicates the ""role"" of the beam, a role=0° means y-axis of +profile pointing upwards.
                • +
                + +

                Figure 79 illustrates a standard geometric representation with cardinal point applied as 1 (bottom left).

                +

                The following interpretation of dimension parameter applies for rectangular beams with linear extrusions:

                +
                  +
                • IfcRectangleProfileDef.YDim interpreted as beam height
                • +
                • IfcRectangleProfileDef.XDim interpreted as beam width
                • +
                +

                The following interpretation of dimension parameter applies for circular beams:

                +
                  +
                • IfcCircleProfileDef.Radius interpreted as beam radius.
                • +
                + + + + +

                Figure 79 — Beam body extrusion

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the 'Clipping' +representation:

                +
                  +
                • Solid : see 'SweptSolid' geometric representation
                • +
                • Solid Position : see 'SweptSolid' geometric +representation
                • +
                • Profile : see 'SweptSolid' geometric representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion : see 'SweptSolid' geometric +representation
                • +
                • Orientation : see 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or its subtypes).
                • +
                + +

                Figure 80 illustrates a 'Clipping' geometric representation with use of IfcBooleanClippingResult between an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body, with cardinal point applied as 4 (mid-depth left)

                + + + + +

                Figure 80 — Beam body clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The 'AdvancedSweptSolid' representation type is a valid body +representation of IfcBeamStandardCase. The following +attribute values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer agreement +can further constrain the allowed swept solid +types.
                  +
                • +
                • Solid Position : see 'SweptSolid' geometric +representation
                • +
                • Profile: see 'SweptSolid' geometric representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion: not applicable
                • +
                + +
                " +1266;IfcColumn;" +

                Definition from ISO 6707-1:1989: Structural member of +slender form, usually vertical, that transmits to its base the +forces, primarily in compression, that are applied to it.

                +

                IfcColumn is a vertical +structural member which often is aligned with a structural grid +intersection. It represents a vertical, or nearly vertical, +structural member that transmits, through compression, the weight +of the structure above to other structural elements below. It +represents such a member from an architectural point of view. It +is not required to be load bearing.

                +
                NOTE The representation of a column in a +structural analysis model is provided by +IfcStructuralCurveMember being part of an +IfcStructuralAnalysisModel.
                +
                +NOTE ÿFor any longitudial structural member, not +constrained to be predominately horizontal nor vertical, or where +this semantic information is irrelevant, the entity +IfcMember exists.
                +

                The IFC specification provides two entities for column +occurrences:

                +
                  +
                • IfcColumnStandardCase used for all occurrences of +columns, tthat have a profile defined that is swept along a +directrix. The profile might be changed uniformly by a taper +definition along the directrix. The profile parameter and its +cardinal point of insertion can be fully described by the +IfcMaterialProfileSetUsage. These beams are always +represented geometricly by an 'Axis' and a 'SweptSolid' or +'AdvancedSweptSolid' shape representation (or by a 'Clipping' +geometry based on the swept solid), if a 3D geometric +representation is assigned. In addition they have to have a +corresponding IfcMaterialProfileSetUsage assigned. +
                  NOTEÿ View definitions and implementer +agreements may further constrain the applicable geometry types, +e.g. by excluding tapering from an IfcColumnStandardCase +implementation.
                  +
                • +
                • IfcColumn used for all other occurrences of columns, +particularly for columns with changing profile sizes along the +extrusion, or columns defined by non-linear extrusion, or columns +having only 'Brep', or 'SurfaceModel' geometry.
                • +
                +
                HISTORY New entity in IFC Release 1.0
                + +

                Type Use Definition

                +

                IfcColumn defines the occuurence of any column, common +information about column types (or styles) is handled by +IfcColumnType. The IfcColumnType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material layer set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcColumnType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                +

                If no IfcColumnType is attachedÿ(i.e. if only +occurrence information is given) the PredefinedType should +be provided. If set to .USERDEFINED. a user defined value can be +provided by the ObjectType attribute.

                +

                Material Use Definition

                +

                The material of the IfcColumn is defined by the +IfcMaterialProfileSet or as fallback by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

                +
                Note: It is illegal to assign an +IfcMaterialProfileSetUsage to an IfcColumn. Only +the subtype IfcColumnStandardCase supports this +concept.
                +

                Material information can also be given at the +IfcColumnType, defining the common attribute data for all +occurrences of the same type.ÿIt is then accessible by the +inverse IsTypedBy +relationship pointing to +IfcColumnType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterialProfileSet or IfcMaterial. If both are +given, then the material directly assigned to IfcColumn +overrides the material assigned to IfcColumnType.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcColumn are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcColumn are +part of this IFC release:

                + +

                Property sets can also be given at the IfcColumnType, +defining the common property data for all occurrences of the same +type.ÿIt is then accessible by the inverse IsTypedBy relationship pointing to +IfcColumnType.HasPropertySets. If both are given, then the +properties directly assigned to IfcColumn overrides the +properties assigned to IfcColumnType.

                +

                Quantity Use Definition:

                +

                The quantities relating to the IfcColumn are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties. It is accessible by the inverse +IsDefinedBy relationship. The following base quantities +are defined and should be exchanged with the +IfcElementQuantity.MethodOfMeasurement = 'BaseQuantities'. +Other quantities can be defined being subjected to local standard +of measurement with another string value assigned to Name +and a value provided for MethodOfMeasurement. Quanties +shall be never assigned to the IfcColumnType.

                + + +

                Containment Use Definition

                +

                The IfcColumn, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcColumn, is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcColumn, may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this +case it should not be additionally contained in the project +spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                + +

                Geometry Use Definition

                +

                The geometric representation of IfcColumn is given by +the IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local Placement

                +

                The local placement for IfcColumn is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to +a spatial structure element at a higher level, referenced by +that.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Axis', 'Body', +and 'Box' representations are supported. The 'Box' representation +includes the representation type 'BoundingBox' and is explained +at IfcBuildingElement.

                +

                Axis Representation

                +

                The axis geometric representation of IfcColumn is +defined using the 'Axis' representation. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D', 'Curve3D'
                • +
                +

                The axis representation can be used to represent the system +length of a column that may extent the body length of the +column.

                +

                Body Representation

                +

                The body representation of IfcColumn can be represented +using the representation types 'SweptSolid', 'Clipping', +'AdvancedSweptSolid', 'MappedRepresentation', 'SurfaceModel', and +'Brep'. The representation types 'SurfaceModel' and 'Brep' are +explained at IfcBuildingElement.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Profile: all subtypes of IfcProfileDef (with +exception of IfcArbitraryOpenProfileDef)ÿ
                • +
                • Extrusion:ÿAll extrusion directions shall be +supported
                • +
                + +

                Figure 81 illustrates a 'SweptSolid' geometric representation. There are no restrictions or conventions on +how to use the local placement (black), solid of extrusion placement (red) and profile placement (green).

                + + + + +

                Figure 81 — Column swept solid

                + +

                Figure 82 illustrates use of a special profile type (here IfcIShapeProfileDef) for the definition of the IfcExtrudedAreaSolid.

                + + + + +

                Figure 82 — Column extrusion of I-Shape

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the advanced +representation:

                +
                  +
                • Solid: see 'SweptSolid' geometric representation
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Extrusion: see 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid.
                • +
                + +

                Figure 83 illustrates a 'Clipping' geometric representation with use of IfcBooleanClippingResult between +an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body.

                + + + + +

                Figure 83 — Column clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer +agreements can further constrain the allowed swept solid +types.
                  +
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿnot applicable
                • +
                +

                MappedRepresentation Representation Type

                +

                The 'MappedRepresentation' representation type is supported as +it allows for reusing the geometry definition of the beam type at +all occurrences of the same type. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'MappedRepresentation'
                • +
                +

                The same constraints, as given for theÿ 'SweptSolid', +'Clipping', 'AdvancedSweptSolid', 'SurfaceModel' and 'Bre' +geometric representation, shall apply to the +MappedRepresentation of the +IfcRepresentationMap.

                +
                " +1271;IfcColumnStandardCase;" +

                The standard column, +IfcColumnStandardCase, defines a column with certain +constraints for the provision of material usage, parameters and +with certain constraints for the geometric representation. The +IfcColumnStandardCase handles all cases of columns, +that:

                +
                  +
                • have a reference to the IfcMaterialProfileSetUsage +defining the material profile association of the column with the +cardinal point of its insertion relative to the local +placement.
                • +
                • are based on a sweep of a planar profile, or set of profiles, +as defined by the IfcMaterialProfileSet
                • +
                • have an 'Axis' shape representation with constraints provided +below in the geometry use definition
                • +
                • have a 'Body' shape representation with constraints provided +below in the geometry use definition
                • +
                • have a start profile, or set of profiles, that is swept along +the directrix and might be changed uniformly by a taper +definition
                • +
                • are consistent in using the correct cardinal point offset of +the profile as compared to the 'Axis' and 'Body' shape +representation
                • +
                • are extruded perpendicular to the profile definition +plane
                • +
                • +
                  NOTEÿ View definitions and implementer +agreements may further constrain the applicable geometry types, +e.g. by excluding tapering from an IfcBeamStandardCase +implementation.
                  +
                • +
                +
                HISTORY New entity in IFC2x4.
                + +

                Type Use Definition

                +

                IfcColumn defines the occuurence of any column, common +information about column types (or styles) is handled by +IfcColumnType. The IfcColumnType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material layer set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcColumnType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +

                The IfcColumnStandardCase defines in addition that the +IfcColumnType should have a unique +IfcMaterialProfileSet, that is referenced by the +IfcMaterialProfileSetUsage assigned to all occurrences of +this column type.

                + +

                Figure 84 illustrates assignment of IfcMaterialProfileSetUsage and IfcMaterialProfileSet to the IfcColumnStandardCase as the column occurrence and to the IfcColumnType. The same IfcMaterialProfileSet shall be shared by many occurrences of IfcMaterialProfileSetUsage. This relationship shall be consistent to the relationship between the IfcColumnType and the IfcColumnStandardCase.

                + + + + +

                Figure 84 — Column profile usage

                + +

                Figure 85 illustrates cardinal point alignment.

                +
                NOTEÿ It has to be guaranteed that the use of IfcCardinalPointEnum is consistent to the placement of the +extrusion body provided by IfcExtrudedAreaSolid.Position
                +
                NOTEÿ The cardinal points 7 (top left), and 6 (mid-depth right) are assigned according to the +definition at IfcCardinalPointReference
                + + + + +

                Figure 85 — Column cardinal points

                + +

                Figure 86 illustrates assignment of a composite profile by using IfcCompositeProfile for geometric representation and several IfcMaterialProfile's within the IfcMaterialProfileSet. The number of IfcMaterialProfile's within the IfcMaterialProfileSet is restricted to maximal 2 and requires the use of IfcExtrudedAreaSolidTapered, or IfcRevolvedAreaSolidTapered for the correct 'Body' shape representation.

                + + + + +

                Figure 86 — Column composite profiles

                + +

                Material Use Definition

                +

                The material of the IfcColumnStandardCase is defined by +IfcMaterialProfileSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Composite profile columns can be represented by refering to +several IfcMaterialProfile's within the +IfcMaterialProfileSet that is referenced from the +IfcMaterialProfileSetUsage.

                +

                Material information can also be given at the +IfcColumnType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcColumnType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial. See Type Use +Definition for additional agreements for standard +columns.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcColumnStandardCase +are defined at the supertype IfcColumn.

                +Quantity Use Definition +

                The quantities relating to the IfcColumnStandardCase +are defined at the supertype IfcColumn.

                +

                Containment Use Definition

                +

                The containment use definitions relating to the +IfcColumnStandardCase are defined at the supertype +IfcColumn.

                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcColumn is given by +the IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local Placement

                +

                The use of local placement is defined at the supertype +IfcColumn.

                +

                Geometric Representations

                +

                The geometric representation of IfcColumnStandardCase +is defined using the following multiple shape representations for +its definition:

                +
                  +
                • Axis: A three-dimensional open curve (subtype of +IfcBoundedCurve) defining the axis for the standard +column. The cardinal point is determined by the column axis.
                • +
                • Body: A Swept Solid Representation or a CSG +representation defining the 3D shape of the standard column.
                • +
                +
                NOTE It is invalid to exchange a +'SurfaceModel', 'Brep', or 'MappedRepresentation' representation +for the 'Body' shape representation of an +IfcColumnStandardCase.
                +

                Axis Representation

                +

                The axis geometric representation of +IfcColumnStandardCase is defined using the 'Axis' +representation. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve3D'
                • +
                +

                The following additional constraints apply to the 'Axis' +representation, if the 'Body' shape representation has the +RepresentationType : 'SweptSolid':

                +
                  +
                • Axis : IfcPolyline having two Points, or +IfcTrimmedCurve with BasisCurve of Type +IfcLine.
                • +
                • The axis curve lies on the z axis of the object coordinate +system
                • +
                + +

                As shown in Figure 87, the axis shall be defined along the z axis of +the object coordinate system. The axis representation can be used to +represent the system length of a column that may extent the body +length of the column.

                + + + + +

                Figure 87 — Column axis representation

                + +

                As shown in Figure 88, the axis representation shall be used to represent the cardinal point as the offset between the 'Axis' and the extrusion path of the column. The extrusion path is provided as IfcExtrudedAreaSolid.ExtrudedDirection and should be parallel to the 'Axis'. It has to be guaranteed that the value provided by IfcMaterialProfileSetUsage.CardinalPoint is consistent to the IfcExtrudedAreaSolid.Position.

                + + + + +

                Figure 88 — Column axis cardinal point

                + +

                Body Representation

                +

                The body representation of IfcColumnStandardCase can be +represented using the representation types 'SweptSolid', +'Clipping', or 'AdvancedSweptSolid'.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Profile: all subtypes of IfcProfileDef (with +exception of IfcArbitraryOpenProfileDef)
                • +
                • Profile Position : For all single profiles, the +IfcParameterizedProfileDef.Position shall be NIL, or +having Location = 0.,0. and RefDirection = +1.,0.
                • +
                • Extrusion:ÿperpendicular to the profile direction. The +IfcExtrudedAreaSolid.ExtrudedDirection shall be +[0.,0.,1.].
                • +
                • Orientation: The y-axis of the profile, as determined +by IfcSweptAreaSolid.Position.P[2] shall point to the +Y-Axis. It indicates the ""role"" of the column, a role=0° +means y-axis of profile = Y-axis of reference coordinate +system.
                • +
                + +

                Figure 89 illustrates a standard geometric representation with cardinal point applied as 5 (mid-depth centre).

                +

                The following interpretation of dimension parameter applies for rectangular columns:

                +
                  +
                • IfcRectangleProfileDef.YDim interpreted as column width
                • +
                • IfcRectangleProfileDef.XDim interpreted as column depth
                • +
                +

                The following interpretation of dimension parameter applies for circular columns:

                +
                  +
                • IfcCircleProfileDef.Radius interpreted as column radius.
                • +
                + + + + + +

                Figure 89 — Column body extrusion

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the advanced +representation:

                +
                  +
                • Solid: see 'SweptSolid' geometric representation
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿsee 'SweptSolid' geometric +representation
                • +
                • Orientation: see 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or its subtypes).
                • +
                + +

                Figure 90 illustrates a 'Clipping' geometric representation with use of IfcBooleanClippingResult between +an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body, with cardinal point applied as 2 (bottom centre).

                + + + + +

                Figure 90 — Column body clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The 'AdvancedSweptSolid' representation type is a valid body +representation of IfcColumnStandardCase. The following +attribute values for the IfcShapeRepresentation holding +this geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer +agreement can further constrain the allowed swept solid +types.
                  +
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿnot applicable
                • +
                +
                " +1277;IfcMember;" +

                An IfcMember is a +structural member designed to carry loads between or beyond +points of support. It is not required to be load bearing. The +orientation of the member (being horizontal, vertical or sloped) +is not relevant to its definition (in contrary to IfcBeam +and IfcColumn). An IfcMember represents a linear +structural element from an architectural or structural modeling +point of view and shall be used if it cannot be expressed more +specifically as either an IfcBeam or an +IfcColumn.

                +
                NOTE The representation of a member in a +structural analysis model is provided by +IfcStructuralCurveMember being part of an +IfcStructuralAnalysisModel.
                +

                The IFC specification provides two entities for member +occurrences:

                +
                  +
                • IfcMemberStandardCase used for all occurrences of +members, that have a profile defined that is swept along a +directrix. The profile might be changed uniformly by a taper +definition along the directrix. The profile parameter and its +cardinal point of insertion can be fully described by the +IfcMaterialProfileSetUsage. These beams are always +represented geometricly by an 'Axis' and a 'SweptSolid' or +'AdvancedSweptSolid' shape representation (or by a 'Clipping' +geometry based on the swept solid), if a 3D geometric +representation is assigned. In addition they have to have a +corresponding IfcMaterialProfileSetUsage assigned. +
                  NOTEÿ View definitions and implementer +agreements may further constrain the applicable geometry types, +e.g. by excluding tapering from an IfcMemberStandardCase +implementation.
                  +
                • +
                • IfcMember used for all other occurrences of members, +particularly for members with changing profile sizes along the +extrusion, or members defined by non-linear extrusion, or members +having only 'Brep', or 'SurfaceModel' geometry.
                • +
                +
                HISTORY New entity in +IFC Release 2x2 Addendum.
                +

                Type Use Definition

                +

                IfcMember defines the occuurence of any member, common +information about member types (or styles) is handled by +IfcMemberType. The IfcMemberType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material profile set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcMemberType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                +

                If no IfcMemberType is attachedÿ(i.e. if only +occurrence information is given) the PredefinedType should +be provided. If set to .USERDEFINED. a user defined value can be +provided by the ObjectType attribute.

                +

                Material Use Definition

                +

                The material of the IfcMember is defined by the +IfcMaterialProfileSet or as fallback by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Material information can also be given at +theÿIfcMemberType, defining the common attribute data for +all occurrences of the same type.ÿIt is then accessible by the +inverse <<i>IsTypedBy +relationship pointing to IfcMemberType.HasAssociations and +via IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterialProfileSet or IfcMaterial. If both are +given, then the material directly assigned to IfcMember +overrides the material assigned toÿIfcMemberType.

                +

                Property Set Use Definition

                +

                The property sets relating to the IfcMember are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcMember are +part of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcMember and +IfcMemberStandardCase are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quanties shall +be never assigned to the IfcMemberType.

                + +

                Containment Use Definition

                +

                The IfcMember, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcMember is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcMember may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this +case it should not be additionally contained in the project +spatial hierarchy, i.e. +SELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                +

                Geometry Use Definition

                +

                The geometric representation of IfcMember is given by +the IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local Placement

                +

                The local placement for IfcMember is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to +a spatial structure element at a higher level, referenced by +that.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Axis', 'Body', +and 'Box' representations are supported. The 'Box' representation +includes the representation type 'BoundingBox' and is explained +at IfcBuildingElement.

                +

                Axis Representation

                +

                The axis geometric representation of IfcMember is +defined using the 'Axis' representation. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D', 'Curve3D'
                • +
                +

                The axis representation can be used to represent the system +length of a member that may extent the body length of the +member.

                +

                Body Representation

                +

                The body representation of IfcBeam can be represented +using the representation types 'SweptSolid', 'Clipping', +'AdvancedSweptSolid', 'MappedRepresentation', 'SurfaceModel', and +'Brep'. The representation types 'SurfaceModel' and 'Brep' are +explained at IfcBuildingElement.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Profile: all subtypes of IfcProfileDef (with +exception of IfcArbitraryOpenProfileDef)ÿ
                • +
                • Extrusion: All extrusion directions shall be +supported.
                • +
                + +

                Figure 99 illustrates a 'SweptSolid' geometric representation. There are no restrictions or conventions on +how to use the local placement (black), solid of extrusion placement (red) and profile placement (green).

                + + + + +

                Figure 99 — Member swept solid

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the advanced +representation:

                +
                  +
                • Solid: see 'SweptSolid' geometric representation
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿsee 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or its subtypes).
                • +
                + +

                Figure 100 illustrates a 'Clipping' geometric representation with use of IfcBooleanClippingResult between an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body.

                + + + + +

                Figure 100 — Member clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer +agreements can further constrain the allowed swept solid +types.
                  +
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿnot applicable
                • +
                +

                MappedRepresentation Representation Type

                +

                The 'MappedRepresentation' representation type is supported as +it allows for reusing the geometry definition of the beam type at +all occurrences of the same type. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'MappedRepresentation'
                • +
                +

                The same constraints, as given for theÿ 'SweptSolid', +'Clipping', 'AdvancedSweptSolid', 'SurfaceModel' and 'Bre' +geometric representation, shall apply to the +MappedRepresentation of the +IfcRepresentationMap.

                +
                " +1282;IfcMemberStandardCase;" +

                The standard member, +IfcMemberStandardCase, defines a member with certain +constraints for the provision of material usage, parameters and +with certain constraints for the geometric representation. The +IfcMemberStandardCase handles all cases of members, +that:

                +
                  +
                • have a reference to the IfcMaterialProfileSetUsage +defining the material profile association of the member with the +cardinal point of its insertion relative to the local +placement.
                • +
                • are based on a sweep of a planar profile, or set of profiles, +as defined by the IfcMaterialProfileSet
                • +
                • have an 'Axis' shape representation with constraints provided +below in the geometry use definition
                • +
                • have a 'Body' shape representation with constraints provided +below in the geometry use definition
                • +
                • have a start profile, or set of profiles, that is swept along +the directrix and might be changed uniformly by a taper +definition
                • +
                • are consistent in using the correct cardinal point offset of +the profile as compared to the 'Axis' and 'Body' shape +representation
                • +
                • are extruded perpendicular to the profile definition +plane
                • +
                • +
                  NOTEÿ View definitions and implementer +agreements may further constrain the applicable geometry types, +e.g. by excluding tapering from an IfcMemberStandardCase +implementation.
                  +
                • +
                +
                HISTORY New entity in IFC2x4.
                + +

                Type Use Definition

                +

                IfcMember defines the occuurence of any member, common +information about member types (or styles) is handled by +IfcMemberType. The IfcMemberType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material layer set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcMemberType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +

                The IfcMemberStandardCase defines in addition that the +IfcMemberType should have a unique +IfcMaterialProfileSet, that is referenced by the +IfcMaterialProfileSetUsage assigned to all occurrences of +this beam type.

                + +

                Figure 101 illustrates assignment of IfcMaterialProfileSetUsage and IfcMaterialProfileSet to the IfcMemberStandardCase as the member occurrence and to the IfcMemberType. The same IfcMaterialProfileSet shall be shared by many occurrences of IfcMaterialProfileSetUsage. This relationship shall be consistent to the relationship between the IfcMemberType and the IfcMemberStandardCase.

                + + + + +

                Figure 101 — Member profile usage

                + + +

                Figure 102 illustrates assignment of a composite profile by using IfcCompositeProfile for geometric representation and several IfcMaterialProfile's within the IfcMaterialProfileSet. The number of IfcMaterialProfile's within the IfcMaterialProfileSet is restricted to maximal 2 and +requires the use of IfcExtrudedAreaSolidTapered, or IfcRevolvedAreaSolidTapered for the correct 'Body' shape representation.

                + + + + +

                Figure 102 — Member composite profiles

                + +

                Material Use Definition

                +

                The material of the IfcMemberStandardCase is defined by +IfcMaterialProfileSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Composite profile members can be represented by refering to +several IfcMaterialProfile's within the +IfcMaterialProfileSet that is referenced from the +IfcMaterialProfileSetUsage.

                +

                Material information can also be given at the +IfcMemberType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcMemberType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial. See Type Use +Definition for additional agreements for standard +members.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcMemberStandardCase +are defined at the supertype IfcMember.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcMemberStandardCase +are defined at the supertype IfcMember.

                +

                Containment Use Definition

                +

                The containment use definitions relating to the +IfcMemberStandardCase are defined at the supertype +IfcMember.

                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcMemberStandardCase +is given by the IfcProductDefinitionShape, allowing +multiple geometric representations. Included are:

                +

                Local Placement

                +

                The use of local placement is defined at the supertype +IfcMember.

                +

                Geometric Representations

                +

                The geometric representation of IfcMemberStandardCase +is defined using the following multiple shape representations for +its definition:

                +
                  +
                • Axis: A two- or three dimensional open curve +(IfcBoundedCurve) defining the axis for the standard +member. The cardinal point is determined by the member axis.
                • +
                • Body: A Swept Solid Representation or a CSG +representation defining the 3D shape of the standard member.
                • +
                +
                NOTE It is invalid to exchange a +'SurfaceModel', 'Brep', or 'MappedRepresentation' representation +for the 'Body' shape representation of an +IfcMemberStandardCase.
                +

                Axis Representation

                +

                The axis geometric representation of +IfcMemberStandardCase is defined using the 'Axis' +representation. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D', or 'Curve3D'
                • +
                +

                The following additional constraints apply to the 'Axis' +representation:

                +
                  +
                • Axis : IfcPolyline having two Points, or +IfcTrimmedCurve with BasisCurve of Type +IfcLine.
                • +
                + + +

                As shown in Figure 103, the axis representation can be used to represent the system length of a member that may extent the body length of the member.

                + + + + +

                Figure 103 — Member axis representation

                + +

                As shown in Figure 104, the axis representation shall be used to represent the cardinal point as the offset between the 'Axis' and the extrusion path of the member. The extrusion path is provided as IfcExtrudedAreaSolid.ExtrudedDirection and should be parallel to the 'Axis'. It has to be guaranteed that the value provided by IfcMaterialProfileSetUsage.CardinalPoint is consistent to the IfcExtrudedAreaSolid.Position.

                + + + + +

                Figure 104 — Member axis cardinal point

                + + +

                Body Representation

                +

                The body representation of IfcMemberStandardCase can be +represented using the representation types 'SweptSolid', +'Clipping', or 'AdvancedSweptSolid'.

                +

                SweptSolid Representation Type

                +

                The standard geometric representation of +IfcMemberStandardCase is defined using the 'SweptSolid' +representation. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid, +IfcRevolvedAreaSolid shall be supported
                • +
                • Profile: all subtypes of IfcProfileDef (with +exception of IfcArbitraryOpenProfileDef)
                • +
                • Profile Position : For all single profiles, the +IfcParameterizedProfileDef.Position shall be NIL, or +having Location = 0.,0. and RefDirection = +1.,0.
                • +
                • Extrusion:ÿperpendicular to the profile +direction.
                • +
                • Orientation: The y-axis of the profile, as determined +by IfcSweptAreaSolid.Position.P[2] shall point to the +Z-Axis. It indicates the ""role"" of the column, a role=0° +means y-axis of profile = Z-axis of reference coordinate system. +In the exception of a vertical member, the y-axis shall point to +the Y-axis.
                • +
                + +

                Figure 105 illustrates a 'SweptSolid' geometric representation with cardinal point applied as 1 (bottom left).

                +

                The following interpretation of dimension parameter applies for rectangular members:

                +
                  +
                • IfcRectangleProfileDef.YDim interpreted as member width
                • +
                • IfcRectangleProfileDef.XDim interpreted as member depth
                • +
                +

                The following interpretation of dimension parameter applies for circular members:

                +
                  +
                • IfcCircleProfileDef.Radius interpreted as beam radius.
                • +
                + + + + +
                +""standard

                Figure 105 — Member body extrusion

                + +

                Clipping Representation Type

                +

                The advanced geometric representation of +IfcMemberStandardCase is defined using the 'Clipping' +geometry. The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the advanced +representation:

                +
                  +
                • Solid: see 'SweptSolid' geometric representation
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿsee 'SweptSolid' geometric +representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or its subtypes).
                • +
                + +

                Figure 106 illustrates an advanced geometric representation with use of IfcBooleanClippingResult between +an IfcExtrudedAreaSolid and an IfcHalfSpaceSolid to create a clipped body, with cardinal point applied as 4 (mid-depth left).

                + + + + +

                Figure 06 — Member body clipping

                + +

                AdvancedSweptSolid Representation Type

                +

                The 'AdvancedSweptSolid' representation type is a valid body +representation of IfcMemberStandardCase. The following +attribute values for the IfcShapeRepresentation holding +this geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'AdvancedSweptSolid'
                • +
                +

                The following additional constraints apply to the +'AdvancedSweptSolid' representation type:

                +
                  +
                • Solid: IfcSurfaceCurveSweptAreaSolid, +IfcFixedReferenceSweptAreaSolid, +IfcExtrudedAreaSolidTapered, +IfcRevolvedAreaSolidTapered shall be supported. +
                  NOTE View definitions and implementer +agreement can further constrain the allowed swept solid +types.
                  +
                  NOTE Using IfcExtrudedAreaSolidTapered, +or IfcRevolvedAreaSolidTapered requires the use of two +IfcMaterialProfile's within the +IfcMaterialProfileSet assinged to the +IfcBeamStandardCase
                  +
                • +
                • Profile: see 'SweptSolid' geometric +representation
                • +
                • Profile Position : see 'SweptSolid' geometric +representation
                • +
                • Extrusion:ÿnot applicable
                • +
                +
                " +1299;IfcWall;" +

                Definition from ISO 6707-1:1989: Vertical construction +usually in masonry or in concrete which bounds or subdivides a +construction works and fulfils a load bearing or retaining +function.

                +

                Definition from IAI: The wall represents a vertical +construction that bounds or subdivides spaces. Wall are usually +vertical, or nearly vertical, planar elements, often designed to +bear structural loads. A wall is howeverÿnot required to be load +bearing.

                +
                NOTE NOTE There is a representation of walls +for structural analysis provided by a proper subtype of +IfcStructuralMember being part of the +IfcStructuralAnalysisModel.
                +
                +NOTE An arbitrary planar element to which this semantic +information is not applicable, e.g. is not predominantly +vertical, shall be modeled as +IfcPlate
                +

                A wall may have openings, such as wall openings, openings used +for windows or doors, or niches and recesses. They are defined by +an IfcOpeningElement attached to the wall using the +inverse relationship HasOpenings pointing to +IfcRelVoidsElement.

                +

                The IFC specification provides two entities for wall +occurrences:

                +
                  +
                • IfcWallStandardCase ÿused for all occurrences of +walls, that have a non-changing thickness along the wall path and +where the thickness parameter can be fully described by a +material layer set. These walls are always represented +geometrically by an 'Axis' and a 'SweptSolid' shape +representation (or by a 'Clipping' geometry based on +'SweptSolid'), if a 3D geometric representation is assigned. In +addition they have to have a corresponding +IfcMaterialProfileSetUsage assigned.
                • +
                • IfcWallElementedCase used for occurrences of walls +which are aggregated from subordinate elements, following +specific decomposition rules expressed by the mandatory use of +IfcRelAggregates relationship.
                • +
                • IfcWall ÿused for all other occurrences of wall, +particularly for walls with changing thickness along the wall +path (e.g. polygonal walls), or walls with a non-rectangular +cross sections (e.g. L-shaped retaining walls), and walls having +an extrusion axis that is unequal to the global Z axis of the +project (i.e. non-vertical walls), or walls having only 'Brep', +or 'SurfaceModel' geometry.
                • +
                +
                HISTORY New entity in +IFC Release 1.0
                +

                Type Use Definition

                +

                IfcWall defines the occurrence of any wall, common +information aboutÿwall types (or styles) is handled by +IfcWallType. The IfcWallType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material layer set, common set of properties and common +shape representations (using IfcRepresentationMap). The +IfcWallType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                +

                If no IfcWallType is attachedÿ(i.e. if only occurrence +information is given) the PredefinedType should be +provided. If set to .USERDEFINED. a user defined value can be +provided by the ObjectType attribute.

                +

                Material Use Definition

                +

                The material of the IfcWall is defined by +IfcMaterialLayerSet and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Multi-layer walls can be represented by referring to several +IfcMaterialLayer's within the +IfcMaterialLayerSet.ÿ

                +
                Note: It is illegal to assign an +IfcMaterialLayerSetUsage to an IfcWall. Only the +subtype IfcWallStandardCase supports this +concept.
                +

                Material information can also be given at the +IfcWallType, defining the common attribute data for all +occurrences of the same type.ÿIt is then in addition accessible +by the inverse IsTypedBy +relationship pointing to IfcWallType.HasAssociations and +via IfcRelAssociatesMaterial.RelatingMaterial.

                +

                Property Set Use Definition

                +

                The property sets relating to the IfcWall are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcWall are part +of this IFC release:

                + +

                Property sets can also be given at the IfcWallType, +defining the common property data for all occurrences of the same +type.ÿIt is then accessible by the inverse IsTypedBy relationship pointing to +IfcWallType.HasPropertySets. If both are given, then the +properties directly assigned to IfcWall overrides the +properties assigned to IfcWallType.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcWall and +IfcWallStandardCase are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quantities shall +never be assigned to the IfcWallType.

                + +

                Containment Use Definition

                +

                The IfcWall (and the subtype +IfcWallStandardCase) as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierarchical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcWall is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • TheÿIfcWall may be aggregated into an element assembly +using the objectified relationship IfcRelAggregates, +referring to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype.
                  +In this case the wall should not be additionally contained in the +project spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                +

                TheÿIfcWallÿmay also be an aggregate i.e. being +composed by other elements and acting as an assembly using the +objectified relationship IfcRelAggregates, referring to it +by its inverse attribute +SELF\IfcObjectDefinition.IsDecomposedBy. Components of a +wall are described by instances of IfcBuildingElementPart +that are aggregated to form a complex wall.
                +In this case, the containedÿIfcBuildingElementPart's +should not be additionally contained in the project spatial +hierarchy, i.e. the inverse attribute +SELF\IfcElement.ContainedInStructure of +IfcBuildingElementPart should be NIL.

                +

                Geometry Use Definition

                +

                The geometric representation of IfcWall is given by the +IfcProductDefinitionShape, allowing multiple geometric +representation. Included are:

                +

                Local Placement

                +

                The local placement for IfcWall is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Axis', 'Surface', +'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +

                Axis Representation

                +

                The axis geometric representation of IfcWall is defined +using the 'Axis' representation.

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                +
                NOTE The 'Axis' is not used to locate the +material layer set, only the subtype IfcWallStandardCase +provides this capability.
                +

                Surface Representation

                +

                The surfacic geometric representation of IfcWall is +defined using the 'Surface' representation.

                +
                  +
                • RepresentationIdentifier : 'Surface'
                • +
                • RepresentationType : 'Surface3D'
                • +
                +
                NOTE The 'Surface' can be used to define a +surfacic model of the building (e.g. for analytical purposes, or +for reduced Level of Detail representation).
                +

                Body Representation

                +

                The body representation of IfcWall can be represented +using the representation types 'SweptSolid', 'Clipping', +'SurfaceModel', and 'Brep'. The representation types +'SurfaceModel' and 'Brep' are explained at +IfcBuildingElement.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                If the wall body can be described by a +vertical extrusion of a polygonal footprint with constant +thickness along the axis (where vertical = into the direction of +the global Z axis), the subtype IfcWallStandardCase should +be used. If the extrusion is not equal to global Z, then the +IfcWall should be used.
                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid is required,
                • +
                • Profile: IfcArbitraryClosedProfileDef is +required.
                • +
                • Extrusion:ÿAll extrusion directions shall be +supported.
                • +
                +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The same additional constraints apply as defined for the +'SweptSolid' representation.

                +

                Connection Geometry

                +

                The connection between two walls is represented by the +IfcRelConnectsPathElements. The use of the parameter of +that relationship object is defined at the level of the subtypes +of IfcWall and at the +IfcRelConnectsPathElements.

                +
                " +1305;IfcWallStandardCase;" +

                The IfcWallStandardCase defines a wall with certain +constraints for the provision of parameters and with certain +constraints for the geometric representation. The +IfcWallStandardCase handles all cases of walls, that are +extruded vertically:

                +
                  +
                • along the positive z axis of the wall object coordinate system, +and
                • +
                • along the positve z axis of the global (world) coordinate +system
                • +
                +

                and have a single thickness along the path for each wall layer, +i.e.:

                +
                  +
                • parallel sides for straight walls
                • +
                • co-centric sides for curved walls.
                • +
                +

                and have either:

                +
                  +
                • a straight line axis (straight wall), or
                • +
                • a circular arc axis (round wall).
                • +
                +

                and shall not have

                +
                  +
                • aggregated components, that is, parts aggregated to a wall by IfcRelAggregates
                • +
                • shape representation for 'Body' not being an extrusion, or clipped extrusion
                • +
                +

                The following parameter have to be provided:

                +
                  +
                • Wall height, taken from the depth of extrusion, provided by the geometric representation.
                • +
                • Wall thickness, taken from the material layer set usage, attached to the wall
                • +
                • Wall offset from axis, taken from the material layer set usage, attached to the wall
                • +
                +

                The IfcWallStandardCase requires the provision of the +wall axis either a straight line that is parallel to the x-axis of +the object coordinate system, or a circular arc where the tangent +at start is parallel to the x-axis of the object coordinate system. +The direction of the wall axis shall be the positive direction of +that x-axis.

                +

                The material of the wall is defined by the +IfcMaterialLayerSetUsage and is attached by the +IfcRelAssociatesMaterial objectified relationship. It is +accessible by the inverse HasAssociations relationship. +The material layer set usage has to be given (enforced by where +rule).

                +
                HISTORY New entity in IFC Release 2x.
                + +

                Type Use Definition

                +

                The type information relating to the +IfcWallStandardCase is defined at the supertype +IfcWall. As an additional use agreement for standard +walls, the IfcWallType should have a unique +IfcMaterialLayerSet, that is referenced by +the IfcMaterialLayerSetUsage assigned to all +occurrences of this IfcWallType.

                + +

                Figure 134 illustrates assignment of IfcMaterialLayerSetUsage and IfcMaterialLayerSet to the wall type and the wall occurrence.

                + + + + +

                Figure 134

                + +

                Material Use Definition

                +

                The material of the IfcWallStandardCase is defined by +IfcMaterialLayerSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Multi-layer walls can be represented by refering to several +IfcMaterialLayer's within the IfcMaterialLayerSet +that is referenced from the +IfcMaterialLayerSetUsage. 

                +

                Material information can also be given at the +IfcWallType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcSlabType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial. See Type Use +Definition for additional agreements for standard slabs.

                + +

                Figure 134 illustrates material layer usage, where the following conventions shall be met:

                +
                  +
                • The reference coordinate system is the local coordinate system established by the ObjectPlacement of the IfcWallStandardCase.
                • +
                • The reference axis is the axis defined by the IfcShapeRepresentation with RepresentationType='Axis' as one of the +Representation.Representations of the IfcWallStandardCase.
                • +
                • The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is given as a distance from this axis.
                • +
                • The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is the distance parallel to the reference axis and always within the base +(XY) plane of the reference coordinate system. A positve value of IfcMaterialLayerSetUsage.OffsetFromReferenceLine would +then point into the positive y-axis of the reference coordinate system.
                • +
                • The IfcMaterialLayerSetUsage.DirectionSense defines how the IfcMaterialLayer's are assigned to the reference axis. POSITIVE means in direction to the positive y-axis of the reference coordinate system.
                • +
                • The Thickness of each IfcMaterialLayer is provided starting from the OffsetFromReferenceLine and in the direction given by DirectionSense. It is applied without any gap or overlap between two consecutive layers. The TotalThickness of the IfcMaterialLayerSet is the sum of all layer thicknesses.
                • +
                • The IfcMaterialLayerSetUsage.LayerSetDirection is always AXIS2.
                • +
                + + + + +

                Figure 134 — Wall material layers

                + +

                Property Set Use Definition:

                +

                The property sets relating to the IfcWallStandardCase +are defined at the supertype IfcWall.

                +

                Quantity Use Definition:

                +

                The quantities relating to the IfcWallStandardCase are +defined at the supertype IfcWall.

                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcWallStandardCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

                +

                Local Placement

                +

                The use of local placement defining the wall object coordinate +system is defined at the supertype IfcWall.

                +

                Geometric Representation

                +

                The standard geometric representation of +IfcWallStandardCase is defined using the following +multiple shape representations for its definition:

                +
                  +
                • Axis: A two-dimensional open curve +(IfcBoundedCurve) defining the axis for the standard wall. +The material layer offset is measured from the wall axis.
                • +
                • Body: A Swept Solid Representation or a CSG +representation defining the 3D shape of the standard wall
                • +
                +
                NOTE  It is invalid to exhange a +'SurfaceModel', or 'Brep' or 'MappedRepresentation' representation +for the 'Body' shape representation of an +IfcWallStandardCase.
                +

                Axis Representation

                +

                The wall axis is represented by a two-dimensional open curve +within a particular shape representation. The wall axis is used to +apply the material layer set usage parameter to the wall geometry. +The following attribute values shall be used

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                + + +

                Figure 135 illustrates an axis representation for a straight wall. In case of a straight wall, the set of items shall +include a single geometric representation item of type IfcPolyline or IfcTrimmedCurve with the BasisCurve being an IfcLine. The IfcPolyline or IfcTrimmedCurve shall be parallel (here in a special case co-linear) to the x-axis +of the object coordinate system. The direction shall be identical to the direction of the x-axis.

                + +

                Figure 136 illustrates an axis representation for a curved wall. In case of a curved wall, the set of items shall include +a single geometric representation item of type IfcTrimmedCurve. The curve shall have a BasisCurve of type IfcCircle. The tangent of the IfcTrimmedCurve shall be parallel at start to the x-axis of the object coordinate system. The direction shall be identical to the direction of the x-axis.

                + + + + + + + + + + +

                Figure 135 — Wall axis straight

                Figure 136 — Wall axis curved

                + +

                Body Representation

                +

                The body representation of IfcWallStandardCase is +defined by using 'SweptSolid' representation for walls without +clippings or 'Clipping' representation for walls with clippings +(e.g. under sloped roof slabs).

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid is required,
                • +
                • Profile: IfcArbitraryClosedProfileDef and +IfcRectangleProfileDef shall be supported.
                • +
                • Extrusion: The profile shall be extruded vertically, +i.e., in the direction of the z-axis of the co-ordinate system of +the referred spatial structure element. It might be further +constraint to be in the direction of the global z-axis in +implementers agreements. The extrusion axis shall be perpendicular +to the swept profile, i.e. pointing into the direction of the +z-axis of the Position of the IfcExtrudedAreaSolid.
                • +
                + +

                The profile of a wall is described in the ground view and extruded vertically. The profile (also identical with the foot print of the wall) is defined by the IfcArbitraryClosedProfileDef (excluding its subtypes). The profile is given with all wall connections already resolved.

                + +

                Figure 137 illustrates a body representation for a straight wall. In case of a straight wall, the two sides of the profile shall be parallel to the wall axis, that is, the wall has a single unchanged thickness.

                + +

                Figure 138 illustrates a body representation for a curved wall. In case of a curved wall, the two sides of the profile shall be parallel (with defined offset) to the wall axis, that is, the wall has a single unchanged thickness.

                + + + + + + + + + + +

                Figure 137 — Wall body extrusion straight

                Figure 138 — Wall body extrusion curved

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the 'Clipping' +representation:

                +
                  +
                • Solid: see standard geometric representation
                • +
                • Profile: see standard geometric representation
                • +
                • Extrusion: see standard geometric representation
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid (or subtypes).
                • +
                + +

                Figure 139 illustrates a clipping for a straight wall using an IfcPolygonalBoundedHalfSpace as SecondOperand in +the IfcBooleanClippingResult.

                + +

                Figure 140 illustrates a clipping for a curved wall using an IfcHalfSpaceSolid as SecondOperand in the +IfcBooleanClippingResult.

                + + + + + + + + + + +

                Figure 139 — Wall body clipping straight

                Figure 140 — Wall body clipping curved

                + +
                " +1307;IfcWallElementedCase;" +

                The IfcWallElementedCase +defines a wall with certain constraints for the provision of its +components. The IfcWallElementedCase handles all cases of +walls, that are decomposed into parts:ÿ

                +
                  +
                • having components being assigned to the +IfcWallElementedCase using the IfcRelAggregates +relationship accessible by the inverse relationship +IsDecomposedBy.
                • +
                • applying the constraint that the parts within the +decomposition shall be of type IfcMember, IfcPlate, +IfcBuildingElementPart or +IfcBuildingElementProxy.
                • +
                +
                HISTORY New entity in +IFC2x4.
                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcWallElementedCase +are defined at the supertype IfcWall.

                +
                NOTE The parts within the decomposition +relationship may define their own property +sets.
                +

                Quantity Use Definition:

                +

                The quantities relating to the IfcWallElementedCase are +defined at the supertype IfcWall.

                +
                NOTE The parts within the decomposition +relationship may define their own individual +quantities.
                + +

                Voiding Use Definition:

                + +

                As shown in Figure 132, openings within the composite wall are directly assigned to IfcWallElementedCase using IfcRelVoidsElement pointing to IfcOpeningElement and apply to all aggregated parts. If individual parts have cutting and other voiding features, then the decomposed parts have a separate voiding relationship IfcRelVoidsElement pointing to IfcVoidingFeature.

                + + + + +

                Figure 132 — Wall elemented voiding

                + +

                Decomposition Use Definition:

                +

                The following guidance is provided for the components of the +IfcWallElementedCase. The following component entity types +should be used:

                +
                  +
                • Framed Walls +
                    +
                  • studs : IfcMember
                  • +
                  • plates : IfcMember
                  • +
                  • drywall : IfcPlate
                  • +
                  • wood sheathing : IfcPlate
                  • +
                  • insulation : IfcBuildingElementPart
                  • +
                  • precast panel : IfcBuildingElementPart
                  • +
                  • others : IfcBuildingElementPart
                  • +
                  +
                • +
                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcWallElementedCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

                +

                Local Placement

                +

                The use of local placement is defined at the supertype +IfcWall. The local placement of the +IfcWallElementedCase defines the parent coordinate systems +for the parts within the decomposition. All parts shall be +positioned relative to the IfcWallElementedCase.

                +

                Geometric Representation

                +

                The standard geometric representation of +IfcWallElementedCase is defined using the following +multiple shape representations for its definition:

                +
                  +
                • Axis: A two-dimensional open curve being a subtype of +IfcBoundedCurve defining the axis for the elemented wall. +It maybe used as a simplified representation directly at the +elemented wall.
                • +
                • Surface: A three-dimensional surface being a subtype +of IfcBoundedSurface defining the reference surface for +the elemented wall. It maybe used as a simplified representation +directly at the elemented wall.
                • +
                +
                NOTEÿ It is invalid to exhange a 'Body' shape +representation of an IfcWallElementedCase. The body +geometry is defined by the parts within the +decomposition.
                +

                Axis Representation

                +

                The wall axis is represented by a two-dimensional open curve +within a particular shape representation.

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                +

                Surface Representation

                +

                The surfacic geometric representation of +IfcWallElementedCase is defined using the 'Surface' +representation.

                +
                  +
                • RepresentationIdentifier : 'Surface'
                • +
                • RepresentationType : 'Surface3D'
                • +
                +
                NOTE The 'Surface' can be used to define a +surfacic model of the building (e.g. for analytical purposes, or +for reduced Level of Detail representation). It could suppress +the geometric details of the parts in the +decomposition.
                +
                " +1318;IfcSlab;" +

                A slab is a component of the +construction that normally encloses a space vertically. The slab +may provide the lower support (floor) or upper construction (roof +slab) in any space in a building. It shall be noted, that only +the core or constructional part of this construction is +considered to be a slap. The upper finish (flooring, roofing) and +the lower finish (ceiling, suspended ceiling) are considered to +be coverings. A special type of slab is the landing, described as +a floor section to which one or more stair flights or ramp +flights connect.

                +
                NOTE There is a representation of slabs for +structural analysis provided by a proper subtype of +IfcStructuralMember being part of the +IfcStructuralAnalysisModel.
                +
                +NOTE ÿAn arbitrary planar element to which this semantic +information is not applicable or irrelevant shall be modeled as +IfcPlate.
                +

                A slab may have openings, such as floor openings, or recesses. +They are defined by an IfcOpeningElement attached to the +slab using the inverse relationship HasOpenings pointing +to IfcRelVoidsElement.

                +

                The IFC specification provides three entities for slab +occurrences:

                +
                  +
                • IfcSlabStandardCase used for all occurrences of slabs, +that are prismatic and where the thickness parameter can be fully +described by the IfcMaterialLayerSetUsage. These slabs are +always represented geometrically by a 'SweptSolid' geometry (or +by a 'Clipping' geometry based on 'SweptSolid'), if a 3D +geometric representation is assigned. In addition they have to +have a corresponding IfcMaterialLayerSetUsage +assigned.
                • +
                • IfcSlabElementedCase used for occurrences of slabs +which are aggregated from subordinate elements, following +specific decomposition rules expressed by the mandatory use of +IfcRelAggregates relationship.
                • +
                • IfcSlab used for all other occurrences of slabs, +particularly for slabs with changing thickness, or slabs with non +planar surfaces, and slabs having only 'SweptSolid' or 'Brep' +geometry.
                • +
                +
                HISTORY New entity in IFC Release 2.0, it is a merger of the two previous entities +IfcFloor, IfcRoofSlab, introduced in IFC Release 1.0
                + +

                Type Use Definition

                +

                The IfcSlab defines the occurrence of any slab, common +information about slab types (or styles) is handled by +IfcSlabType. The IfcSlabType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common set of properties, common material layer set, and common +shape representations (using IfcRepresentationMap). The +IfcSlabType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

                +

                If no IfcSlabType is attachedÿ(i.e. if only occurrence +information is given) the PredefinedType should be +provided. Values of the enumeration are .FLOOR. (the default), +.ROOF., .LANDING., .BASESLAB. If set to .USERDEFINED. a user +defined value can be provided by the ObjectType +attribute.

                +

                Material Use Definition

                +

                The material of the IfcSlab is defined by +IfcMaterialLayerSet, or IfcMaterial and attached by +the IfcRelAssociatesMaterial.RelatingMaterial. It +is accessible by the inverse HasAssociations relationship. +Multi-layer slabs can be represented by referring to several +IfcMaterialLayer's within the +IfcMaterialLayerSet.

                +
                NOTE It is illegal to assign an +IfcMaterialLayerSetUsage to an IfcSlab. Only the +subtype IfcSlabStandardCase supports this +concept.
                +
                NOTE Prismatic slabs, where the main face of +the slab is extruded along the slab thickness, are exchanged as +IfcSlabStandardCase, The material for +IfcSlabStandardCase shall be defined +byÿIfcMaterialLayerSetUsage. Multi-layer slabs can be +represented by referring to several IfcMaterialLayer's +within the IfcMaterialLayerSet.ÿ
                +

                Material information can also be given at the +IfcSlabType, defining the common attribute data for all +occurrences of the same type.ÿIt is then accessible by the +inverse IsTypedBy +relationship pointing to IfcSlabType.HasAssociations and +via IfcRelAssociatesMaterial.RelatingMaterial.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcSlab are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcSlab are part +of this IFC release:

                + +

                Property sets can also be given at the IfcSlabType, +defining the common property data for all occurrences of the same +type.ÿIt is then accessible by the inverse IsTypedBy relationship pointing to +IfcSlabType.HasPropertySets. If both are given, then the +properties directly assigned to IfcSlab overrides the +properties assigned to IfcSlabType.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcSlab and +IfcSlabStandardCase are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quantities shall +never be assigned to the IfcSlabType.

                + +

                Containment Use Definition

                +

                The IfcSlab, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierarchical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • TheÿIfcSlab is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • TheÿIfcSlab may be aggregated into an element assembly +using the objectified relationship IfcRelAggregates, +referring to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype.
                  +In this case it should not be additionally contained in the +project spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                +

                The IfcSlabÿmay also be an aggregate i.e. being +composed by other elements and acting as an assembly using the +objectified relationship IfcRelAggregates, referring to it +by its inverse attribute +SELF\IfcObjectDefinition.IsDecomposedBy. Components of a +slab are described by instances of subtypes of +IfcBuildingElement, with IfcBuildingElementPart as +a special focus subtype that are aggregated to form a complex +slab. In this case, the contained elements should not be +additionally contained in the project spatial hierarchy, i.e. the +inverse attribute SELF\IfcElement.ContainedInStructure of +IfcBuildingElementPart (or other subtypes of +IfcBuildingElement) should be NIL.

                +

                Geometry Use Definition

                +

                The geometric representation of IfcSlab is given by the +IfcProductDefinitionShape, allowing multiple geometric +representation. Included are:

                +
                NOTE. If the IfcSlab is of type Landing +and is used within an IfcStair or IfcRamp, the +special agreements to handle stair and ramp geometry will also +affect the geometric representation of the +IfcSlab.
                +

                Local Placement

                +

                The local placement for IfcSlab is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the placement +of the local placement of the same +IfcSpatialStructureElement that is used in the +ContainedInStructure inverse attribute or to a referenced +spatial structure element at a higher level.
                • +
                • If the IfcSlab is of type Landing and is used by an +IfcStair or IfcRamp, and this container class +defines its own local placement, then the PlacementRelTo +relationship of IfcLocalPlacement shall point (if given) +to the local placement of the aggregate.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Surface', +'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +

                Surface Representation

                +

                The surfacic geometric representation of IfcSlab is +defined using the 'Surface' representation.

                +
                  +
                • RepresentationIdentifier : 'Surface'
                • +
                • RepresentationType : 'Surface3D'
                • +
                +
                NOTE The 'Surface' can be used to define a +surfacic model of the building (e.g. for analytical purposes, or +for reduced Level of Detail representation).
                +

                Body Representation

                +

                The body representation of IfcSlab can be represented +using the representation types 'SweptSolid', 'Clipping', +'SurfaceModel', and 'Brep'. The representation types +'SurfaceModel' and 'Brep' are explained at +IfcBuildingElement.

                +

                SweptSolid Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                If a corresponding material definition using +IfcMaterialLayerSetUsage can be assigned, the subtype +IfcSlabStandardCase shall be used.
                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the swept solid +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid is required,
                • +
                • Profile: IfcArbitraryClosedProfileDef, +IfcRectangleProfileDef, IfcCircleProfileDef, +IfcEllipseProfileDef shall be supported.
                • +
                • Extrusion: The profile can be extruded perpendicularly +or non-perpendicularly to the plane of the swept profile.
                • +
                + +

                Figure 120 illustrates a 'SweptSolid' geometric representation.

                +
                NOTE The following interpretation of dimension parameter applies for polygonal slabs (in ground floor view): +
                  +
                • IfcArbitraryClosedProfileDef.OuterCurve: closed bounded curve interpreted as area (or foot print) of the slab.
                • +
                +
                + + + + +

                Figure 120 — Slab body extrusion

                + +

                Clipping Representation Type

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the 'Clipping' +representation:

                +
                  +
                • Solid: see 'SweptSolid' shape representation,
                • +
                • Profile:ÿsee 'SweptSolid' shape representation,
                • +
                • Extrusion:ÿsee 'SweptSolid' shape representation,
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid.
                • +
                + +

                Figure 121 illustrates a 'Clipping' geometric representation with definition of a roof slab using advanced +geometric representation. The profile is extruded non-perpendicular and the slab body is clipped at the eave.

                + + + + +

                Figure 121 — Slab body clipping

                + +
                " +1324;IfcSlabStandardCase;" +

                The standard slab, +IfcSlabStandardCase, defines a slab with certain constraints +for the provision of material usage, parameters and with certain +constraints for the geometric representation. The +IfcSlabStandardCase handles all cases of slabs, that:

                +
                  +
                • have a reference to the IfcMaterialLayerSetUsage +defining the material layers of the slab with thicknesses
                • +
                • are based on an extrusion of a planar surface as defined by the +slab profile
                • +
                • have a constant thickness along the extrusion direction
                • +
                • are consistent in using the correct material layer set offset +to the base planar surface in regard to the shape +representation
                • +
                • are extruded either perpendicular or slanted to the plane +surface
                • +
                +

                The definitions of slab openings and niches are the same as +given at the supertype IfcSlab. The same agreements to the +special types of slabs, as defined in the PredefinedType +attribute apply as well.

                +
                HISTORY New entity in +IFC2x Edition 4.
                +

                Type Use Definition

                +

                The IfcSlabStandardCase defines the occuurence of any +slab, common information about slab types (or styles) is handled by +IfcSlabType. The IfcSlabType (if present) may +establish the common type name, usage (or predefined) type, +common set of properties, common material layer set, and common +shape representations (using IfcRepresentationMap). The +IfcSlabType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy attribute.

                +

                The IfcSlabStandardCase defines in addition that the +IfcSlabType should have a unique IfcMaterialLayerSet, +that is referenced by the IfcMaterialLayerSetUsage +assigned to all occurrences of this slab type.

                + +

                Figure 123 illustrates assignment of IfcMaterialLayerSetUsage and IfcMaterialLayerSet to the IfcSlabStandardCase as the slab occurrence and to the IfcSlabType. The same IfcMaterialLayerSet shall be shared by many occurrences of IfcMaterialLayerSetUsage. This relationship shall be consistent to the relationship between the IfcSlabType and the IfcSlabStandardCase.

                + + + + +

                Figure 123 — Slab type definition

                + +

                Material Use Definition

                +

                The material of the IfcSlabStandardCase is defined by +IfcMaterialLayerSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Multi-layer slabs can be represented by refering to several +IfcMaterialLayer's within the IfcMaterialLayerSet +that is referenced from the +IfcMaterialLayerSetUsage. 

                +

                Material information can also be given at the +IfcSlabType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcSlabType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial. See Type Use +Definition for additional agreements for standard slabs.

                + +

                Figure 123 illustrates slab material usage, where the following conventions shall be met:

                +
                  +
                • The reference coordinate system is the coordinate system established by the IfcExtrudedAreaSolid.Position.
                • +
                • The reference plane is the plane defined by the extruded profile of IfcExtrudedAreaSolid.SweptSolid. The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is given as a distance from this plane.
                • +
                • The IfcMaterialLayerSetUsage.DirectionSense defines how the IfcMaterialLayer's are assigned to the reference plane. POSITIVE means in direction to the positive z-axis of the reference coordinate system.
                • +
                • The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is the distance parallel to the reference plane and always perpendicular to the base (XY) plane of the reference coordinate system. This is independent of a potential non-perpendicular extrusion given by IfcExtrudedAreaSolid.ExtrudedDirection <> 0.,0.,1. A positive value of IfcMaterialLayerSetUsage.OffsetFromReferenceLine would then point into the positive z-axis of the reference coordinate system.
                • +
                • The Thickness of each IfcMaterialLayer shall be the parallel distance (measured perpendicular to the base plane). The TotalThickness of the IfcMaterialLayerSet is the sum of all layer thicknesses and in case of a perpendicular extrusion identical with IfcExtrudedAreaSolid.Depth
                • +
                • The IfcMaterialLayerSetUsage.LayerSetDirection is always AXIS3.
                • +
                + + + + + +
                ++""slab +
                ++""roof

                Figure 124 — Slab material layers

                + +

                Property Set Use Definition:

                +

                The property sets relating to the IfcSlabStandardCase are +defined at the supertype IfcSlab.

                +

                Quantity Use Definition

                +

                The quantities relating to the IfcSlabStandardCase are +defined at the supertype IfcSlab.

                +

                Containment Use Definition

                +

                The containment use definitions relating to the +IfcSlabStandardCase are defined at the supertype +IfcSlab.

                + +

                Geometry Use Definitions

                +

                The geometric representation of IfcSlabStandardCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

                +
                +

                NOTE If the IfcSlabStandardCase is of type Landing +and is used within an IfcStair or IfcRamp, the +special agreements to handle stair and ramp geometry will also +affect the geometric representation of the +IfcSlabStandardCase.

                +
                +

                Local Placement

                +

                The use of local placement is defined at the supertype +IfcSlab.

                +

                Geometric Representations

                +

                Currently, the use of 'SweptSolid' and 'Clipping' +representations is supported. In addition the general +representation type 'BoundingBox' is allowed. The geometry use +definitions for 'BoundingBox', is explained at +IfcBuildingElement.

                +

                SweptSolid Representation

                +

                The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used for the 'SweptSolid' representation:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the swept solid +representation:

                +
                  +
                • Solid: IfcExtrudedAreaSolid is required,
                • +
                • Profile: IfcArbitraryClosedProfileDef, +IfcRectangleProfileDef, IfcCircleProfileDef, +IfcEllipseProfileDef shall be supported.
                • +
                • Extrusion: The profile can be extruded perpendicularly +or non-perpendicularly to the plane of the swept profile.
                • +
                • Material: The definition of the +IfcMaterialLayerSetUsage, particularly of the +OffsetFromReferenceLine and the +ForLayerSet.TotalThickness, has to be consistent to the +'SweptSolid' representation.
                • +
                + +

                Figure 125 illustrates a 'SweptSolid' geometric representation.

                +
                NOTE The following interpretation of dimension parameter applies for polygonal slabs (in ground floor view): +
                  +
                • IfcArbitraryClosedProfileDef.OuterCurve: closed bounded curve interpreted as area (or foot print) of the slab.
                • +
                +
                + + + + +

                Figure 125 — Slab body extrusion

                + +

                Clipping representation

                +

                The 'Clipping' geometric representation of +IfcSlabStandardCase is defined using the swept area geometry +with additional clippings applied. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'Clipping'
                • +
                +

                The following constraints apply to the 'Clipping' +representation:

                +
                  +
                • Solid: see 'SweptSolid' shape representation,
                • +
                • Profile: see 'SweptSolid' shape +representation,
                • +
                • Extrusion: see 'SweptSolid' shape +representation,
                • +
                • Material: see 'SweptSolid' shape +representation,
                • +
                • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid.
                • +
                + +

                Figure 126 illustrates a 'Clipping' geometric representation with definition of a roof slab using advanced geometric representation. The profile is extruded non-perpendicular and the slab body is clipped at the eave.

                + + + + +

                Figure 126 — Slab body clipping

                + +
                " +1326;IfcSlabElementedCase;" +

                The IfcSlabElementedCase +defines a slab with certain constraints for the provision of its +components. The IfcSlabElementedCase handles all cases of +slabs, that are decomposed into parts:ÿ

                +
                  +
                • having components being assigned to the +IfcSlabElementedCase using the IfcRelAggregates +relationship accessible by the inverse relationship +IsDecomposedBy.
                • +
                • applying the constraint that the parts within the +decomposition shall be of type IfcBeam, IfcMember, +IfcPlate, IfcBuildingElementPart or +IfcBuildingElementProxy.
                • +
                +
                HISTORY New entity in +IFC2x4.
                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcSlabElementedCase +are defined at the supertype IfcSlab.

                +
                NOTE The parts within the decomposition +relationship may define their own property +sets.
                +

                Quantity Use Definition:

                +

                The quantities relating to the IfcSlabElementedCase are +defined at the supertype IfcSlab.

                +
                NOTE The parts within the decomposition +relationship may define their own individual +quantities.
                + +

                Voiding Use Definition:

                + +

                As shown in Figure 122, openings within the composite slab are directly assigned to IfcSlabElementedCase using IfcRelVoidsElement pointing to IfcOpeningElement and apply to all aggregated parts. If individual parts have cutting and other voiding features, then the decomposed parts have a separate voiding relationship IfcRelVoidsElement pointing to IfcVoidingFeature.

                + + + + +

                Figure 122 — Slab elemented voiding

                + +

                Decomposition Use Definition:

                +

                The following guidance is provided for the components of the +IfcSlabElementedCase. The following component entity types +should be used:

                +
                  +
                • Precast hollow core slabs +
                    +
                  • double tee or plank components : IfcBeam
                  • +
                  • topping : IfcBuildingElementPart
                  • +
                  • others : IfcBuildingElementPart
                  • +
                  +
                • +
                +

                Geometry Use Definitions:

                +

                The geometric representation of IfcSlabElementedCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

                +

                Local Placement

                +

                The use of local placement is defined at the supertype +IfcSlab. The local placement of the +IfcSlabElementedCase defines the parent coordinate systems +for the parts within the decomposition. All parts shall be +positioned relative to the IfcSlabElementedCase.

                +

                Geometric Representation

                +

                The standard geometric representation of +IfcSlabElementedCase is defined using the following +multiple shape representations for its definition:

                +
                  +
                • Surface: A three-dimensional surface being a subtype +of IfcBoundedSurface defining the reference surface for +the elemented slab. It maybe used as a simplified representation +directly at the elemented slab.
                • +
                +
                NOTEÿ It is invalid to exhange a 'Body' shape +representation of an IfcSlabElementedCase. The body +geometry is defined by the parts within the +decomposition.
                +

                Surface Representation

                +

                The surfacic geometric representation of +IfcSlabElementedCase is defined using the 'Surface' +representation.

                +
                  +
                • RepresentationIdentifier : 'Surface'
                • +
                • RepresentationType : 'Surface3D'
                • +
                +
                NOTE The 'Surface' can be used to define a +surfacic model of the building (e.g. for analytical purposes, or +for reduced Level of Detail representation). It should suppress +the geometric details of the parts in the +decomposition.
                +
                " +1335;IfcRamp;" +

                Definition from ISO 6707-1:1989: Inclined way or floor +joining two surfaces at different levels.

                +

                A ramp is a vertical passageway which +provides a human circulation link between one floor level and +another floor level at a different elevation. It may include a +landing as an intermediate floor slab. A ramp normally does not +include steps (stepped ramps are out of scope for this IFC +Release).

                +

                The ramp is a container entity that aggregates all components +of the ramp, it represents. The aggregation is handled via the +IfcRelAggregates relationship, relating an IfcRamp +with the related flights (IfcRampFlight) and landings +(IfcSlab with type 'Landing'). Railings belonging to the +ramp may be included into the aggregation as +IfcRailing.

                + +
                HISTORY New Entity in IFC Release 2.0.
                +
                IFC2x4 CHANGE Attribute ShapeType renamed to PredefinedType
                + +

                Type Use Definition

                +

                IfcRamp defines the occuurence of any ramp, common +information about ramp types (or styles) is handled by +IfcRampType. The IfcRampType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material, common set of properties and common shape +representations (using IfcRepresentationMap). The +IfcRampType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +
                NOTE Since the IfcRamp might be +represented as an aggregate of parts, e.g. represented by +IfcRampFlight, or IfcSlab, these individual parts +may have type information attached (represented e.g. by +IfcRampFlightType, or +IfcSlabType).
                +

                Material Use Definition

                +

                The material of the IfcRamp is defined by the +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

                +

                Material information can also be given at the +IfcRampType, defining the common attribute data for all +occurrences of the same type.ÿIt is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcRampType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterial. If both are given, then the material directly +assigned to IfcRamp overrides the material assigned to +IfcRampType.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcRamp are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcRamp are part +of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcRamp are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.MethodOfMeasurement = 'BaseQuantities'. +Other quantities can be defined being subjected to local standard +of measurement with another string value assigned to Name +and a value provided for MethodOfMeasurement. Quantities +shall never be assigned to the IfcRampType.

                +

                The individual quantities shall only be given at +IfcRamp, it is not decomposed into the individual parts, +IfcRampFlight and IfcSlab.

                + +

                Geometry Use Definitions:

                +

                The geometric representation of IfcRamp is given by the +IfcProductDefinitionShape, allowing multiple geometric +representations. Independent geometric representations should +only be used when the IfcRamp is not defined as an +aggregate. If defined as an aggregate, the geometric +representation is the sum of the representation of the components +within the aggregate.

                +

                Local placement

                +

                The local placement for IfcRamp is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                If the LocalPlacement is given for the IfcRamp, +then all components, which are aggregated to the ramp should use +this placement as their relative placement.

                +

                Geometric representations

                +

                Geometric representation by own shape +representation

                +

                If the IfcRamp has no components defined (empty set of +SELF\IfcProduct.IsDecomposedBy) then the IfcRamp +may be represented by an own IfcShapeRepresentation with +the following values:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid', 'Clipping', +'SurfaceModel', or 'Brep'
                • +
                +

                The conventions to use these representations are provided at +IfcBuildingElement. No further constraints or provisions +on how to use the representation types are defined for +IfcRamp.

                +

                Geometric representation by aggregated elements

                +

                If the IfcRamp has components (referenced by +SELF\IfcProduct.IsDecomposedBy) then no independent +geometric representation shall be defined for the IfcRamp. +The IfcRamp is then geometrically represented by the +geometric representation of its components. The components are +accessed via +SELF\IfcProduct.IsDecomposedBy[1].RelatedObjects.

                + +

                Figure 111 illustrates IfcRamp defining the local placement for all components.

                + + + + +

                Figure 111 — Ramp placement

                + +
                " +1349;IfcStair;" +

                Definition from ISO 6707-1:1989: Construction comprising +a succession of horizontal stages (steps or landings) that make it +possible to pass on foot to other levels.

                +

                A stair is a vertical passageway allowing +occupants to walk (step) from one floor level to another floor +level at a different elevation. It may include a landing as an +intermediate floor slab. The stair should either be +represented:

                +
                  +
                • as a stair assembly entity that aggregates all components +(stair flight, landing, etc. with own representations), or
                • +
                • as a single stair entity without decomposition including all +representation directly at the stair entity.
                • +
                +

                In case of a stair container, the aggregation is handled via the +IfcRelAggregates relationship, relating an IfcStair +with the related IfcStairFlight's and landings (represented +by IfcSlab with IfcSlab.PredefinedType = 'LANDING'). +IfcRailing's belonging to the stair may be included into the +aggregation as well.

                + +
                HISTORY New Entity in IFC Release 2.0.
                +
                IFC2x4 CHANGE Attribute ShapeType renamed to PredefinedType.
                + +

                Type Use Definition

                +

                IfcStair defines the occurrence of any stair, common +information about stair types (or styles) is handled by +IfcStairType. The IfcStairType (if present) may +establish the common type name, usage (or predefined) type, common +material, common set of properties and common shape representations +(using IfcRepresentationMap). The IfcStairType is +attached using the IfcRelDefinedByType.RelatingType +objectified relationship and is accessible by the inverse +IsDefinedBy attribute.

                +
                NOTE Since the IfcStair might be +represented as an aggregate of parts, e.g. represented by +IfcStairFlight, or IfcSlab, these individual parts +may have type information attached (represented e.g. by +IfcStairFlightType, or +IfcSlabType).
                +

                Material Use Definition

                +

                The material of the IfcStair is defined by the +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

                +

                Material information can also be given at the +IfcStairType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the inverse +IsDefinedBy relationship pointing to +IfcStair.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterial. If both are given, then the material directly +assigned to IfcStair overrides the material assigned to +IfcStairType.

                + +

                Property Set Use Definition:

                +

                The property sets relating to the IfcStair are defined by +the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcStair are part of this +IFC release:

                + + +

                Figure 127 shows the use of property sets Pset_StairCommon and +Pset_StairFlightCommon for the various stair properties.

                + + + + +

                Figure 127 — Stair properties

                + +

                Geometry Use Definitions:

                +

                The geometric representation of IfcStair is given by the +IfcProductDefinitionShape, allowing multiple geometric +representation. Independent geometric representations should only +be used when the IfcStair is not defined as an aggregate. If +defined as an aggregate, the geometric representation is the sum of +the representation of the components within the aggregate.

                +

                Local placement

                +

                The local placement for IfcStair is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                If the LocalPlacement is given for the IfcStair, +then all components, which are aggregated to the stair should use +this placement as their relative placement.

                +

                Geometric Representation

                +

                Currently, the 'Axis', 'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +
                  +
                • Axis: A two-dimensional open curve +IfcBoundedCurve defining the walking line for the +stair.
                • +
                • FootPrint: A geometric curve set defining the footing +print, including the boundary of the stair.
                • +
                • Body: A solid representation defining the 3D shape of +the stair.
                • +
                +

                Axis Representation

                +

                The walking line is represented by a two-dimensional open curve +as the axis. The curve is directed into the upward direction +(direction has to be interpreted as specified at the subtypes of +IfcCurve). The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                +
                +

                NOTE  The 'Axis' representation of IfcStair +may be provided even if the IfcStair has components with own +shape representations.

                +
                +

                FootPrint Representation

                +

                The stair foot print, including the stair boundary is +represented by a two-dimensional geometric curve set. The following +attribute values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'FootPrint'
                • +
                • RepresentationType : 'GeometricCurveSet'
                • +
                +
                +

                NOTE  The 'Footprint' representation of +IfcStair may be provided even if the IfcStair has +components with own shape representations.

                +
                +

                Body Representation

                +

                The body representation of IfcStair can be represented +using the representation types 'SweptSolid', 'SurfaceModel', +'Brep', and 'MappedRepresentation'. The general usage of +representation is are explained at IfcBuildingElement. No +further constraints or provisions on how to use the representation +types are defined for IfcStairFlight.

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid', 'SurfaceModel', +'Brep', 'MappedRepresentation'
                • +
                +

                The 'Body' representation shall only be provided if the +IfcStair has no components defined (empty set of +SELF\IfcObject.IsDecomposedBy) or if the components defined +no not carry an own 'Body' representation.

                +

                Geometric representation by aggregated elements

                +

                If the IfcStair has components (referenced by +SELF\IfcObject.IsDecomposedBy) with own 'Body' +representation, then no 'Body' representation shall defined for the +IfcStair. The IfcStair shape is then represented by +the geometric representation of its components. The components are +accessed via +SELF\IfcObject.IsDecomposedBy[1].RelatedObjects.

                + +

                Figure 128 illustrates stair placement, where the IfcStair defines the local placement for all components and the common 'Axis' representation, and each component has its own 'Body' representation.

                + + + + +

                Figure 128 — Stair placement

                + +
                " +1371;IfcRoof;" + +

                Definition from ISO 6707-1:1989: Construction enclosing the building from above.

                +

                The IfcRoof is a description of the total roof. It acts as a container entity, that aggregates all components of the roof, it represents. The aggregation is handled via the IfcRelAggregates relationship, relating an IfcRoof with the related roof elements, like slabs (represented by IfcSlab), rafters and purlins (represented by IfcBeam), or other included roofs, such as dormers (represented by IfcRoof).

                + +
                HISTORY New Entity in IFC Release 2.0.
                +
                IFC2x4 CHANGE Attribute ShapeType renamed to PredefinedType.
                + +

                Property Set Use Definition:

                +

                The property sets relating to the IfcRoof are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcRoof are part +of this IFC release:

                + +

                The quantities relating to the IfcRoof are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.MethodOfMeasurement = 'BaseQuantities'. +Other quantities can be defined being subjected to local standard +of measurement with another string value assigned to Name +and a value provided for MethodOfMeasurement. Quantities +shall never be assigned to the IfcRoofType.

                +

                The individual quantities shall only be given at +IfcRoof, it is not decomposed into the individual parts, +e.g. IfcSlab as roof slabs.

                + +

                Containment Use Definition

                +

                The IfcRoof, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within an element assembly.

                +
                  +
                • The IfcRoof is placed within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcRoof may be aggregated into an element assembly +using the objectified relationship IfcRelAggregates, +referring to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcRoof, the overall roof, as a special focus subtype. In +this case it should not be additionally contained in the project +spatial hierarchy, i.e. +SELF\IfcElement.ContainedInStructure should be NIL.
                • +
                +
                NOTEÿ A roof contained in another roof could +be the representation of a dormer.
                +

                The IfcRoof may be an aggregate i.e. being composed by +other elements and acting as an assembly using the objectified +relationship IfcRelAggregates, referring to it by its +inverse attribute SELF\IfcObjectDefinition.IsDecomposedBy. +Components of a roof are described by instances of subtypes of +IfcBuildingElement (e.g. IfcSlab, IfcBeam, +IfcColumn, IfcBuildingElementPart) that are +aggregated to form a complex roof. In this case, the contained +elements should not be additionally contained in the project +spatial hierarchy, i.e. the inverse attribute +SELF\IfcElement.ContainedInStructure of the aggregated +elements should be NIL.

                + +

                Figure 118 illustrates roof containment, where only the IfcRoof as the aggregate +is included in the spatial structure.

                + + + + +

                Figure 118 — Roof containment

                + +

                Geometry Use Definitions:

                +

                The geometric representation of IfcRoof is given by the +IfcProductDefinitionShape, allowing multiple geometric +representations. Independent geometric representations should +only be used when the IfcRoof is not defined as an +aggregate. If defined as an aggregate, the geometric +representation is the sum of the representation of the components +within the aggregate.

                +
                NOTEÿ View definitions and implementer +agreements may restrict the IfcRoof to not have an +independent geometry, but to always require aggregated elements +to represent the shape of the roof.
                +NOTE If the IfcRoof has aggregated elements to +represent the shape of the roof, then only those elements shall +have openings, not the IfcRoof +itself.
                +

                Local Position

                +

                The local placement for IfcRoof is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level..
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                If the LocalPlacement is given for the IfcRoof, +then all components, which are aggregated to the roof should use +this placement as their relative placement.

                +

                Geometric Representation

                +

                The IfcRoof may have an independent geometric representation +or may be an aggregate with elements holding the geometric +representation of the roof.

                +

                Geometric representation by own shape +representation

                +

                If the IfcRoof has no components defined (empty set of +SELF\IfcObject.IsDecomposedBy) then the IfcRoof may +be represented by an independent IfcShapeRepresentation. +The following attribute values for the IfcShapeRepresentation +holding this geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid', 'Clipping', +'SurfaceModel', or 'Brep'
                • +
                +

                Geometric representation by aggregated elements

                +

                If the IfcRoof has components (referenced by +SELF\IfcObject.IsDecomposedBy) then no independent +geometric representation shall defined for the IfcRoof. +The IfcRoof is then geometrically represented by the +geometric representation of its components. The components are +accessed via +SELF\IfcObject.IsDecomposedBy[1].RelatedObjects. The +geometric representations that are supported for the aggregated +elements are defined with each element. See geometric use +definition for IfcSlab, IfcBeam, IfcColumn, +IfcBuildingElementPart and other subtypes of +IfcBuildingElement.

                + +

                Figure 119 illustrates roof placement, with an IfcRoof defining the local placement for all aggregated elements.

                + + + + +

                Figure 119 — Roof placement

                + +
                " +1392;IfcStairFlight;" +

                A stair flight is an assembly of +building components in a single ""run"" of stair steps (not +interrupted by a landing). The stair steps and any stringers are +included in the stair flight. A winder is also regarded a part of +a stair flight.

                +

                An IfcStairFlight is normally aggregated by an +IfcStair through the IfcRelAggregates relationship, +the stair flight is then included in the set of +IfcRelAggregates.RelatedObjects. An IfcStairFlight +normally connects the floor slab of zero to two different storeys +(or partial storeys, or landings) within a building. The +connection relationship between the IfcStairFlight and the +IfcSlab is expressed using the +IfcRelConnectsElements relationship.

                + +
                HISTORY: New Entity in IFC Release 2.0.
                + +

                Type Use Definition

                +

                IfcStairFlight defines the occurrence of any stair +flight, common information about stair flight types (or styles) +is handled by IfcStairFlightType. The +IfcStairFlightType (if present) may establish the +commonÿtype name, usage (or predefined) type, common material +layer set, common set of properties and common shape +representations (using IfcRepresentationMap). The +IfcStairFlightType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +

                Material Use Definition

                +

                The material of the IfcStairFlight is defined by the +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcStairFlight are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcStairFlight +are part of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcStairFlight are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quantities shall +never be assigned to the IfcStairFlightType.

                + +

                Containment Use Definition

                +

                The IfcStairFlight, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first relationship is the +hierachical spatial containment, the second relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcStairFlight is placed within the project +spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcStairFlight may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcStair as a special focus subtype. In this case it +shall not be additionally contained in the project spatial +hierarchy, i.e.ÿSELF\IfcElement.ContainedInStructure +shall be NIL.
                • +
                +

                Geometry Use Definition

                +

                The geometric representation of IfcStairFlight is given +by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

                +

                Local placement

                +

                The local placement for IfcStairFlight is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                • +
                • If the IfcStairFlight, however, is used by an +IfcStair, and this container class defines its own local +placement, then the PlacementRelTo relationship of +IfcLocalPlacement shall point to the local placement of +the IfcStair.
                • +
                +

                Geometric Representations

                +

                Currently, the 'Axis', 'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +
                  +
                • Axis: A two-dimensional open curve +IfcBoundedCurve defining the walking line for the stair +flight.
                • +
                • FootPrint: A geometric curve set defining the footing +print, including the boundary of the stair flight.
                • +
                • Body: A solid representation defining the 3D shape of +the stair flight
                • +
                +

                Axis Representation

                +

                The walking line is represented by a two-dimensional open +curve as the axis. The curve is directed into the upward +direction (direction has to be interpreted as specified at the +subtypes of IfcCurve). The following attribute values for +the IfcShapeRepresentation holding this geometric +representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                + +

                Figure 129 illustrates the axis representation which has the following constraints:

                +
                  +
                • In case of straight flights the curve shall be a single item of type IfcPolyline.
                • +
                • In case of winding flights the curve shall be a single item of type IfcCompositeCurve.
                • +
                • In case of a curved flight or a spiral flight the curve shall be a single item of type IfcTrimmedCurve.
                • +
                + + + + +

                Figure 129 — Stair flight axis

                + +

                FootPrint Representation

                +

                The flight foot print, including the flight boundary is +represented by a two-dimensional geometric curve set. The +following attribute values for the IfcShapeRepresentation +holding this geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'FootPrint'
                • +
                • RepresentationType : 'GeometricCurveSet'
                • +
                + +

                Figure 130 illustrates the footprint representation which has the following constraints:

                +
                  +
                • In case of straight flights the curve set shall consists of a single item of type IfcPolyline.
                • +
                • In case of winding flights or curved flights the curve set shall consists of a single item of type IfcCompositeCurve.
                • +
                • In case of a spiral flight the curve set shall consists of a single item of type IfcConic or IfcPolyline.
                • +
                + + + + +

                Figure 130 — Stair flight footprint

                + +

                Body Representation

                +

                The body representation of IfcStairFlight can be represented using the representation types 'SweptSolid', 'SurfaceModel', 'Brep', and 'MappedRepresentation'. The general usage of representation is are explained at +IfcBuildingElement. No further constraints or provisions on how to use the representation types are defined for +IfcStairFlight.

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid', 'SurfaceModel', 'Brep', 'MappedRepresentation'
                • +
                +

                Figure 131 illustrates the body representation.

                + + + +

                Figure 131 — Stair flight body

                +
                " +1408;IfcRampFlight;" +

                A ramp is an inclined slab segment, normally +providing a human circulation link between two landings, floors or +slabs at different elevations.

                +

                An IfcRampFlight is normally aggregated by an +IfcRamp through the IfcRelAggregates relationship, +the ramp flight is then included in the set of +IfcRelAggregates.RelatedObjects. An IfcRampFlight +normally connects the floor slab of zero to two different storeys +(or partial storeys or landings) within a building. The connection +relationship between the IfcRampFlight and the +IfcSlab is expressed using the IfcRelConnectsElements +relationship.

                +
                HISTORY New Entity in IFC Release 2.0.
                + +

                Type Use Definition

                +

                IfcRampFlight defines the occurrence of any ramp flight, +common information about ramp flight types (or styles) is handled +by IfcRampFlightType. The IfcRampFlightType (if +present) may establish the common type name, usage (or +predefined) type, common material layer set, common set of +properties and common shape representations (using +IfcRepresentationMap). The IfcRampFlightType is +attached using the IfcRelDefinedByType.RelatingType +objectified relationship and is accessible by the inverse +IsDefinedBy attribute.

                +

                Material Use Definition

                +

                The material of the IfcRampFlight is defined by the +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcRampFlight are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcRampFlight are part of +this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcRampFlight are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following base +quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other quantities +can be defined being subjected to local standard of measurement +with another string value assigned to Name and a value +provided for MethodOfMeasurement. Quantities shall never be +assigned to the IfcRampFlightType.

                + +

                Containment Use Definition

                +

                The IfcRampFlight, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first relationship is the +hierachical spatial containment, the second relationship is the +aggregation within an element assembly.

                +
                  +
                • The IfcRampFlight is placed within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid +spatial containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcRampFlight may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with IfcRamp +as a special focus subtype. In this case it should not be +additionally contained in the project spatial hierarchy, +i.e. SELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                +

                Geometry Use Definition

                +

                The geometric representation of IfcRampFlight is given by +the IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local placement

                +

                The local placement for IfcRampFlight is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement that is +used in the ContainedInStructure inverse attribute or to a +referenced spatial structure element at a higher level.
                • +
                • If the IfcRampFlight, however, is used by an +IfcRamp, and this container class defines its own local +placement, then the PlacementRelTo relationship of +IfcLocalPlacement shall point to the local placement of the +IfcRamp.
                • +
                +

                Geometric Representations

                +

                Currently, the 'Axis', 'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

                +
                  +
                • Axis: A two-dimensional open curve +IfcBoundedCurve defining the walking line for the ramp +flight.
                • +
                • FootPrint: A geometric curve set defining the footing +print, including the boundary of the ramp flight.
                • +
                • Body: A solid representation defining the 3D shape of +the ramp flight
                • +
                +

                Axis Representation

                +

                The walking line is represented by a two-dimensional open curve +as the axis. The curve is directed into the upward direction +(direction has to be interpreted as specified at the subtypes of +IfcCurve). The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                + +

                Figure 112 illustrates the axis representation which has the following constraints:

                +
                  +
                • In case of straight flights the curve shall be a single item of type IfcPolyline.
                • +
                • In case of winding flights the curve shall be a single item of type IfcCompositeCurve.
                • +
                • In case of a curved flight or a spiral flight the curve shall be a single item of type IfcTrimmedCurve.
                • +
                + + + + +

                Figure 112 — Ramp flight axis

                + +

                FootPrint Representation

                +

                The flight foot print, including the flight boundary is represented by a two-dimensional geometric curve set. The following attribute values for the IfcShapeRepresentation holding this geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'FootPrint'
                • +
                • RepresentationType : 'GeometricCurveSet'
                • +
                + +

                Figure 113 illustrates the footprint representation which has the following constraints:

                +
                  +
                • In case of straight flights the curve set shall consist of a single item of type IfcPolyline.
                • +
                • In case of winding flights or curved flights the curve set shall consists of a single item of type +IfcCompositeCurve.
                • +
                • In case of a spiral flight the curve set shall consists of a single item of type IfcConic or +IfcPolyline.
                • +
                + + + + +

                Figure 113 — Ramp flight footprint

                + +

                Body Representation

                +

                The body representation of IfcRampFlight can be +represented using the representation types 'SweptSolid', +'SurfaceModel', 'Brep', and 'MappedRepresentation'. The general +usage of representation is are explained at +IfcBuildingElement. For further constraints on the +'SweptSolid' the representation types see below..

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid', 'SurfaceModel', +'Brep', 'MappedRepresentation'
                • +
                +

                SweptSolid Representation Type

                +

                The 'SweptSolid' representation type is a valid body +representation of IfcRampFlight is defined using the swept +area geometry. The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SweptSolid'
                • +
                +

                The following additional constraints apply to the 'SweptSolid' +representation type:

                +
                  +
                • Solid: IfcExtrudedAreaSolid is required,
                • +
                • Profile: IfcRectangleProfileDef and +IfcArbitraryClosedProfileDef shall be supported.
                • +
                • Extrusion: The profile shall be extruded in any +direction relative to the XY plane of the position coordinate +system of the IfcExtrudedAreaSolid. Therefore +non-perpendicular sweep operation has to be supported. It might be +further constrained to be in the direction of the global z-axis in +implementers agreements.
                • +
                + +

                Figure 114 illustrates the body representation.

                + + + +

                Figure 114 — Ramp flight body

                + +
                " +1417;IfcCurtainWall;" +

                Definition from ISO 6707-1:1989: Non load bearing wall +positioned on the outside of a building and enclosing it.

                +

                A curtain wall is an exterior wall of a building which is +an assembly of components, hung from the edge of the floor/roof +structure rather than bearing on a floor. Curtain wall is +represented as a building element assembly and implemented as a +subtype of IfcBuildingElement that uses an +IfcRelAggregates relationship.

                +
                HISTORY New Entity in IFC Release 2.0
                + +

                Type Use Definition

                +

                IfcCurtainWall defines the occuurence of any curtain +wall, common information about curtain wall types (or styles) is +handled by IfcCurtainWallType. The +IfcCurtainWallType (if present) may establish the +commonÿtype name, usage (or predefined) type, common material +information, common set of properties and common shape +representations (using IfcRepresentationMap). The +IfcCurtainWallType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +

                If no IfcCurtainWallType is attachedÿ(i.e. if only +occurrence information is given) the predefined type may be given +by using the ObjectType attribute.

                +
                NOTE Since the IfcCurtainWall might be +represented as an aggregate of parts, e.g. represented by +IfcMember, or IfcPlate, these individual parts may +have type information attached (represented e.g. by +IfcMemberType, or +IfcPlateType).
                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcCurtainWall are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcCurtainWall +are part of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcCurtainWall are +defined by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quantities shall +never be assigned to the IfcCurtainWallType.

                + +

                Geometry Use Definitions:

                +

                The geometric representation of IfcCurtainWall is given +by the IfcProductDefinitionShape, allowing multiple +geometric representations. Independent geometric representations, +as described below, should only be used when the +IfcCurtainWall is not defined as an aggregate. If defined +as an aggregate, the geometric representation is the sum of the +representations of the components within the aggregate.

                +

                Local placement

                +

                The local placement for IfcCurtainWall is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the same +IfcSpatialStructureElement that is used in the +ContainedInStructure inverse attribute or to a referenced +spatial structure element at a higher level.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                If the IfcCurtainWall establishes an aggregate, then +all contained elements (defined by the IsDecomposedBy +inverse attribute) shall be placed relative to the +IfcCurtainWall.ObjectPlacement.

                +

                Geometric Representation

                +

                The geometric representation of IfcCurtainWall is +defined using the following multiple shape representations for +its definition:

                +
                  +
                • Axis: A two-dimensional open curve (for restrictions see +below) defining the axis for the curtain wall. +
                    +
                  • This is an optional representation for curtain walls.
                  • +
                  +
                • +
                • Body: A surface model or boundary representation model +representation defining the 3D shape of the curtain wall. +
                    +
                  • If the IfcCurtainWall has components (referenced by +SELF\IfcObject.IsDecomposedBy) then no independent shape +representation with RepresentationType = 'Body' shall be +defined. The body of IfcCurtainWall is then geometrically +represented by the shape representation of its components. The +components are accessed via +SELF\IfcObject.IsDecomposedBy[1].RelatedObjects.
                  • +
                  +
                    +
                  • If the IfcCurtainWall has no components defined (empty +set of SELF\IfcObject.IsDecomposedBy) then the +IfcCurtainWall may be represented by an shape +representation with the RepresentationIdentifier = +'Body'.
                  • +
                  +
                • +
                +

                Axis Representation

                +

                The axis geometric representation of IfcCurtainWall is +defined using the 'Axis' representation. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D'
                • +
                +

                The following additional constraints apply to the 'Axis' +representation:

                +
                  +
                • Axis : IfcPolyline having two Points, or +IfcTrimmedCurve with BasisCurve of Type +IfcLine or IfcCircle.
                • +
                +

                Body Representation

                +

                The body shape representation of IfcCurtainWall is +defined using the 'Body' representation. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SurfaceModel', 'Brep' and +'MappedRepresentation'
                • +
                +

                An own 'Body' representation shall only be included if no +components of the curtain wall are defined.

                +
                " +1424;IfcRailing;" +

                Definition of IAI: The railing is a frame assembly +adjacent to human circulation spaces and at some space boundaries +where it is used in lieu of walls or to compliment walls. +Designed to aid humans, either as an optional physical support, +or to prevent injury by falling.

                +
                HISTORY New Entity in +IFC Release 2.0
                +

                Type Use Definition

                +

                IfcRailing defines the occuurence of any railing, +common information about railing types (or styles) is handled by +IfcRailingType. The IfcRailingType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common material, common set of properties and common shape +representations (using IfcRepresentationMap). The +IfcRailingType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

                +

                Material Use Definition

                +

                The material of the IfcRailing is defined by the +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

                +

                Material information can also be given at the +IfcRailingType, defining the common attribute data for all +occurrences of the same type.ÿIt is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcRailingType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterial. If both are given, then the material directly +assigned to IfcRailing overrides the material assigned to +IfcRailingType.

                +

                Property Set Use Definition

                +

                The property sets relating to the IfcRailing are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcRailing are +part of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcRailing are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.MethodOfMeasurement = 'BaseQuantities'. +Other quantities can be defined being subjected to local standard +of measurement with another string value assigned to +MethodOfMeasurement.

                + +

                Containment Use Definition

                +

                The IfcRailing, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcRailing is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcRailing may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcStair, or IfcRamp as a special focus subtypes. +In this case it should not be additionally contained in the +project spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
                • +
                +

                Geometry Use Definition

                +

                The geometric representation of IfcRailing is given by +the IfcProductDefinitionShape, allowing multiple geometric +representations. Included are:

                +

                Local placement

                +

                The local placement for IfcRailing is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

                +
                  +
                • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the same +IfcSpatialStructureElement that is used in the +ContainedInStructure inverse attribute or to a referenced +spatial structure element at a higher level
                • +
                • If the IfcRailing, however, is used by an +IfcStair or IfcRamp, and this container class +defines its own local placement, then the PlacementRelTo +relationship of IfcLocalPlacement shall point to the local +placement of IfcStair or IfcRamp.
                • +
                • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
                • +
                +

                Geometric Representation

                +

                Currently, the 'Axis', 'Body', +and 'Box' representations are supported. The 'Box' representation +includes the representation type 'BoundingBox' and is explained +at IfcBuildingElement.

                +

                Axis Representation

                +

                The axis geometric representation of IfcRailing is +defined using the 'Axis' representation. The following attribute +values for the IfcShapeRepresentation holding this +geometric representation shall be used:

                +
                  +
                • RepresentationIdentifier : 'Axis'
                • +
                • RepresentationType : 'Curve2D', 'Curve3D'
                • +
                +

                Body Representation

                +

                Currently the use of 'SurfaceModel', 'Brep' and +'MappedRepresentation' representations of IfcRailing are +supported. The conventions to use these representations are given +at the level of the supertype, IfcBuildingElement. No +further constraints or provisions on how to use the +representation types are defined for IfcRailing.

                +
                  +
                • RepresentationIdentifier : 'Body'
                • +
                • RepresentationType : 'SurfaceModel', 'Brep', +'MappedRepresentation'
                • +
                + +
                " +1434;IfcDoor;" +

                Definition from ISO 6707-1:1989: Construction for +closing an opening, intended primarily for access with hinged, +pivoted or sliding operation.

                +

                The door is a building element +that is predominately used to provide controlled access for +people and goods. It includes constructions with hinged, pivoted, +sliding, and additionally revolving and folding operations. A +door consists of a lining and one or several panels.

                +

                The IfcDoor defines a particular occurrence of a door +inserted in the spatial context of a project. A door can:

                +
                  +
                • be inserted as a filler in an opening using the +IfcRelFillsElement relationship, then the IfcDoor +has an inverse attribute FillsVoids provided, +
                    +
                  • NOTEÿ View definitions or +implementer agreements may restrict the relationship to only +include one window (or door) into one opening.
                    +
                  • +
                  +
                • +
                • be part of an element assembly, in general an +IfcCurtainWall, using the IfcRelAggregates +relationship, then the inverse attribute Decomposes is +provided.
                • +
                • or be a ""free standing"" door, then the IfcDoor has no +inverse attributes FillsVoids or Decomposes +provided.
                • +
                +

                The IFC specification provides two entities for door +occurrences:

                +
                  +
                • IfcDoorStandardCase used for all occurrences of doors, +that have a 'Profile' shape representation defined to which a set +of shape parameters for lining and framing properties apply. +Additionally it requires the provision of an IfcDoorType +that references one IfcDoorLiningProperties and on to many +IfcDoorPanelProperties. +
                    +
                  • NOTEÿ see +IfcDoorStandardCase for all specific constraints imposed +by this subtype.
                  • +
                  +
                • +
                • IfcDoor used for all other occurrences of doors, +particularly for doors having only 'Brep', or 'SurfaceModel' +geometry without applying shape parameters.
                • +
                +

                The actual parameter of the door and/or its shape are defined +by the IfcDoor as the occurrence definition (or project +instance), or by the IfcDoorType as the specific definition (or +project type). The following parameters are given:

                +
                  +
                • at the IfcDoor or IfcDoorStandardCase for +occurrence specific parameters. The IfcDoor +specifies:
                • +
                • +
                    +
                  • the door width and height
                  • +
                  • the door opening direction (by the y-axis of the +ObjectPlacement)
                    +
                  • +
                  +
                • +
                • at the IfcDoorType, to +which the IfcDoor is related by the inverse relationship +IsDefinedBy pointing to IfcRelDefinesByType, for +type parameters common to all occurrences of the same type.
                • +
                • +
                    +
                  • the operation type (single swing, double swing, revolving, +etc.)
                  • +
                  • the door hinge side (by using two different styles for right +and left opening doors)
                  • +
                  • the construction material type
                  • +
                  • the particular attributes for the lining by the +IfcDoorLiningProperties
                  • +
                  • the particular attributes for the panels by theÿ +IfcDoorPanelProperties
                  • +
                  +
                • +
                +
                HISTORY New entity in IFC Release 1.0.
                +
                IFC2x4 CHANGE The attributes PredefinedType and OperationType are added, the applicable type object has been changed to IfcDoorType.
                + +

                Material Use Definition

                +

                The material of the IfcDoor is defined by the +IfcMaterialConstituentSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

                +

                The following keywords for +IfcMaterialConstituentSet.MaterialConstituents[n].Name +shall be used:

                +
                  +
                • 'Lining' - to indicate that the material constituent applies +to to the door lining
                • +
                • 'Framing' - to indicate that the material constituent applies +to to the door panel(s), if not provided, the 'Lining' material +information applied to panel(s) as well
                • +
                • 'Glazing' - to indicate that the material constituent applies +to to the glazing part
                • +
                +

                If the fall back single IfcMaterial is referenced, it +applies to the lining and framing of the door.

                +

                Property Set Use Definition:

                +

                The property sets relating to the IfcDoor are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcDoor are part +of this IFC release:

                + +

                Quantity Use Definition

                +

                The quantities relating to the IfcDoor are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to +MethodOfMeasurement. Quanties shall be never assigned to +the IfcDoorType.

                + + +

                Containment Use Definition

                +

                The IfcDoor, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships as shown in Figure 96. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

                +
                  +
                • The IfcDoor is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
                • +
                • The IfcDoor may be aggregated into an element assembly +using the objectified relationship IfcRelAggregates, +refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Doors may be part of +an IfcCurtainWall as a special focus subtype. In this case +it should not be additionally contained in the project spatial +hierarchy, i.e.ÿSELF\IfcElement.ContainedInStructure +should be NIL.
                • +
                + +NOTE The containment shall be defined independently of the +filling relationship, that is, even if the IfcDoor is a +filling of an opening established by IfcRelFillsElement, +it is also contained in the spatial structure by an +IfcRelContainedInSpatialStructure.
+ + + + +
+""Containment""

Figure 96 — Door containment

+ +

Geometry Use Definitions:

+

The geometric representation of IfcDoor is given by the +IfcProductDefinitionShape, allowing multiple geometric +representations. The IfcDoor, in case of an occurrance +object, gets its parameter and shape from the IfcDoorType. +If an IfcRepresentationMap (a block definition) is defined +for the IfcDoorType, then the IfcDoor inserts it +through the IfcMappedItem.

+

Local Placement

+

The local placement for IfcDoor is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

+
    +
  1. The PlacementRelTo relationship of +IfcLocalPlacement shall point to the local placement of +the same element (if given), in which the IfcDoor is used +as a filling (normally an IfcOpeningElement), as provided +by the IfcRelFillsElement relationship.
  2. +
  3. If the IfcDoor is not inserted into an +IfcOpeningElement, then the PlacementRelTo +relationship of IfcLocalPlacement shall point (if given) +to the local placement of the same +IfcSpatialStructureElement that is used in the +ContainedInStructure inverse attribute or to a referenced +spatial structure element at a higher level.
  4. +
  5. If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
  6. +
+

Geometric Representation

+

Theÿgeometric representation of IfcDoor is defined +using the following (potentiallyÿmultiple) +IfcShapeRepresentation's for its +IfcProductDefinitionShape:

+
    +
  • Profile: Aÿ'Curve3D' +consisting of a single losed curve defining the outer boundary of +the door (lining). The door parametric representation uses this +profile in order to apply the door lining and panel parameter. If +not provided, the profile of the IfcOpeningElement is +taken.
  • +
  • FootPrint: A 'GeometricCurveSet', or 'Annotation2D' +representation defining the 2D shape of the door
  • +
  • Body: A 'SweptSolid', 'SurfaceModel', or 'Brep' +representation defining the 3D shape of the door.
  • +
+

In addition the parametric representation of a (limited) door +shape is available by applying the parameters from +IfcDoorType referencing IfcDoorLiningProperties and +IfcDoorPanelProperties. The purpose of the parameter is +described at those entities and below (door opening operation by +door type).

+

Profile -ÿ'Curve3D' representation

+

The door profile is represented by a three-dimensional closed +curve within a particular shape representation. The profile is +used to apply the parameter of the parametric door +representation.ÿThe following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'Profile'
  • +
  • RepresentationType : 'Curve3D', only a single closed +curve shall be contained in the set of +IfcShapeRepresentation.Items.
  • +
+

A 'Profile' representation has to be provided if:

+
    +
  • a parametric representation shall be applied to the door +AND
  • +
  • +
      +
    • theÿdoor is 'free standing', or
    • +
    • the opening into which theÿdoor is inserted is not extruded +horizontally (i.e. where the opening profile does not match +theÿdoor profile)
    • +
    +
  • +
+

FootPrint -ÿ'GeometricCurveSet' or 'Annotation2D' +representation

+

The door foot print is represented by a set of +two-dimensionalÿcurves (or in case of 'Annotation2D' additional +hatching and text) within a particular shape representation. The +foot print is used for the planview representation of the +door.ÿThe following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'FootPrint'
  • +
  • RepresentationType : 'GeometricCurveSet', or +'Annotation2D'
  • +
+

Body - 'SweptSolid', 'SurfaceModel', or 'Brep' +representation

+

The door body is either represented parameterically (see +parametric representation) or by explicit 3D shape. The 3D shape +is given by using extrusion geometry, or surface models, or Brep +models within a particular shape representation. The body is used +for the model view representation of the door.ÿThe following +attribute values for the IfcShapeRepresentation holding +this geometric representation shall be used:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'SweptSolid', 'SurfaceModel', or +'Brep'
  • +
+

MappedRepresentation

+

The 'FootPrint' and 'Body' geometric representation of +IfcDoor can be shared among several identical doors using +the 'MappedRepresentation'. The following attribute values for +the IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'FootPrint', 'Body'
  • +
  • RepresentationType : 'MappedRepresentation'
  • +
+

The same constraints, as given for theÿ 'FootPrint', 'Body' +representation identifiers, shall apply to the +MappedRepresentation of the +IfcRepresentationMap.

+

Parameteric Representation using parameters at +IfcDoorType

+

The parameters that defines the shape of the IfcDoor, +are given at the IfcDoorType and the property sets, which +are included in the IfcDoorType. The IfcDoor only +defines the local placement which determines the opening +direction of the door. The overall size of +the IfcDoor to be used to apply the lining or panel +parameter provided by the IfcDoorType is determined by the +IfcShapeRepresentation with the RepresentationIdentifier = +'Profile'. Only in case of an IfcDoor inserted into an +IfcOpeningElement using the IfcRelFillsElement +relatioship, having a horizontal extrusion (along the y-axis of +the IfcDoor), the overall size is determined by the +extrusion profile of the IfcOpeningElement.

+
NOTE ÿThe OverallWidth and +OverallHeight parameters are for informational purpose +only.
+

The opening direction is determined by the local placement of +IfcDoor and the OperationType of the door +style as shown in Figure 97.

+
NOTE ÿThere are different definitions in +various countries on what a left opening or left hung or left +swing door is (same for right). Therefore the IFC definition may +derivate from the local standard and need to be mapped +appropriately.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Opening +directions +DefinitionsReference to other +standards

The door panel (for swinging doors) opens +always into the direction of the positive Y axis of the local +placement. The determination of whether the door opens to the +left or to the right is done at the level of the +IfcDoorType. Here it is a left side opening door given +byÿIfcDoorType.OperationType = +SingleSwingLeftrefered to as LEFT HAND (LH) in US *
+
+refered to as DIN-R (right hung) in Germany

If the door should open to the other +side, then the local placement has to be changed. It is still a +left side opening door, given by IfcDoorType.OperationType += SingleSwingLeftrefered to as RIGHT HAND REVERSE (RHR) in +US *
+
+refered to as DIN-R (right hung) in Germany
If the door panel (for swinging doors) +opens to the right, a separate door style needs to be used (here +IfcDoorTypee.OperationType = SingleSwingRight) and it +always opens into the direction of the positive Y axis of the +local placement.ÿrefered to as RIGHT HAND (RH) in US *
+
+refered to as DIN-L (left hung) in Germany

If the door panel (for swinging doors) +opens to the right, and into the opposite directions, the local +placement of the door need to change. The door style is given by +IfcDoorType.OperationType = SingleSwingRight.refered to as LEFT HAND REVERSE (LHR) in +US *
+
+refered to as DIN-L (left hung) in Germany
* it assumes that the +'inside/private/primary' space is above (top in the pictures) and +the 'outside/public/secondary' space is below (bottom in the +pictures).
+ +

Figure 97 — Door swing

+ + +
" +1441;IfcDoorStandardCase;" +

The standard door, +IfcDoorStandardCase, defines a door with certain constraints +for the provision of operation types, opening directions, frame and +lining parameters, and with certain constraints for the geometric +representation. The IfcDoorStandardCase handles all cases of +doors, that:

+
    +
  • are inserted into an opening, represented by +IfcOpeningElement, using the IfcRelFillsElement +relationship
  • +
  • have a local placement relative to this opening, and with the +y-axis of the placement pointing into the opening direction
  • +
  • have a profile geometry, represented by +IfcShapeRepresentation.RepresentationIdentifier=""Profile"" as +a closed curve to which the door parameter apply. The profile +represents a rectangle within the xz plane of the local +placement
  • +
  • have a reference to an IfcDoorType to define the opening +direction and the operation type (swinging, sliding, folding, etc.) +of the door. The attribute OperationType shall be provided +and not being UNDEFINED, and the attribute +ParameterTakesPrecedence shall be ""TRUE"".
  • +
  • have an IfcDoorLiningProperties and an +IfcDoorPanelProperties instances included in the set of +HasPropertySets at IfcDoorType
  • +
+
HISTORY New entity in IFC2x4.
+ +

Type Use Definition

+

IfcDoorStandardCase defines the occuurence of any door, +common information about door types (or styles) is handled by +IfcDoorType. The IfcDoorType (that has to be present) +establishes the common type name, usage (opening direction and +operation), common set of properties, including shape parameters, +like lining thickness panel width, etc. and maybe an additional +common shape representations (using IfcRepresentationMap). +The IfcDoorType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy attribute.

+

Property Set Use Definition:

+

The property sets relating to the IfcDoorStandardCase are +defined at the supertype IfcDoor.

+

Quantity Use Definition

+

The quantities relating to the IfcDoorStandardCase are +defined at the supertype IfcDoor.

+

Containment Use Definition

+

The containment use definitions relating to the +IfcDoorStandardCase are defined at the supertype +IfcDoor.

+

Geometry Use Definitions:

+

The geometric representation of IfcDoorStandardCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representations. Included are:

+

Local Placement

+

The use of local placement is defined at the supertype +IfcDoor.

+

Geometric Representations

+

The geometric representation of IfcDoorStandardCase is +defined using the following multiple shape representations for its +definition:

+
    +
  • Profile: a three-dimensional closed curve within a +particular shape representation. The profile is used to apply the +parameter of the parametric door representation. The profile around +the edges of the opening is used to apply the door lining and door +panel shape parameter.
  • +
  • MappedRepresentation: A SweptSolid, SurfaceModel, or +Brep Representation or a CSG additionally defining the 3D shape of +the standard door in addition to the parametric representation by +applying the IfcDoorLiningProperties and an the +IfcDoorPanelProperties to the Profile representation.
  • +
+

Profile representation

+

The door profile is represented by a three-dimensional closed +curve within a particular shape representation. The profile is used +to apply the parameter of the parametric door +representation. The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

+
    +
  • RepresentationIdentifier : 'Profile'
  • +
  • RepresentationType : 'Curve3D' or 'GeometricCurveSet', +in case of 'GeometricCurveSet' only a single closed curve shall be +contained in the set of IfcShapeRepresentation.Items.
  • +
+

The following additional constraints apply to the 'Profile' +representation type:

+
    +
  • Curve: being an IfcPolyline defining a +rectangle.
  • +
  • Position: The curve shall lie in the xz plane of the +object placement coordinate (the y coordinate values of the +IfcCartesianPoint's shall be 0.).
  • +
+ +

Figure 98 illustrates applying the door lining parameters to the door profile shape representation. The profile defines the outer boundary to which the door lining parameters relate as:

+
    +
  • IfcDoorLiningProperties.LiningDepth starting at distance defined by LiningOffset going into the positive y direction.
  • +
  • IfcDoorLiningProperties.LiningThickness offset into the inner side of the rectangle.
  • +
  • IfcDoorLiningProperties.LiningOffset distance along the positive y direction to where the LiningDepth applies.
  • +
  • IfcDoorLiningProperties.ThresholdThickness starting at the bottom edge of the rectangle into the inner side of the rectangle
  • +
  • IfcDoorLiningProperties.ThresholdDepth starting at distance defined by LiningOffset going into the positive y direction.
  • +
  • IfcDoorLiningProperties.TransomOffset starting at the bottom edge of the rectangle (along local x axis) into the inner side of the rectangle, distance provided as percentage of overall height. Distance to the centre line of the transom.
  • +
+ + + + +

Figure 98 — Door profile

+ +
" +1469;IfcWindow;" +

Definition form ISO 6707-1:1989: Construction for +closing a vertical or near vertical opening in a wall or pitched +roof that will admit light and may admit fresh air.

+

The window is a building element +that is predominately used to provide natural light and fresh +air. It includes vertical and horizontal opening (e.g. skylights +or light domes). It includes constructions with swinging, +pivoting, sliding, or revolving panels and fixed panels. A window +consists of a lining and one or several panels.

+

The IfcWindow defines a particular occurrence of a +window inserted in the spatial context of a project. A window +can:

+
    +
  • be inserted into an IfcOpeningElement using the +IfcRelFillsElement relationship, , then the IfcDoor +has an inverse attribute FillsVoids provided, +
      +
    • NOTEÿ View definitions or +implementer agreements may restrict the relationship to only +include one window (or door) into one opening.
      +
    • +
    +
  • +
  • be part of an element assembly, often an +IfcCurtainWall, using the IfcRelAggregates +relationship, then the inverse attribute Decomposes is +provided.
  • +
  • or be a ""free standing"" window, then the IfcWindow has +no inverse attributes FillsVoids or Decomposes +provided.
  • +
+

The IFC specification provides two entities for window +occurrences:

+
    +
  • IfcWindowStandardCase used for all occurrences of +windows, that have a 'Profile' shape representation defined to +which a set of shape parameters for lining and framing properties +apply. Additionally it requires the provision of an +IfcWindowType that references one +IfcWindowLiningProperties and on to many +IfcWindowPanelProperties. +
      +
    • NOTEÿ see +IfcWindowStandardCase for all specific constraints imposed +by this subtype.
    • +
    +
  • +
  • IfcWindow used for all other occurrences of windows, +particularly for windows having only 'Brep', or 'SurfaceModel' +geometry without applying shape parameters.
  • +
+

The actual parameter of the window and/or its shape is defined +at the IfcWindow as the occurrence definition (or project +instance), or by the IfcWindowType as the specific definition (or +project type). The following parameters are given:

+
    +
  • at the IfcWindow or IfcWindowStandardCase for +occurrence specific parameters. The IfcWindow +specifies:
  • +
  • +
      +
    • the window width and height
    • +
    • the window opening direction (by the y-axis of the +ObjectPlacement)
      +
    • +
    +
  • +
  • at the IfcWindowType to +which the IfcWindow is related by the inverse relationship +IsDefinedBy pointing to IfcRelDefinesByType, for +type parameters common to all occurrences of the same type.
  • +
  • +
      +
    • the partitioning type (single panel, double panel, tripel +panel, more panels)
    • +
    • the operation type (swing, tilt and turn, pivot revolve, +fixed case ment, etc.)
    • +
    • the window panel hinge side (by using two different styles +for right and left opening windows)
    • +
    • the construction material type
    • +
    • the particular attributes for the lining by the +IfcWindowLiningProperties
    • +
    • the particular attributes for the panels by theÿ +IfcWindowPanelProperties
    • +
    +
  • +
+
HISTORY New entity in IFC Release 1.0.
+
IFC2x4 CHANGE The attributes PredefinedType and OperationType are added, the applicable type object has been changed to IfcDoorType.
+ +

Material Use Definition

+

The material of the IfcWindow is defined by the +IfcMaterialConstituentSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+

The following keywords for +IfcMaterialConstituentSet.MaterialConstituents[n].Name +shall be used:

+
    +
  • 'Lining' - to indicate that the material constituent applies +to to the window lining
  • +
  • 'Framing' - to indicate that the material constituent applies +to to the window panel(s), if not provided, the 'Lining' material +information applied to panel(s) as well
  • +
  • 'Glazing' - to indicate that the material constituent applies +to to the glazing part
  • +
+

If the fall back single IfcMaterial is referenced, it +applies to the lining and framing of the window.

+

Property Set Use Definition:

+

The property sets relating to the IfcWindow are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcWindow are +part of this IFC release:

+ +

Quantity Use Definition

+

The quantities relating to the IfcWindow are defined by +the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to +MethodOfMeasurement. Quanties shall be never assigned to +the IfcWindowStyle.

+ +

Containment Use Definition

+ +

The IfcWindow, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the +aggregation within anÿelement assembly.

+
    +
  • The IfcWindow is placed within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
  • +
  • The IfcWindow may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Windows may be part +of an IfcCurtainWall as a special focus subtype. In this +case it should not be additionally contained in the project +spatial hierarchy, +i.e.ÿSELF\IfcElement.ContainedInStructure should be +NIL.
  • +
+ +

Figure 141 illustrates window containment.

+
NOTE The containment shall be defined independently of the filling relationship, that is, even if the IfcWindow is a filling of an opening established by IfcRelFillsElement, it is also contained in the spatial structure by an IfcRelContainedInSpatialStructure.
+ + + + +
+""Containment""

Figure 141 — Window containment

+ +

Geometry Use Definitions:

+

The geometric representation of IfcWindow is given by +the IfcProductDefinitionShape, allowing multiple geometric +representation. The IfcWindow, in case of an occurrence +object, gets its parameter and shape from the +IfcWindowType. If an IfcRepresentationMap (a block +definition) is defined for the IfcWindowType, then the +IfcWindow inserts it through the IfcMappedItem +(refered to by IfcShapeRepresentation.Items).

+

Local Placement

+

The local placement for IfcWindow is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

+
    +
  1. The PlacementRelTo relationship of +IfcLocalPlacement shall point to the local placement of +the same element (if given), in which the IfcWindow is +used as a filling (normally an IfcOpeningElement), as +provided by the IfcRelFillsElement relationship.
  2. +
  3. If the IfcWindow is not inserted into an +IfcOpeningElement, then the PlacementRelTo +relationship of IfcLocalPlacement shall point (if given) +to the local placement of the same +IfcSpatialStructureElement that is used in the +ContainedInStructure inverse attribute or to a referenced +spatial structure element at a higher level.
  4. +
  5. If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
  6. +
+

Geometric Representation

+

Theÿgeometric representation of IfcWindow is defined +using the following (potentiallyÿmultiple) +IfcShapeRepresentation's for its +IfcProductDefinitionShape:

+
    +
  • Profile: Aÿ'Curve3D' +consisting of a single losed curve defining the outer boundary of +the window (lining). Theÿwindow parametric representation uses +this profile in order to apply theÿwindow lining and panel +parameter. If not provided, the profile of the +IfcOpeningElement is taken.
  • +
  • FootPrint: A 'GeometricCurveSet', or 'Annotation2D' +representation defining the 2D shape of theÿwindow
  • +
  • Body: A 'SweptSolid', 'SurfaceModel', or 'Brep' +representation defining the 3D shape of theÿwindow.
  • +
+

In addition the parametric representation of a +(limited)ÿwindow shape is available by applying the parameters +fromÿIfcWindowType +referencingÿIfcWindowLiningProperties +andÿIfcWindowPanelProperties. The purpose of the parameter +is described at those entities and below (parametric +representation).

+

Profile -ÿ'Curve3D' representation

+

Theÿwindow profile is represented by a three-dimensional +closed curve within a particular shape representation. The +profile is used to apply the parameter of the parametricÿwindow +representation.ÿThe following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'Profile'
  • +
  • RepresentationType : 'Curve3D', only a single closed +curve shall be contained in the set of +IfcShapeRepresentation.Items.
  • +
+

A 'Profile' representation has to be provided if:

+
    +
  • a parametric representation shall be applied to the +windowÿAND
  • +
  • +
      +
    • the window is 'free standing', or
    • +
    • the opening into which the window is inserted is not extruded +horizontally (i.e. where the opening profile does not match the +window profile)
    • +
    +
  • +
+

FootPrint -ÿ'GeometricCurveSet' or 'Annotation2D' +representation

+

Theÿwindow foot print is represented by a set of +two-dimensionalÿcurves (or in case of 'Annotation2D' additional +hatching and text) within a particular shape representation. The +foot print is used for the plan view representation of +theÿwindow.ÿThe following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'FootPrint'
  • +
  • RepresentationType : 'GeometricCurveSet', or +'Annotation2D'
  • +
+

Body - 'SweptSolid', 'SurfaceModel', or 'Brep' +representation

+

Theÿwindow body is either represented parameterically (see +parametric representation) or by explicit 3D shape. The 3D shape +is given by using extrusion geometry, or surface models, or Brep +models within a particular shape representation. The body is used +for the model view representation of theÿwindow.ÿThe following +attribute values for the IfcShapeRepresentation holding +this geometric representation shall be used:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'SweptSolid', 'SurfaceModel', or +'Brep'
  • +
+

MappedRepresentation

+

The 'FootPrint' and 'Body' geometric representation +ofÿIfcWindow can be shared among several identicalÿwindows +using the 'MappedRepresentation'. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'FootPrint', 'Body'
  • +
  • RepresentationType : 'MappedRepresentation'
  • +
+

The same constraints, as given for theÿ 'FootPrint', 'Body' +representation identifiers, shall apply to the +MappedRepresentation of the +IfcRepresentationMap.

+

Parameteric Representation using parameters at +IfcWindowType

+

The parameters, which define the shape of the +IfcWindow, are given at the IfcWindowType and the +property sets, which are included in the IfcWindowType. +The IfcWindow only defines the local placement. +The overall size of the IfcWindow to +be used to apply the lining or panel parameter provided by the +IfcWindowType is determined by the IfcShapeRepresentation +with the RepresentationIdentifier = 'Profile'. Only in case of an +IfcWindow inserted into an IfcOpeningElement using +the IfcRelFillsElement relatioship, having a horizontal +extrusion (along the y-axis of the IfcDoor), the overall +size is determined by the extrusion profile of the +IfcOpeningElement.

+ +

Figure 142 illustrates the insertion of a window into the IfcOpeningElement by creating an instance of +IfcWindow with PartitioningType = DoublePanelHorizontal. The parameters OverallHeight and OverallWidth show the extent of the window in the positive Z and X axis of the local placement of the window. The lining and the transom are created by the given parameters.

+ + + + +

Figure 142 — Window placement

+ +

Figure 143 illustrates the final window (DoublePanelHorizontal) with first panel having PanelPosition = TOP, OperationType = BOTTOMHUNG and second panel having PanelPosition = BOTTOM and OperationType = TILTANDTURNLEFTHAND.

+ + + + +

Figure 143 — Window planes

+ +

Window opening operation by window type

+

The parameters that defines the shape of the IfcWindow, +are given at the IfcWindowType and the property sets, +which are included in the IfcWindowType. The +IfcWindow only defines the local placement which +determines the opening direction of the window. The overall +layout of the IfcWindow is determined by +itsÿIfcWindowType.PartitioningType. Each window panel has +its own operation type, provided by +IfcWindowPanelProperties.OperationType. All window panels +are assumed to open into the same direction (if relevant for the +particular window panel operation. The hindge side (whether a +window opens to the left or to the right) is determined by the +IfcWindowPanelProperties.OperationType.

+
NOTE ÿThere are different conventions in +different countries on how to show the symbolic presentation of +the window panel operation (the ""triangles""). Either as seen from +the exterior, or from the interior side. The following figures +show the symbolics from the exterior side (the convention as used +predominately in Europe).
+ +

Figure 144 illustrates window operation types.

+ + + +
+ + + + + + + + + + + + + + + + + + + + +

+

The window panel (for side hung windows) opens always +into the direction of the positive Y axis of the local placement. +The determination of whether the window opens to the left or to +the right is done at +IfcWindowPanelProperties.OperationType. Here it is a left +side opening window given byÿOperationType = +SideHungLeftHand.

+

+

If the window should open to the other side, then the +local placement has to be changed. It is still a left hung +window, given by IfcWindowPanelProperties.OperationType +=ÿSideHungLeftHand.

+
+

If the window panel (for side hung windows) opens to +the right, a separate window panel style needs to be used (here +IfcWindowPanelProperties.OperationType +=ÿSideHungRightHand) and it always opens into the direction of +the positive Y axis of the local placement.ÿ

+

+

If the window should open to the other side, then the +local placement has to be changed. It is still a right hung +window, given by IfcWindowPanelProperties.OperationType +=ÿSideHungRightHand.

+.
+ +

Figure 144 — Window operations

+ +
" +1476;IfcWindowStandardCase;" +

The standard window, +IfcWindowStandardCase, defines a window with certain +constraints for the provision of operation types, opening +directions, frame and lining parameters, construction types and +with certain constraints for the geometric representation. The +IfcWindowStandardCase handles all cases of windows, +that:

+
    +
  • are inserted into an opening, represented by +IfcOpeningElement, using the IfcRelFillsElement +relationship
  • +
  • have a local placement relative to this opening, and with the +y-axis of the placement pointing into the opening direction
  • +
  • have a profile geometry, represented by +IfcShapeRepresentation.RepresentationIdentifier=""Profile"" +as a closed curve to which the window parameter apply. The +profile represents a rectangle within the xz plane of the local +placement
  • +
  • have a reference to an IfcWindowType to define the +opening direction and the operation type (swinging, sliding, +folding, etc.) of the window. The attribute OperationType +shall be provided and not being UNDEFINED, and the attribute +ParameterTakesPrecedence shall be ""TRUE"".
  • +
  • have a single IfcWindowLiningProperties and a set of +IfcWindowPanelProperties instances included in the set of +HasPropertySets at IfcWindowType
  • +
+
HISTORY New entity in IFC2x4.
+ +

Type Use Definition

+

IfcWindowStandardCase defines the occuurence of any +window, common information about window types (or styles) is +handled by IfcWindowType. The IfcWindowType (that +has to be present) establishes the common type name, usage +(opening direction, configuration and operation), common set of +properties, including shape parameters, like lining thickness +panel width, etc. and maybe an additional common shape +representations (using IfcRepresentationMap). The +IfcWindowType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

+

Property Set Use Definition:

+

The property sets relating to the IfcWindowStandardCase +are defined at the supertype IfcWindow.

+

Quantity Use Definition

+

The quantities relating to the IfcWindowStandardCase +are defined at the supertype IfcWindow.

+

Containment Use Definition

+

The containment use definitions relating to the +IfcWindowStandardCase are defined at the supertype +IfcWindow.

+

Geometry Use Definitions:

+

The geometric representation of IfcWindowStandardCase +is given by the IfcProductDefinitionShape, allowing +multiple geometric representations. Included are:

+

Local Placement

+

The use of local placement is defined at the supertype +IfcWindow.

+

Geometric Representations

+

The geometric representation of IfcWindowStandardCase +is defined using the following multiple shape representations for +its definition:

+
    +
  • Profile: a three-dimensional closed curve within a +particular shape representation. The profile is used to apply the +parameter of the parametric window representation. The profile +around the edges of the opening is used to apply the window +lining and window panel shape parameter.
  • +
  • MappedRepresentation: A SweptSolid, SurfaceModel, or +Brep Representation or a CSG additionally defining the 3D shape +of the standard window in addition to the parametric +representation by applying the IfcWindowLiningProperties +and an the IfcWindowPanelProperties to the Profile +representation.
  • +
+
    +
  • RepresentationIdentifier : 'Profile'
  • +
  • RepresentationType : 'Curve3D' or 'GeometricCurveSet', +in case of 'GeometricCurveSet' only a single closed curve shall +be contained in the set of +IfcShapeRepresentation.Items.
  • +
+

The following additional constraints apply to the 'Profile' +representation type:

+
    +
  • Curve: being an IfcPolyline defining a +rectangle.
  • +
  • Position: The curve shall lie in the xz plane of the +object placement coordinate (the y coordinate values of the +IfcCartesianPoint's shall be 0.).
  • +
+

As shown in Figure 145, the profile defines the outer boundary to which the window +lining parameters relate as:

+
    +
  • IfcWindowLiningProperties.LiningDepth starting at +distance defined by LiningOffset going into the positive y +direction.
  • +
  • IfcWindowLiningProperties.LiningThickness offset into +the inner side of the rectangle.
  • +
  • IfcWindowLiningProperties.LiningOffset distance along +the positive y direction to where the LiningDepth +applies.
  • +
  • IfcWindowLiningProperties.FirstTransomOffset starting +at the bottom edge of the rectangle (along local x axis) into the +inner side of the rectangle, distance provided as percentage of +overall height. Distance to the centre line of the transom. +SecondTransomOffset defined accordingly.
  • +
  • IfcWindowLiningProperties.FirstMullionOffset starting +at the left edge of the rectangle (along local z-axis) into the +inner side of the rectangle, distance provided as percentage of +overall width. Distance to the centre line of the mullion. +SecondMullionOffset defined accordingly.
  • +
+ + + + +
+""standard

Figure 145 — Window profile

+ +
" +1495;IfcPlate;" +

Definition from IAI: An IfcPlate is a planar and +often flat part with constant thickness. A plate can be a +structural part carrying loads between or beyond points of +support, however it is not required to be load bearing.ÿThe +location of the plate (being horizontal, vertical or sloped) is +not relevant to its definition (in contrary to IfcWall and +IfcSlab (as floor slab)).ÿ

+
NOTE ÿPlates areÿnormally made of steel, other +metallic material, or by glass panels. However the definition of +IfcPlate is material independent and specific material +information shall be handled by using +IfcAssociatesMaterial to assign a material specification +to the IfcPlate.ÿ
+
+NOTE ÿAlthough not necessarily, plates are often add-on +parts. This is represented by the IfcRelAggregates +decomposition mechanism used to aggregate parts, such as +IfcPlate, into a container element, e.g. +IfcElementAssembly, or IfcCurtainWall.ÿ
+
+NOTE The representation of a plate in a structural +analysis model is provided by IfcStructuralSurfaceMember +being part of an +IfcStructuralAnalysisModel.
+

An instance IfcPlate should preferably get its +geometric representation and material assignment through the type +definition by IfcPlateType assigned using the +IfcRelDefinesByType relationship. This allows identical +plates in a construction to be represented by the same instance +of IfcPlateType.

+

A plate may have openings, such as voids or recesses. They are +defined by an IfcOpeningElement attached to the plate +using the inverse relationship HasOpenings pointing to +IfcRelVoidsElement. The position number of a plate as +often used in steel construction is assigned through the +attribute IfcElement.Tag

+

The IFC specification provides two entities for plate +occurrences:

+
    +
  • IfcPlateStandardCase used for all occurrences of +plates, that are prismatic and where the thickness parameter can +be fully described by the IfcMaterialLayerSetUsage. These +plates are always represented geometrically by a 'SweptSolid' +geometry (or by a 'Clipping' geometry based on 'SweptSolid'), if +a 3D geometric representation is assigned. In addition they have +to have a corresponding IfcMaterialLayerSetUsage +assigned.
  • +
  • IfcPlate used for all other occurrences of plates, +particularly for plates with changing thickness, or plates with +non planar surfaces, and plates having only 'SurfaceModel' or +'Brep' geometry.
  • +
+
HISTORY New entity in +IFC Release 2x2
+

Type Use Definition

+

The IfcPlate defines the occuurence of any plate, +common information about plate types (or styles) is handled by +IfcPlateType. The IfcPlateType (if present) may +establish the commonÿtype name, usage (or predefined) type, +common set of properties, common material layer set, and common +shape representations (using IfcRepresentationMap). The +IfcPlateType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

+

If no IfcPlateType is attachedÿ(i.e. if only occurrence +information is given) the PredefinedType should be +provided. If set to .USERDEFINED. a user defined value can be +provided by the ObjectType attribute.

+

Material Use Definition

+

The material of the IfcPlate is defined by +IfcMaterialLayerSet, or IfcMaterial and attached by +the IfcRelAssociatesMaterial.RelatingMaterial. It +is accessible by the inverse HasAssociations +relationship.

+
NOTE It is illegal to assign an +IfcMaterialLayerSetUsage to an IfcPlate. Only the +subtype IfcPlateStandardCase supports this +concept.
+

Material information can also be given at the +IfcPlateType, defining the common attribute data for all +occurrences of the same type.ÿIt is then accessible by the +inverse IsTypedBy +relationship pointing to IfcPlateType.HasAssociations and +via IfcRelAssociatesMaterial.RelatingMaterial.

+

Property Set Use Definition

+

The property sets relating to the IfcPlate are defined +by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcPlate are part +of this IFC release:

+ +

Quantity Use Definition

+

The quantities relating to the IfcPlate and +IfcPlateStandardCase are defined by the +IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quanties shall +be never assigned to the IfcPlateType.

+ +

Containment Use Definitions

+

The IfcPlate, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second relationship is the aggregation within +anÿelement assembly.

+
    +
  • TheÿIfcPlate is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes ofÿIfcSpatialStructureElement are valid spatial +containers, with IfcBuildingStorey being the default +container.
  • +
  • TheÿIfcPlate may be aggregated into an element +assembly using the objectified relationship +IfcRelAggregates, referring to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this +case, no additional relationship to the spatial hierarchy shall +be given (i.e.ÿSELF\IfcElement.ContainedInStructure = +NIL), the relationship to the spatial container is handled by the +element assembly.
  • +
+

Geometry Use Definition

+

The geometric representation of IfcPlate is +given by the IfcProductDefinitionShape, allowing multiple +geometric representations. Included are:

+

Local Placement

+

The local placement for IfcPlate is defined in +its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

+
    +
  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to +a spatial structure element at a higher level, referenced by +that. +
      +
    • If the IfcPlate is part of an assembly, the +PlacementRelTo relationship of IfcLocalPlacement +shall point to the local placement of the container element, e.g. +IfcElementAssembly,
    • +
    +
  • +
  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
  • +
+

Geometric Representation

+

Currently, the 'Surface', +'FootPrint', 'Body', and 'Box' +representations are supported. The 'Box' representation includes +the representation type 'BoundingBox' and is explained at +IfcBuildingElement.

+

Surface Representation

+

The surfacic geometric representation of IfcPlate is +defined using the 'Surface' representation.

+
    +
  • RepresentationIdentifier : 'Surface'
  • +
  • RepresentationType : 'Surface3D'
  • +
+
NOTE The 'Surface' can be used to define a +surfacic model of the building (e.g. for analytical purposes, or +for reduced Level of Detail representation).
+

Body Representation

+

The body representation of IfcPlate can be represented +using the representation types 'SweptSolid', 'Clipping', +'MappedRepresentation', 'SurfaceModel', and 'Brep'. The +representation types 'SurfaceModel' and 'Brep' are explained at +IfcBuildingElement.

+

SweptSolid Representation Type

+

The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
If a corresponding material definition using +IfcMaterialLayerSetUsage can be assigned, the subtype +IfcPlateStandardCase shall be used.
+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'SweptSolid'
  • +
+

The following additional constraints apply to the swept solid +representation:

+
    +
  • Solid: IfcExtrudedAreaSolid is required,
  • +
  • Profile: IfcArbitraryClosedProfileDef, +IfcArbitraryProfileDefWithVoids, IfcRectangleProfileDef, +IfcCircleProfileDef, IfcEllipseProfileDef shall be +supported.
  • +
  • Extrusion: The profile can be extruded perpendicularly +or non-perpendicularly to the plane of the swept profile.
  • +
+

Clipping Representation Type

+

The following attribute values for the +IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'Clipping'
  • +
+

MappedRepresentation Representation Type

+

The 'MappedRepresentation' shall be supported as it allows for +reusing the geometry definition of the member type at all +occurrences of the same type. The following attribute values for +the IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'MappedRepresentation'
  • +
+

The same constraints, as given for the 'SweptSolid', +'Clipping', 'SurfaceModel', and 'Brep' geometric representation, +shall apply to the MappedRepresentation of the +IfcRepresentationMap.

+
" +1500;IfcPlateStandardCase;" +

The standard plate, +IfcPlateStandardCase, defines a plate with certain +constraints for the provision of material usage, parameters and +with certain constraints for the geometric representation. The +IfcPlateStandardCase handles all cases of plates, that:

+
    +
  • have a reference to the IfcMaterialLayerSetUsage +defining the material layers of the plate with thicknesses
  • +
  • are based on an extrusion of a planar surface as defined by the +plate profile
  • +
  • have a constant thickness along the extrusion direction
  • +
  • are consistent in using the correct material layer set offset +to the base planar surface in regard to the shape +representation
  • +
  • are extruded perpendicular to the plane surface
  • +
+

The definitions of plate openings and niches are the same as +given at the supertype IfcPlate. The same agreements to the +special types of plates, as defined in the PredefinedType +attribute apply as well.

+
HISTORY New entity in +IFC2x Edition 4.
+

Type Use Definition

+

The IfcPlateStandardCase defines the occuurence of any +plate, common information about plate types (or styles) is handled +by IfcPlateType. The IfcPlateType (if present) may +establish the common type name, usage (or predefined) type, +common set of properties, common material layer set, and common +shape representations (using IfcRepresentationMap). The +IfcPlateType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy attribute.

+

The IfcPlateStandardCase defines in addition that the +IfcPlateType should have a unique +IfcMaterialLayerSet, that is referenced by +the IfcMaterialLayerSetUsage assigned to all +occurrences of this plate type.

+ +

Figure 107 illustrates assignment of IfcMaterialLayerSetUsage and IfcMaterialLayerSet to the IfcPlateStandardCase as the plate occurrence and to the IfcPlateType. The same IfcMaterialLayerSet shall be shared by many occurrences of IfcMaterialLayerSetUsage. This relationship shall be consistent to the relationship between the IfcPlateType and the IfcPlateStandardCase.

+ + + + +
+

 

Figure 107 — Plate type definition

+ +

Material Use Definition

+

The material of the IfcPlateStandardCase is defined by +IfcMaterialLayerSetUsage and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship. +Multi-layer plates can be represented by refering to several +IfcMaterialLayer's within the IfcMaterialLayerSet +that is referenced from the +IfcMaterialLayerSetUsage. 

+

Material information can also be given at the +IfcPlateType, defining the common attribute data for all +occurrences of the same type. It is then accessible by the +inverse IsDefinedBy relationship pointing to +IfcPlateType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial. See Type Use +Definition for additional agreements for standard plates.

+ +

As shown in Figure 108, the following conventions shall be met:

+
    +
  • The reference coordinate system is the coordinate system established by the IfcExtrudedAreaSolid.Position.
  • +
  • The reference plane is the plane defined by the extruded profile of IfcExtrudedAreaSolid.SweptSolid. The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is given as a distance from this plane.
  • +
  • The IfcMaterialLayerSetUsage.DirectionSense defines how the IfcMaterialLayer's are assigned to the reference plane. POSITIVE means in direction to the positive z-axis of the reference coordinate system.
  • +
  • The IfcMaterialLayerSetUsage.OffsetFromReferenceLine is the distance parallel to the reference plane and always perpendicular to the base (XY) plane of the reference coordinate system. This is independent of a potential non-perpendicular extrusion given by IfcExtrudedAreaSolid.ExtrudedDirection <> 0.,0.,1. A positive value of IfcMaterialLayerSetUsage.OffsetFromReferenceLine would then point into the positive z-axis of the reference coordinate system.
  • +
  • The Thickness of each IfcMaterialLayer shall be the parallel distance (measured perpendicular to the base plane). The TotalThickness of the IfcMaterialLayerSet is the sum of all layer thicknesses and in case of a perpendicular extrusion identical with IfcExtrudedAreaSolid.Depth
  • +
  • The IfcMaterialLayerSetUsage.LayerSetDirection i always AXIS3.
  • +
+ + + + +

Figure 108 — Plate material layers

+ +

Property Set Use Definition:

+

The property sets relating to the IfcPlateStandardCase +are defined at the supertype IfcPlate.

+

Quantity Use Definition

+

The quantities relating to the IfcPlateStandardCase are +defined at the supertype IfcPlate.

+

Containment Use Definition

+

The containment use definitions relating to the +IfcPlateStandardCase are defined at the supertype +IfcPlate.

+

Geometry Use Definitions

+

The geometric representation of IfcPlateStandardCase is +given by the IfcProductDefinitionShape, allowing multiple +geometric representation. Included are:

+

Local Placement

+

The use of local placement is defined at the supertype +IfcPlate.

+

Geometric Representations

+

Currently, the use of 'SweptSolid' and 'Clipping' +representations is supported. In addition the general +representation type 'BoundingBox' is allowed. The geometry use +definitions for 'BoundingBox', is explained at +IfcBuildingElement.

+

SweptSolid Representation

+

The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used for the 'SweptSolid' representation:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'SweptSolid'
  • +
+

The following additional constraints apply to the swept solid +representation:

+
    +
  • Solid: IfcExtrudedAreaSolid is required,
  • +
  • Profile: IfcArbitraryClosedProfileDef, +IfcRectangleProfileDef, IfcRoundedRectangleProfileDef, +IfcCircleProfileDef, IfcEllipseProfileDef shall be +supported.
  • +
  • Extrusion: The profile can be extruded perpendicularly +or non-perpendicularly to the plane of the swept profile.
  • +
  • Material: The definition of the +IfcMaterialLayerSetUsage, particularly of the +OffsetFromReferenceLine and the +ForLayerSet.TotalThickness, has to be consistent to the +'SweptSolid' representation.
  • +
+ +

Figure 109 illustrates a 'SweptSolid' geometric representation.

+
NOTE The following interpretation of dimension parameter applies for polygonal plates (in ground floor view):

+
    +
  • IfcArbitraryClosedProfileDef.OuterCurve: closed bounded curve interpreted as area (or foot print) of the plate.
  • +
+
+ + + + +

Figure 109 — Plate body extrusion

+ +

Clipping representation

+

The 'Clipping' geometric representation of +IfcSlabStandardCase is defined using the swept area geometry +with additional clippings applied. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'Clipping'
  • +
+

The following constraints apply to the 'Clipping' +representation:

+
    +
  • Solid: see 'SweptSolid' shape representation,
  • +
  • Profile: see 'SweptSolid' shape +representation,
  • +
  • Extrusion: see 'SweptSolid' shape +representation,
  • +
  • Material: see 'SweptSolid' shape +representation,
  • +
  • Boolean result: The IfcBooleanClippingResult +shall be supported, allowing for Boolean differences between the +swept solid (here IfcExtrudedAreaSolid) and one or several +IfcHalfSpaceSolid.
  • +
+ +

Figure 110 illustrates a 'Clipping' geometric representation with definition of a plate using advanced geometric representation. The profile is extruded non-perpendicular and the plate body is clipped at the eave.

+ + + + +

Figure 110 — Plate body clipping

+ +
" +1507;IfcChimney;" +

Definition from ISO 6707-1:1989: Construction +containing one or more flues. Flue: Duct designed to convey the +products of combustion to the open air. Chimney stack: Part of +the chimney that projects above a roof.

+

Definition from IAI: Chimneys are typically vertical, +or as near as vertical, parts of the construction of a building +and part of the building fabric. Often constructed by pre-cast or +insitu concrete, today seldom by bricks.

+
HISTORY New entity in +IFC2x4
+

Property Set Use Definition:

+

The property sets relating to the IfcChimney are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcChimney are +part of this IFC release:

+ +

Property sets can also be given at the IfcChimneyType, +defining the common property data for all occurrences of the same +type.ÿIt is then accessible by the inverse IsTypedBy relationship pointing to +IfcChimneyType.HasPropertySets. If both are given, then +the properties directly assigned to IfcChimney overrides +the properties assigned to IfcChimneyType.

+

Quantity Use Definition:

+

The quantities relating to the IfcChimney are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties. It is accessible by the inverse +IsDefinedBy relationship. The following base quantities +are defined and should be exchanged with the +IfcElementQuantity.MethodOfMeasurement = 'BaseQuantities'. +Other quantities can be defined being subjected to local standard +of measurement with another string value assigned to Name +and a value provided for MethodOfMeasurement. Quanties +shall be never assigned to the IfcChimneyType.

+ +
" +1514;IfcBuildingElementProxy;" +

Definition from IAI: The IfcBuildingElementProxy +is a proxy definition that provides the same functionality as an +IfcBuildingElement, but without having a predefined meaning +of the special type of building element, it represents. Proxies can +also be used as spatial place holders or provisions, that maybe +later replaced by special types of elements.

+

One use of the proxy object is a provision for voids, i.e. where +a particular volume of space is requested by some engineering +function that might later be accepted or rejected and if accepted +potentially transformed into a void within a building element, like +a wall opening, or a slab opening. The provision for voids is +exchanged as an IfcBuildingElementProxy with the +PredefinedType = ProvisionForVoid.

+

Other usages of IfcBuildingElementProxy include:

+
    +
  • The IfcBuildingElementProxy can be used to exchange +special types of building elements for which the current IFC +Release does not yet provide a semantic definition.
  • +
  • The IfcBuildingElementProxy can also be used to +represent building elements for which the participating +applications can not provide additional semantic +classification.
  • +
+
HISTORY  New entity +in IFC Release 2x.
+IFC2x4 CHANGE  The attribute +CompositionType has been replaced by PredefinedType, +being a superset of the enumerators.
+

Type Use Definition

+

The IfcBuildingElementProxy defines the occuurence of any +building element, common information about the types (or styles) is +handled by IfcBuildingElementProxyType.

+

The IfcBuildingElementProxyType (if present) may +establish the common type name, usage (or predefined) type, common +material, common set of properties and common shape representations +(using IfcRepresentationMap). The +IfcBuildingElementProxyType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsTypedBy attribute.

+
+

NOTE The IfcBuildingElementProxyType can be used +to share common information among many occurrences of the same +proxy without establishing a particular semantic meaning of the +type.

+
+

If no IfcBuildingElementProxyType is attached (i.e. if +only occurrence information is given) the PredefinedType +should be provided. If set to .USERDEFINED. a user defined value +can be provided by the ObjectType attribute.

+

Material Use Definition

+

The material of the IfcBuildingElementProxy is defined by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

+
Note It is illegal to assign an +IfcMaterial to an IfcBuildingElementProxy with the +PredefinedType = ProvisionForVoid.
+

Material information can also be given at the +IfcBuildingElementProxyType, defining the common attribute +data for all occurrences of the same type. It is then +accessible by the inverse IsTypedBy relationship pointing to +IfcBuildingElementProxyType.HasAssociations and via +IfcRelAssociatesMaterial.RelatingMaterial to +IfcMaterial. If both are given, then the material directly +assigned to IfcBuildingElementProxy overrides the material +assigned to IfcBuildingElementProxyType.

+

Property Set Use Definition:

+

The property sets relating to the IfcBuildingElementProxy +are defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible by +the inverse IsDefinedBy relationship. The following property +set definitions specific to the IfcBuildingElementProxy are +part of this IFC release:

+ +

Property sets can also be given at the +IfcBuildingElementProxyType, defining the common property +data for all occurrences of the same type. It is then +accessible by the inverse IsTypedBy relationship pointing to +IfcBuildingElementProxyType.HasPropertySets. If both are +given, then the properties directly assigned to +IfcBuildingElementProxy overrides the properties assigned to +IfcBuildingElementProxyType.

+

Containment Use Definition

+

The IfcBuildingElementProxy, as any subtype of +IfcBuildingElement, may participate in two different +containment relationships. The first (and in most implementation +scenarios mandatory) relationship is the hierachical spatial +containment, the second (optional) relationship is the aggregation +within an element assembly.

+
    +
  • The IfcBuildingElementProxy is places within the project +spatial hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, refering to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid +spatial containers, with IfcBuildingStorey being the default +container.
  • +
  • The IfcBuildingElementProxy may be aggregated into an +element assembly using the objectified relationship +IfcRelAggregates, refering to it by its inverse attribute +SELF\IfcObjectDefinition.Decomposes. Any subtype of +IfcElement can be an element assembly, with +IfcElementAssembly as a special focus subtype. In this case +it should not be additionally contained in the project spatial +hierarchy, i.e. SELF\IfcElement.ContainedInStructure +should be NIL.
  • +
+

Geometry Use Definition

+

The geometric representation of IfcBuildingElementProxy +is given by the IfcProductDefinitionShape, allowing multiple +geometric representations. Included are:

+

Local Placement

+

The local placement for any IfcBuildingElementProxy is +defined in its supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate system +that is referenced by all geometric representations. The local +placement can be given relativly.

+
    +
  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the same IfcSpatialStructureElement, which is +used in the ContainedInStructure inverse attribute, or to a +spatial structure element at a higher level, referenced by +that.
  • +
  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
  • +
+

Geometric Representation

+

Currently, the 'FootPrint', 'Body', and 'Box' representations +are supported. The 'Box' representation includes the representation +type 'BoundingBox' and is explained at +IfcBuildingElement.

+

FootPrint Representation

+

Any building element proxy may be represented by a geometric +curve set, given by a collection of 2D points and curves. The foot +pring geometric representation of IfcBuildingElementProxy is +defined using the 'FootPrint' representation.

+
    +
  • RepresentationIdentifier: 'FootPrint'
  • +
  • RepresentationType: 'GeometricCurveSet', +'Annotation2D'
  • +
+

Body Representation

+

The body representation of IfcBuildingElementProxy can be +represented using the representation types 'GeometricSet', +'SweptSolid', 'CSG' 'SurfaceModel', 'Brep', and +'MappedRepresentation'. The representation types 'SurfaceModel', +'Brep', and 'MappedRepresentation' are explained at +IfcBuildingElement.

+

GeometricSet Representation Type

+

Any building element proxy may be represented by a geometric +set, given by a collection of 2D and 3D points, curves, and +surfaces. It represents the body of the proxy object, when no +topological structure is available. The following attribute values +for the IfcShapeRepresentation holding this geometric +representation shall be used:

+
    +
  • RepresentationIdentifier: 'Body'
  • +
  • RepresentationType: 'GeometricSet'
  • +
+

SweptSolid Representation Type

+

Any building element proxy may be represented by swept solid +geometry (either by extrusion or by revolution). The following +attribute values for the IfcShapeRepresentation holding this +geometric representation shall be used:

+
    +
  • RepresentationIdentifier: 'Body'
  • +
  • RepresentationType: 'SweptSolid'
  • +
+

No further restrictions (e.g., for the profile or extrusion +direction) are defined at this level. A single or multiple swept +area solid(s) can be the Items of the +IfcShapeRepresentation.

+

CSG Representation Type

+

Any building element proxy may be represented by a CSG primitive +or CSG tree. The following attribute values for the +IfcShapeRepresentation holding this geometric representation +shall be used:

+
    +
  • RepresentationIdentifier: 'Body'
  • +
  • RepresentationType: 'CSG'
  • +
+

No further restrictions (e.g., for the depths of the CSG tree) +are defined at this level.

+
" +1526;IfcCovering;" +

Definition from ISO 6707-1:1989: term used: Finishing - +final coverings and treatments of surfaces and their +intersections.

+

A covering is an element which +covers some part of another element and is fully dependent on +that other element. The IfcCovering defines the occurrence +of a covering type, that (if given) is expressed by the +IfcCoveringType. Examples of coverings include wall +claddings, floorings and suspended ceilings. Coverings are +elements with relationships to the covered element and the space +on the other side, they may contain openings, assigned by +IfcRelVoidsElement, material information, assigned by +IfcRelAssociatesMaterial, and others.

+
NOTE A more basic information about claddings, +floorings, and ceilings of a space can be attached to +IfcSpace's using the Pset_SpaceCommon properties. Then +only a name can be provided and the covering quantities would be +interpreted from the space quantities.
+

Coverings can be assigned to

+
    +
  • a space represented by IfcSpace +
      +
    • using the inverse relationship CoversSpaces pointing +to IfcRelCoversSpaces. The space is then accessible via +IfcRelCoversSpaces.RelatedSpace. It defines to which space +a covering is facing towards. +
        +
      • NOTE The mere containment relationship between an +IfcCovering and an IfcSpace is +created by using +IfcRelContainedInSpatialStructure
      • +
      +
    • +
    +
  • +
  • a space boundary represented by IfcRelSpaceBoundary +
      +
    • using the inverse relationship ProvidesBoundaries +pointing to IfcRelSpaceBoundary. The space is then +accessible via IfcRelSpaceBoundary.RelatingSpace.
    • +
    +
  • +
  • a building element represented by IfcBuildingElement +
      +
    • using the inverse relationship Covers pointing to +IfcRelCoversBldgElements. The building element is then +accessible via +IfcRelCoversBldgElements.RelatingBuildingElement.
    • +
    +
  • +
+

The following guideline shall apply:

+
    +
  • (default) if the space has coverings that may not have an own +shape representation and no defined relationships to the building +elements they cover, then the IfcCovering shall be +assigned to IfcSpace using the IfcRelCoversSpaces +relationship,
  • +
  • if the space has coverings that have an own shape +representation and the space has defined space boundaries, then +the covering, which relates to that space, may be assigned to the +space boundaries using the link +toÿIfcRelSpaceBoundary,
  • +
  • if the covering does not relate to a space, then the covering +should be assigned to the building element or a distribution +element using the IfcRelCoversBldgElements +relationship.
  • +
+
HISTORY New entity in IFC Release 1.0.
+
IFC2x CHANGE The attribute PredefinedType is now optional and should only be inserted when no type information, given by IfcCoveringType, is assigned to the IfcCovering occurrence by IfcRelDefinesByType.
+
IFC2x4 CHANGE The IfcCovering is restricted to coverings of building elements by having +RelatingBuildingElement pointing to IfcBuildingElement.
+ +

Type Use Definition

+

The IfcCovering defines the occuurence of any covering, +common information about covering types (or styles) is handled by +IfcCoveringType. The IfcCoveringType (if present) +may establish the commonÿtype name, usage (or predefined) type, +common set of properties, common material layer set, and common +shape representations (using IfcRepresentationMap). The +IfcCoveringType is attached using the +IfcRelDefinedByType.RelatingType objectified relationship +and is accessible by the inverse IsDefinedBy +attribute.

+

As an additional use agreement for standard coverings (i.e. +slabs with constant thickness along the extrusion direction), the +IfcCoveringType should have a unique +IfcMaterialLayerSet, that is referenced by +theÿIfcMaterialLayerSetUsage assigned to all occurrences +of this covering type.

+ +

Figure 91 illustrates assignment of IfcMaterialLayerSetUsage and IfcMaterialLayerSet to the covering type and the covering occurrence.

+ + + + +

Figure 91 — Covering material usage

+ +

If an IfcCoveringType is assigned to the +IfcCovering, the attribute PredefinedType shall not +be assigned, or shall be identical to +IfcCoveringType.PredefinedType.

+

Property Set Use Definition:

+

The property sets relating to the IfcCovering are +defined by the IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to the IfcCovering are +part of this IFC release:

+
    +
  • Pset_CoveringCommon: common property set for all +covering occurrences +
      +
    • Pset_CoveringCeiling: specific property set +for all occurrences of coverings with the PredefinedType: +CEILING
    • +
    • Pset_CoveringFlooring: specific property set +for all occurrences of coverings with the PredefinedType: +FLOORING
    • +
    +
  • +
+

Quantity Use Definition:

+

The quantities relating to the IfcCovering are defined +by the IfcElementQuantity and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +base quantities are defined and should be exchanged with the +IfcElementQuantity.Name = 'BaseQuantities'. Other +quantities can be defined being subjected to local standard of +measurement with another string value assigned to Name and +a value provided for MethodOfMeasurement. Quantities shall +never be assigned to the IfcCoveringType.

+ +

Containment Use Definition

+

The IfcCovering has a containment relationship within +the hierarchical spatial structure.

+
    +
  • The IfcCovering is places within the project spatial +hierarchy using the objectified relationship +IfcRelContainedInSpatialStructure, referring to it by its +inverse attribute SELF\IfcElement.ContainedInStructure. +Subtypes of IfcSpatialStructureElement are valid spatial +containers, with IfcSpace being the default +container.
  • +
+

Geometry Use Definitions

+

The geometric representation of IfcCovering is given by +the IfcProductDefinitionShape, allowing multiple geometric +representation. Included are:

+

Local Placement

+

The local placement for IfcCovering is defined in its +supertype IfcProduct. It is defined by the +IfcLocalPlacement, which defines the local coordinate +system that is referenced by all geometric representations.

+
    +
  • The PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the same +IfcSpatialStructureElement , which is used in the +ContainedInStructure inverse attribute, or to a spatial +structure element at a higher level, referenced by that.
  • +
  • If the IfcCovering, however, is assigned to an +IfcBuildingElement, and this element defines its own local +placement, than the PlacementRelTo relationship of +IfcLocalPlacement shall point (if given) to the local +placement of the IfcBuildingElement.
  • +
  • If the relative placement is not used, the absolute placement +is defined within the world coordinate system.
  • +
+

Geometric Representations

+

The geometric representation of the IfcCovering depends +on two criteria:

+
    +
  1. Does it define an area or a volume?
  2. +
  3. Is the base surface (either the IfcRelSpaceBoundary or +the surface of the IfcBuildingElement it relates to) a +planar surface or a cylindrical surface?
  4. +
+

GeometricSet Representation

+

The 'GeometricSet' geometric representation of +IfcCovering supports area definitions as 3D surfaces.ÿ

+
    +
  • RepresentationIdentifier : 'Surface'
  • +
  • RepresentationType : 'GeometricSet'
  • +
+

The following additional constraints apply to the +'GeometricSet' representation of IfcCovering:

+
    +
  • for planar base surfaces - bounded surface +representation
  • +
  • for cylindrical base surfaces - swept surface +representation
  • +
+ +

Figure 92 illustrates a planar surface representation where the area of IfcCovering is given by an IfcPolyLoop for planar base surfaces (here given by the IfcRelSpaceBoundary).

+
    +
  • The implicit planar surface of the IfcPolyLoop shall be identical with the planar surface defined by the IfcRelSpaceBoundary.
  • +
+ + + + +

Figure 92 — Covering surface planar

+ +

Figure 93 illustrates a cylindrical surface representation where the area of the IfcCovering is given by an IfcSurfaceOfLinearExtrusion for cylindrical base surfaces (here given by the IfcRelSpaceBoundary - such as caused by a round wall).

+
    +
  • The geometry representation of the IfcCovering is given by the IfcTrimmedCurved (the Curve parameter of the +IfcArbitraryOpenProfileDef - in cases of faceted representation also an IfcPolyline). It is extruded within the plane of the base surface using the Depth parameter of the IfcSurfaceOfLinearExtrusion.
  • +
+ + + + +

Figure 93 — Covering surface cylindrical

+ +

SweptSolid Representation

+

The 'SweptSolid' geometric representation of +IfcCovering supports volume definitions as 3D solids.ÿ

+
    +
  • RepresentationIdentifier : 'Body'
  • +
  • RepresentationType : 'SweptSolid'
  • +
+

The following additional constraints apply to the 'SweptSolid' +representation of IfcCovering:

+
    +
  • for planar base surfaces - swept area representation
  • +
  • for cylindrical base surfaces - swept area +representation
  • +
+ +

Figure 94 illustrates a body representation where the volume of IfcCovering is given by an IfcExtrudedAreaSolid for planar base surfaces (here given by the IfcRelSpaceBoundary).

+
    +
  • The extruded area (IfcArbitraryClosedProfileDef) shall be coplanar to the surface defined by the IfcRelSpaceBoundary.
  • +
+ + + + +

Figure 94 — Covering body planar

+ +

Figure 95 illustrates a body representation where the volume of the IfcCovering is given by an IfcExtrudedAreaSolid for cylindrical base surfaces (here given by the IfcRelSpaceBoundary - such as caused by a round wall).

+
    +
  • The geometry representation of the IfcCovering is given by the IfcCompositeCurve (the OuterCurve parameter of the +IfcArbitraryClosedProfileDef - in cases of faceted representation also a closed IfcPolyline). It is extruded along the plane of the base surface using the Depth parameter of the IfcSurfaceOfLinearExtrusion.
  • +
+ + + + +

Figure 95 — Covering body circular

+ +" +1543;IfcRelCoversBldgElements;" +

Definition from IAI: The +IfcRelCoversBldgElements is an objectified relationship +between an element and one to many coverings, which cover the +building element.

+
    +
  • IfcRelCoversBldgElements, this relationship, expresses +the primary relation to the element,
  • +
  • IfcRelCoversSpaces expresses the primary relation to +the space.
  • +
+
HISTORY New Entity in +IFC Release 1.5
+
IFC2x4 CHANGE: The data +type of the attribute RelatingElement has been changed +from IfcElement to its subtype +IfcBuildingElement.
+
" +1546;IfcShadingDevice;" +

Definition from IAI: Shading devices are purpose built +devices to protect from the sunlight, from natural light, or +screening them from view. Shading devices can form part of the +facade or can be mounted inside the building, they can be fixed +or operable.

+
NOTE Also other building elements such as +protruding slabs or balconies can act as shading devices. Those +elements however have another primary purpose and are defined as +IfcSlab or by other subtypes of IfcBuildingElement. +The particular additional purpose as a shading device is provided +by assigning the property set Pset_ElementShading to those +building elements.
+
HISTORY New entity in +IFC2x4
+
" +1556;IfcSlabType;" +

The element type IfcSlabType defines commonly shared +information for occurrences of slabs. The set of shared information +may include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common material layer definitions
  • +
  • common shape representations
  • +
  • +
    NOTE It is illegal to share shape +representations as representation maps for occurrences of +IfcSlabStandardCase.
    +
  • +
+

It is used to define a slab specification (i.e. the specific +product information, that is common to all occurrences of that +product type). Slab types may be exchanged without being already +assigned to occurrences.

+
NOTE The product representations are defined as +representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element occurrence +instance through the IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
+

The occurrences of the IfcSlabType within building models +are represented by instances of IfcSlabStandardCase if the +IfcSlabType has a single associated +IfcMaterialLayerSet; otherwise they are represented by +instances of IfcSlab, or IfcSlabElementedCase.

+
+

HISTORY  New +entity in Release IFC2x2.

+
+

Informal proposition:

+
    +
  1. The material assignment, if provided using the +IfcRelAssociatesMaterial relationship, shall not reference +the IfcMaterialLayerSetUsage.
  2. +
+

Material Use Definition

+

The material of the IfcSlabType is defined by the +IfcMaterialLayerSet or as fall back by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcSlabType, if there is at least +one occurrences. of IfcSlabStandardCase for this +type.
+

Layer Set Use Definition:

+

The shared material layer set definition is defined by assigning +an IfcMaterialLayerSet (see material use definition above). +The IfcMaterialLayer refers to one or several of +IfcMaterial that is the common for all slab occurrence, if +used. It is only applicable if the IfcSlabType has only +occurrences of type IfcSlabStandardCase (see definition of +IfcSlabStandardCase for further information).

+
NOTE Since each individual instance of +IfcSlabStandardCase defines its own +IfcMaterialLayerSetUsage including the offset from the +reference plane, the same IfcSlabType can be used +independently of the reference plane alignment of its +occurrences.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcSlabType are +defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcWallType are part of this IFC +release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcSlabType and those that are only assignable to +IfcSlab. If the same property is assigned to the +IfcSlabType and the IfcSlab being an occurrence of +the IfcSlabType, then the occurrence property overrides the +type property.
+ +
" +1559;IfcWallType;" +

Definition from IAI: The element type +IfcWallType defines commonly shared information for +occurrences of walls. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common material layer definitions
  • +
  • common shape representations
  • +
  • +
    NOTE It is illegal to share shape +representations as representation maps for occurrences of +IfcWallStandardcase.
    +
  • +
+

It is used to define a wall specification (i.e. the specific +product information, that is common to all occurrences of that +product type). Wall types may be exchanged without being already +assigned to occurrences.

+
+

NOTE: The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.

+
+

Occurrences of the IfcWallType within building models +are represented by instances of IfcWallStandardCase if the +IfcBeamType has a single associated +IfcMaterialLayerSet; otherwise they are represented by +instances of IfcWall, or IfcWallElementedCase. +Occurrences of the IfcWallType within structural analysis +models are represented by instances of +IfcStructuralSurfaceMember, or its applicable +subtypes.

+
HISTORY: New entity in +Release IFC2x Editon 2.
+

Informal proposition:

+
    +
  1. The material assignment, if provided using the +IfcRelAssociatesMaterial relationship, shall not reference +the IfcMaterialLayerSetUsage.
  2. +
+

Material Use Definition

+

The material of the IfcWallType is defined by the +IfcMaterialLayerSet or as fall back by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcWallType, if there is at least +one occurrences. of IfcWallStandardCase for this +type.
+

Layer Set Use Definition:

+

The shared material layer set definition is defined by +assigning an IfcMaterialLayerSet (see material use +definition above). The IfcMaterialLayer refers to one or +several of IfcMaterialLayer that is the common for all +wall occurrence, if used. It is only applicable if the +IfcWallType has only occurrences of type +IfcWallStandardCase (see definition of +IfcWallStandardCase for further information).

+
NOTE Since each individual instance of +IfcWallStandardCase defines its own +IfcMaterialLayerSetUsage including the offset from the +wall axis, the same IfcWallType can be used independently +of the axis alignment of its occurrences.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcWallType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcWallType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcWallType and those that are only assignable to +IfcWall. If the same property is assigned to the +IfcWallType and the IfcWall being an occurrence of +the IfcWallType, then the occurrence property overrides +the type property.
+ +
" +1562;IfcStairFlightType;" +

Definition from IAI: The element type (IfcStairFlightType) + defines a list of commonly shared property set definitions of a stair flight + and an optional set of product representations. It is used to define an stair + flight specification (i.e. the specific product information, that is common to + all occurrences of that product type).

+
+

NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + gets assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem.

+

A stair flight type is used to define the common properties of a certain + type of a stair flight that may be applied to many instances of that type to + assign a specific style. Stair flight types may be exchanged without being + already assigned to occurrences.

+

The occurrences of the IfcStairFlightType are represented by + instances of IfcStairFlight.

+
+

HISTORY: New entity in Release IFC2x + Edition 2.

+
" +1565;IfcRailingType;" +

Definition from IAI: The element type (IfcRailingType) + defines a list of commonly shared property set definitions of a railing element + and an optional set of product representations. It is used to define a railing + specification (i.e. the specific product information, that is common to all + occurrences of that product type).

+
+

NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + gets assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem.

+

A railing type is used to define the common properties of a certain type + of railing that may be applied to many instances of that type to assign a + specific style. Railing types may be exchanged without being already assigned + to occurrences.

+

The occurrences of the IfcRailingType are represented by + instances of IfcRailing.

+
+

HISTORY New entity in Release IFC2x + Editon 2.

+
" +1568;IfcRampFlightType;" +

Definition from IAI: The element type (IfcRampFlightType) + defines a list of commonly shared property set definitions of a ramp flight and + an optional set of product representations. It is used to define an ramp flight + specification (i.e. the specific product information, that is common to all + occurrences of that product type).

+
+

NOTE: The product representations are defined as + representation maps (at the level of the supertype IfcTypeProduct, which + gets assigned by an element occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem.

+

A ramp flight type is used to define the common properties of a certain + type of a ramp flight that may be applied to many instances of that type to + assign a specific style. Ramp flight types may be exchanged without being + already assigned to occurrences.

+

The occurrences of the IfcRampFlightType are represented by + instances of IfcRampFlight.

+
+

HISTORY New entity in Release IFC2x + Edition 2.

+
" +1571;IfcBeamType;" +

Definition from IAI: The element type +IfcBeamType defines commonly shared information for +occurrences of beams. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common profile definitions
  • +
  • common shape representations
  • +
+

It is used to define a beam specification, or beam style (i.e. +the specific product information that is common to all +occurrences of that beam type). Beam types may be exchanged +without being already assigned to occurrences.

+

Occurrences of the IfcBeamType within building models +are represented by instances of IfcBeamStandardCase if the +IfcBeamType has a single associated +IfcMaterialProfileSet; otherwise they are represented by +instances of IfcBeam. Occurrences of the +IfcBeamType within structural analysis models are +represented by instances of IfcStructuralCurveMember, or +its applicable subtypes.

+
HISTORY New entity in +Release IFC2x Edition 2.
+

Material Use Definition

+

The material of the IfcBeamType is defined by the +IfcMaterialProfileSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcBeamType, if there is at least +one occurrences. of IfcBeamStandardCase for this +type.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcBeamType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcBeamType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcBeamType and those that are only assignable to +IfcBeam. If the same property is assigned to the +IfcBeamType and the IfcBeam being an occurrence of +the IfcBeamType, then the occurrence property overrides +the type property.
+ +

Profile Use Definition:

+

The shared profile definition is defined by assigning an +IfcMaterialProfileSet (see material use definition above). +The IfcMaterialProfile refers to the subtype of +IfcProfileDef that is the common profile for all beam +occurrence, if used. It is only applicable if the +IfcBeamType has only occurrences of type +IfcBeamStandardCase (see definition of +IfcBeamStandardCase for further information).

+
NOTE The attribute ProfileName of the +IfcProfileDef subtype, referenced in +IfcMaterialProfile should contain a standardized profile +name according to local standards. However, an additional +geometric representation of the profile is necessary (e.g. as +IfcExtrudedAreaSolid). An importing application is allowed +to check for the existence of the profile name: in case of +identifying it as a standardized name, the corresponding profile +geometry and possibly other cross sectional properties can be +read from a library. Otherwise the geometric representation and +possible non geometric IfcProfileProperties have to be +used.
+

Geometry Use Definition:

+

The IfcBeamType may define the shared geometric +representation for all beam occurrences. The +RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'Axis', or 'Body'). It +is only applicable if the IfcBeamType has only occurrences +of type IfcBeam (See geometric use definition of +IfcBeam for further information).

+
NOTE If the IfcBeamType has an +associated IfcMaterialProfileSet, then no shared geometric +representation shall be provided.
+
NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
+
NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcBeam and +IfcBeamStandardCase
+
" +1574;IfcColumnType;" +

Definition from IAI: The element type +IfcColumnType defines commonly shared information for +occurrences of columns. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common profile definitions
  • +
  • common shape representations
  • +
+

It is used to define a column specification, or column style +(i.e. the specific product information that is common to all +occurrences of that column type). Column types may be exchanged +without being already assigned to occurrences.

+

Occurrences of the IfcColumnType within building models +are represented by instances of IfcColumnStandardCase if +the IfcColumnType has a single associated +IfcMaterialProfileSet; otherwise they are represented by +instances of IfcColumn. Occurrences of the +IfcColumnType within structural analysis models are +represented by instances of IfcStructuralCurveMember, or +its applicable subtypes.

+
HISTORY New entity in +Release IFC2x Edition 2.
+

Material Use Definition

+

The material of the IfcColumnType is defined by the +IfcMaterialProfileSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcColumnType, if there is at +least one occurrences of IfcColumnStandardCase for this +type.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcColumnType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcColumnType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcColumnType and those that are only assignable to +IfcColumn. If the same property is assigned to the +IfcColumnType and the IfcColumn being an occurrence +of the IfcColumnType, then the occurrence property +overrides the type property.
+ +

Profile Use Definition:

+

The shared profile definition is defined by assigning an +IfcMaterialProfileSet (see material use definition above). +The IfcMaterialProfile refers to the subtype of +IfcProfileDef that is the common profile for all column +occurrence, if used. It is only applicable if the +IfcColumnType has only occurrences of type +IfcColumnStandardCase (see definition of +IfcColumnStandardCase for further information).

+
NOTE The attribute ProfileName of the +IfcProfileDef subtype, referenced in +IfcMaterialProfile should contain a standardized profile +name according to local standards. However, an additional +geometric representation of the profile is necessary (e.g. as +IfcExtrudedAreaSolid). An importing application is allowed +to check for the existence of the profile name: in case of +identifying it as a standardized name, the corresponding profile +geometry and possibly other cross sectional properties can be +read from a library. Otherwise the geometric representation and +possible non geometric IfcProfileProperties have to be +used.
+

Geometry Use Definition:

+

The IfcColumnType may define the shared geometric +representation for all column occurrences. The +RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'Axis', or 'Body'). It +is only applicable if the IfcColumnType has only +occurrences of type IfcColumn (See geometric use +definition of IfcColumn for further information).

+
NOTE If the IfcColumnType has an +associated IfcMaterialProfileSet, then no shared geometric +representation shall be provided.
+
NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
+
NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcColumn and +IfcColumnStandardCase
+
" +1577;IfcMemberType;" +

Definition from IAI: The element type +IfcMemberType defines commonly shared information for +occurrences of members. Members are predominately linear building +elements, often forming part of a structural system. The +orientation of the member (being horizontal, vertical or sloped) +is not relevant to its definition (in contrary to beam and +column). The set of shared information may include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common profile definitions
  • +
  • common shape representations
  • +
+

It is used to define a member specification, or member style +(i.e. the specific product information that is common to all +occurrences of that member type). Member types may be exchanged +without being already assigned to occurrences.

+

Occurrences of the IfcMemberType within building models +are represented by instances of IfcMemberStandardCase if +the IfcMemberType has a single associated +IfcMaterialProfileSet; otherwise they are represented by +instances of IfcMember. Occurrences of the +IfcMemberType within structural analysis models are +represented by instances of IfcStructuralCurveMember, or +its applicable subtypes.

+
HISTORY New entity in +Release IFC2x2 Addendum 1.
+

Material Use Definition

+

The material of the IfcMemberType is defined by the +IfcMaterialProfileSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcMemberType, if there is at +least one occurrences of IfcMemberStandardCase for this +type.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcMemberType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcMemberType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcMemberType and those that are only assignable to +IfcMember. If the same property is assigned to the +IfcMemberType and the IfcMember being an occurrence +of the IfcMemberType, then the occurrence property +overrides the type property.
+ +

Profile Use Definition:

+

The shared profile definition is defined by assigning an +IfcMaterialProfileSet (see material use definition above). +The IfcMaterialProfile refers to the subtype of +IfcProfileDef that is the common profile for all member +occurrence, if used. It is only applicable if the +IfcMemberType has only occurrences of type +IfcMemberStandardCase (see definition of +IfcMemberStandardCase for further information).

+
NOTE The attribute ProfileName of the +IfcProfileDef subtype, referenced in +IfcMaterialProfile should contain a standardized profile +name according to local standards. However, an additional +geometric representation of the profile is necessary (e.g. as +IfcExtrudedAreaSolid). An importing application is allowed +to check for the existence of the profile name: in case of +identifying it as a standardized name, the corresponding profile +geometry and possibly other cross sectional properties can be +read from a library. Otherwise the geometric representation and +possible non geometric IfcProfileProperties have to be +used.
+

Geometry Use Definition:

+

The IfcMemberType may define the shared geometric +representation for all member occurrences. The +RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'Axis', or 'Body'). It +is only applicable if the IfcMemberType has only +occurrences of type IfcMember (See geometric use +definition of IfcMember for further information).

+
NOTE If the IfcMemberType has an +associated IfcMaterialProfileSet, then no shared geometric +representation shall be provided.
+
NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
+
NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcMember and +IfcMemberStandardCase
+
" +1580;IfcCurtainWallType;" +

Definition from IAI: The element type (IfcCurtainWallType) +defines a list of commonly shared property set definitions of a curtain +wall element and an optional set of product representations. It is used +to define a curtain wall specification (i.e. the specific product +information, that is common to all occurrences of that product type).

+
+

NOTE: The product +representations are defined as representation maps (at the level of the +supertype IfcTypeProduct, which gets assigned by an +element occurrence instance through the IfcShapeRepresentation.Item[1] +being an IfcMappedItem.

+
+

A curtain wall type is used to define the common properties of +a certain type of curtain wall that may be applied to many instances of +that type to assign a specific style. Curtain wall types may be +exchanged without being already assigned to occurrences.

+

The occurrences of the IfcCurtainWallType +are represented by instances of IfcCurtainWall.

+
+

HISTORY +New entity in Release IFC2x Editon 3.

+
+
" +1583;IfcPlateType;" +

The element type IfcPlateType defines commonly shared +information for occurrences of plates. The set of shared +information may include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common material layer definitions
  • +
  • common shape representations
  • +
  • +
    NOTE It is illegal to share shape +representations as representation maps for occurrences of +IfcPlateStandardCase.
    +
  • +
+

It is used to define a plate specification (i.e. the specific +product information, that is common to all occurrences of that +product type). Plate types may be exchanged without being already +assigned to occurrences.

+
NOTE The product representations are defined as +representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element occurrence +instance through the IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
+

The occurrences of the IfcPlateType within building +models are represented by instances of IfcPlateStandardCase +if the IfcPlateType has a single associated +IfcMaterialLayerSet; otherwise they are represented by +instances of IfcPlate.

+
+

HISTORY  New +entity in Release IFC2x2.

+
+

Informal proposition:

+
    +
  1. The material assignment, if provided using the +IfcRelAssociatesMaterial relationship, shall not reference +the IfcMaterialLayerSetUsage.
  2. +
+

Material Use Definition

+

The material of the IfcPlateType is defined by the +IfcMaterialLayerSet or as fall back by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations relationship.

+
Note: It is illegal to assign an +IfcMaterial to an IfcPlateType, if there is at least +one occurrences of IfcPlateStandardCase for this +type.
+

Layer Set Use Definition:

+

The shared material layer set definition is defined by assigning +an IfcMaterialLayerSet (see material use definition above). +The IfcMaterialLayer refers to one or several of +IfcMaterial that is the common for all plate occurrence, if +used. It is only applicable if the IfcPlateType has only +occurrences of type IfcPlateStandardCase (see definition of +IfcPlateStandardCase for further information).

+
NOTE Since each individual instance of +IfcPlateStandardCase defines its own +IfcMaterialLayerSetUsage including the offset from the +reference plane, the same IfcPlateType can be used +independently of the reference plane alignment of its +occurrences.
+

Property Set Use Definition:

+

The shared property sets relating to the IfcPlateType are +defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcWallType are part of this IFC +release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcPlateType and those that are only assignable to +IfcPlate. If the same property is assigned to the +IfcPlateType and the IfcPlate being an occurrence of +the IfcPlateType, then the occurrence property overrides the +type property.
+ +
" +1586;IfcStairType;" +

+ Definition from IAI: The element type + IfcStairType defines a list of commonly shared + property set definitions of a stair and an optional set of + product representations. It is used to define a stair + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

+
+ NOTE The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +
+

+ An IfcStairTypeÿis used to define the common + properties of a specific stair that may be applied to many + instances of that type to assign a specific style. + Building element types (or the instantiable subtypes) + may be exchanged without being + already assigned to occurrences. +

+

+ The IfcStairType can have common material (using the + inverse relationship HasAssociations) or property + set information (using HasPropertySets) assigned. If + present, it does apply equally to all occurrences of the + IfcStairType. Property set information may be + overridden at the occurrence. +

+

+ The occurrences of the IfcStairType are represented + by instances of IfcStair. +

+
+ HISTORY New entity in Release + IFC2x Edition 4. +
+ +
" +1589;IfcRampType;" +

+ Definition from IAI: The element type + IfcRampType defines a list of commonly shared + property set definitions of a ramp and an optional set of + product representations. It is used to define a ramp + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

+
+ NOTE The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +
+

+ An IfcRampTypeÿis used to define the common + properties of a specific ramp that may be applied to many + instances of that type to assign a specific style. + Building element types (or the instantiable subtypes) + may be exchanged without being + already assigned to occurrences. +

+

+ The IfcRampType can have common material (using the + inverse relationship HasAssociations) or property + set information (using HasPropertySets) assigned. If + present, it does apply equally to all occurrences of the + IfcRampType. Property set information may be + overridden at the occurrence. +

+

+ The occurrences of the IfcRampType are represented + by instances of IfcRamp. +

+
+ HISTORY New entity in Release + IFC2x Edition 4. +
+
" +1592;IfcRoofType;" +

+ Definition from IAI: The element type + IfcRoofType defines a list of commonly shared + property set definitions of a roof and an optional set of + product representations. It is used to define a roof + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

+
+ NOTE The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +
+

+ An IfcRoofTypeÿis used to define the common + properties of a specific roof that may be applied to many + instances of that type to assign a specific style. Building + element types (or the instantiable subtypes) may be + exchanged without being already assigned to occurrences. +

+

+ The IfcRoofType can have common material (using the + inverse relationship HasAssociations) or property + set information (using HasPropertySets) assigned. If + present, it does apply equally to all occurrences of the + IfcRoofType. Property set information may be + overridden at the occurrence. +

+

+ The occurrences of the IfcRoofType are represented + by instances of IfcRoof. +

+
+ HISTORY New entity in Release + IFC2x Edition 4. +
+
" +1595;IfcChimneyType;" +

+ Definition from IAI: The IfcChimneyType + defines a list of commonly shared property set definitions + of a chimney element and an optional set of product + representations. It is used to define a chimney + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

+
+ NOTE: The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +
+

+ A chimney type is used to define the common properties of a + certain type of chimney that may be applied to many + instances of that type to assign a specific style. Chimney + types may be exchanged without being already assigned to + occurrences. +

+

+ The occurrences of the IfcChimneyType are + represented by instances of IfcChimney. +

+
+ HISTORY New entity in Release + IFC2x4. +
+
" +1598;IfcBuildingElementProxyType;" +

+ Definition from IAI: + TheÿIfcBuildingElementProxyType defines a list of + commonly shared property set definitions of a building + element proxy and an optional set of product + representations. It is used to define an element + specification (i.e. the specific product information, that + is common to all occurrences of that product type). +

+
+

+ NOTEÿ The product representations are defined as + representation maps (at the level of the supertype + IfcTypeProduct, which gets assigned by an element + occurrence instance through the + IfcShapeRepresentation.Item[1] being an + IfcMappedItem. +

+
+

+ A building element proxy type is used to define the common + properties of a certain type of a building element proxy + that may be applied to many instances of thatÿtype to + assign a specific style. Building element proxy typesÿmay + be exchanged without being already assigned to occurrences. +

+
+

NOTE Although an building element proxy does not have + a predefined ontological meaning the provision of a type may be + helpful in sharing information among multiple occurrences. Applications + that provide type information for element types not yet included in the + current IFC specification can use the IfcBuildingElementProxyType + to exchange such types.

+
+

+ The occurrences of the IfcBuildingElementProxyType + are represented by instances of + IfcBuildingElementProxy. +

+
+

+ HISTORYÿ New entity in + Release IFC2x Edition 3. +

+
+
" +1600;IfcCoveringType;" +

Definition from IAI: The element type +IfcCoveringType defines commonly shared information for +occurrences of coverings. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material (layer set) information
  • +
  • common shape representations
  • +
+

It is used to define an covering specification or covering +style (i.e. the specific product information, that is common to +all occurrences of that product type). Covering types may be +exchanged without being already assigned to occurrences.

+

The occurrences of the IfcCoveringType are represented +by instances of IfcCovering

+
+

HISTORY New entity in Release +IFC2x Edition 2.

+
+

Informal proposition

+
    +
  1. The material assignment, if provided using the +IfcRelAssociatesMaterial relationship, shall not reference +the IfcMaterialLayerSetUsage.
  2. +
+

Material Use Definition

+

The material of the IfcCoveringType is defined by the +IfcMaterialLayerSet or as fall back by IfcMaterial +and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+

Property Set Use Definition:

+

The shared property sets relating to the +IfcCoveringType are defined by the IfcPropertySet +and are attached by the HasPropertySets attribute. The +following property set definitions specific to the +IfcCoveringType are part of this IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcCoveringType and those that are only assignable to +IfcCovering. If the same property is assigned to the +IfcCoveringType and the IfcCovering being an +occurrence of the IfcCoveringType, then the occurrence +property overrides the type property.
+
    +
  • Pset_CoveringCommon: common property set for all +covering types +
      +
    • Pset_CoveringCeiling: specific property set +for all occurrences of covering types with the PredefinedType: +CEILING
    • +
    • Pset_CoveringFlooring: specific property set +for all occurrences of coverings with the PredefinedType: +FLOORING
    • +
    +
  • +
+

Geometry Use Definition:

+

The IfcCoveringType may define the shared geometric +representation for all covering occurrences. The +RepresentationMaps attribute refers to a list of +IfcRepresentationMap's, that allow for multiple geometric +representations (e.g. with IfcShaperepresentation's having +an RepresentationIdentifier 'Box', 'Surface', or 'Body'). +(See geometric use definition of IfcCovering for further +information).

+
NOTE If the IfcCoveringType has an +associated IfcMaterialLayerSet, then no shared geometric +representation shall be provided.
+
NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
+
NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcCoveringType.
+
" +1603;IfcDoorType;" +

Definition from IAI: The element type +IfcDoorType defines commonly shared information +for occurrences of doors. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common operation type definitions
  • +
  • common shape representations
  • +
+

A door type defines the particular parameter of the lining and +one (or several) panels through the +IfcDoorLiningProperties and the +IfcDoorPanelProperties as predefined property sets +applicable to doors only.

+

It is used to define a door specification, or door style (i.e. +the specific product information that is common to all +occurrences of that door type). Door types may be exchanged +without being already assigned to occurrences.

+
NOTE The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
+

Occurrences of the IfcDoorType within building models +are represented by instances of IfcDoor or +IfcDoorStandardCase.

+
HISTORY New entity in +IFC2x4 .
+NOTE The entity IfcDoorType +replaces the previous definition IfcDoorStyle (which is +deprecated in IFC2x4).
+

Operation type use definition

+

The IfcDoorTypeOperationEnum defines the general layout +of the door type and its symbolic presentation. Depending on the +enumerator, the appropriate instances of +IfcDoorLiningProperties and IfcDoorPanelProperties +are attached in the list of HasPropertySets. The +IfcDoorTypeOperationEnum mainly determines the hinge side +(left hung, or right hung), the operation (swinging, sliding, +folding, etc.) and the number of panels.

+
Note ÿThere are different definitions in +various countries on what a left opening or left hung or left +swing door is (same for right). Therefore the IFC definition may +derivate from the local standard and may need to be mapped +appropriately.
+

See geometry use definitions at +IfcDoorTypeOperationEnum for the correct usage of opening +symbols for different operation types.

+

Material Use Definition

+

The material of the IfcDoorType is defined by the +IfcMaterialConstituentSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+

The following keywords for +IfcMaterialConstituentSet.MaterialConstituents[n].Name +shall be used:

+
    +
  • 'Lining' - to indicate that the material constituent applies +to to the door lining
  • +
  • 'Framing' - to indicate that the material constituent applies +to to the door framing, if not provided, the 'Lining' material +information applied to frams as well
  • +
  • 'Glazing' - to indicate that the material constituent applies +to to the glazing as well
  • +
+

If the fall back single IfcMaterial is referenced, it +applies to the lining and framing of the door.

+

Property Set Use Definition:

+

The shared property sets relating to the IfcDoorType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcDoorType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcDoorType and those that are only assignable to +IfcDoor. If the same property is assigned to the +IfcDoorType and the IfcDoor being an occurrence of +the IfcDoorType, then the occurrence property overrides +the type property.
+ +

Two subtypes of IfcPreDefinedPropertySet are applicable +to IfcDoorType:

+
    +
  • IfcDoorLiningProperties - a single instance to define +the shape parameters of the door lining
  • +
  • IfcDoorPanelProperties - one or several instances to +define the shape parameters of the door panel(s)
  • +
+

Geometry Use Definitions:

+

The IfcDoorType may define the common shape of door +occurrences. The common shape can be defined by

+
    +
  • applying shape parameters defined within the associated +IfcDoorLiningProperties and IfcDoorPanelProperties +applied to the 'Profile' geometric representation. It is only +applicable if the IfcDoorType has only occurrences of type +IfcDoorStandardCase (See geometric use definition of +IfcDoorStandardCase for further information).
  • +
  • applying the RepresentationMaps attribute to refer to +a list of IfcRepresentationMap's, that allow for multiple +geometric representations (e.g. with +IfcShapeRepresentation's having an +RepresentationIdentifier 'Box', 'Profile', 'FootPrint', or +'Body') +
    NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
    +
    NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcDoor and +IfcDoorStandardCase
    +
  • +
+
" +1606;IfcWindowType;" +

Definition from IAI: The element type +IfcWindowType defines commonly shared information for +occurrences of windows. The set of shared information may +include:

+
    +
  • common properties within shared property sets
  • +
  • common material information
  • +
  • common partitioning of panels
  • +
  • common operation types of panels
  • +
  • common shape representations
  • +
+

A window type defines the particular parameter of the lining +and one (or several) panels through the +IfcWindowLiningProperties and the +IfcWindowPanelProperties as predefined property sets +applicable to windows only.

+

It is used to define a window specification, or window style +(i.e. the specific product information that is common to all +occurrences of that window type). Window types may be exchanged +without being already assigned to occurrences.

+

Occurrences of the IfcWindowType within building models +are represented by instances of IfcWindow or +IfcWindowStandardCase.

+
HISTORY New entity in +IFC2x4 .
+NOTE The entity IfcWindowType +replaces the previous definition IfcWindowStyle (which is +deprecated in IFC2x4).
+

Partitioning type use definition

+

The IfcWindowTypePartitioningEnum defines the general +layout of the window type and its symbolic presentation. +Depending on the enumerator, the appropriate instances of +IfcWindowLiningProperties and +IfcWindowPanelProperties are attached in the list of +HasPropertySets. The IfcWindowTypePartitioningEnum +mainly determines the way of partitioning the window into +individual window panels and thereby number and position of +window panels.

+

See geometry use definitions at +IfcWindowTypePartitioningEnum for the correct usage of +panel partitioning and IfcWindowPanelProperties for the +opening symbols for different panel operation types.

+

Material Use Definition

+

The material of the IfcWindowType is defined by the +IfcMaterialConstituentSet or as fall back by +IfcMaterial and attached by the +IfcRelAssociatesMaterial.RelatingMaterial. It is +accessible by the inverse HasAssociations +relationship.

+

The following keywords for +IfcMaterialConstituentSet.MaterialConstituents[n].Name +shall be used:

+
    +
  • 'Lining' - to indicate that the material constituent applies +to to the window lining
  • +
  • 'Framing' - to indicate that the material constituent applies +to to the window panels, if not provided, the 'Lining' material +information applied to panels as well
  • +
  • 'Glazing' - to indicate that the material constituent applies +to to the glazing part
  • +
+

If the fall back single IfcMaterial is referenced, it +applies to the lining and framing of the window.

+

Property Set Use Definition:

+

The shared property sets relating to the IfcWindowType +are defined by the IfcPropertySet and are attached by the +HasPropertySets attribute. The following property set +definitions specific to the IfcWindowType are part of this +IFC release:

+
NOTE There is no differentiation between +properties within the property set that are only assignable to +IfcWindowType and those that are only assignable to +IfcWindow. If the same property is assigned to the +IfcWindowType and the IfcWindow being an occurrence +of the IfcWindowType, then the occurrence property +overrides the type property.
+ +

Two subtypes of IfcPreDefinedPropertySet are applicable +to IfcWindowType:

+
    +
  • IfcWindowLiningProperties - a single instance to +define the shape parameters of the window lining
  • +
  • IfcWindowPanelProperties - one or several instances to +define the shape parameters of the window panel(s)
  • +
+

Geometry Use Definitions:

+

The IfcWindowType may define the common shape of window +occurrences. The common shape can be defined by

+
    +
  • applying shape parameters defined within the associated +IfcWindowLiningProperties and +IfcWindowPanelProperties applied to the 'Profile' +geometric representation. It is only applicable if the +IfcWindowType has only occurrences of type +IfcWindowStandardCase (See geometric use definition of +IfcWindowStandardCase for further information).
  • +
  • applying the RepresentationMaps attribute to refer to +a list of IfcRepresentationMap's, that allow for multiple +geometric representations (e.g. with +IfcShapeRepresentation's having an +RepresentationIdentifier 'Box', 'Profile', 'FootPrint', or +'Body') +
    NOTE The product shape representations are +defined as RepresentationMaps (attribute of the supertype +IfcTypeProduct), which get assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[n] being an +IfcMappedItem. See IfcTypeProduct for further +information.
    +
    NOTE The values of attributes +RepresentationIdentifier and RepresentationType of +IfcShapeRepresentation are restricted in the same way as +those for IfcWindow and +IfcWindowStandardCase
    +
  • +
+
" +1609;IfcShadingDeviceType;" +

Definition from IAI: The IfcShadingDeviceType +defines a list of commonly shared property set definitions of a +shading device element and an optional set of product +representations. It is used to define a shading device +specification (i.e. the specific product information, that is +common to all occurrences of that product type).

+
NOTE: The product representations are defined +as representation maps (at the level of the supertype +IfcTypeProduct, which gets assigned by an element +occurrence instance through the +IfcShapeRepresentation.Item[1] being an +IfcMappedItem.
+

A shading device type is used to define the common properties +of a certain type of chimney that may be applied to many +instances of that type to assign a specific style. Shading device +types may be exchanged without being already assigned to +occurrences.

+

The occurrences of the IfcShadingDeviceType are +represented by instances of IfcShadingDevice.

+
HISTORY New entity in +Release IFC2x4.
+
" +1611;IfcBuildingSystem;" +

Definition from IAI: A building system is a +group by which building elements are group according to a common +function within the building.

+
HISTORY: New entity in +IFC 2x4.
+

The group IfcBuildingSystem defines the occurrence of a +specialized system for use within the context of a building and +finishing fabric. Important functionalities for the description +of a building system are derived from supertypes:

+
    +
  • From IfcSystem it inherits the ability to couple the +building system via IfcRelServicesBuildings to one or more +IfcSpatialElement subtypes as necessary.
  • +
+
    +
  • From IfcGroup it inherits the inverse attribute +IsGroupedBy, pointing to the relationship class +IfcRelAssignsToGroup. This allows to group building +elements (instances of IfcBuildingElement subtypes, +IfcFurnishingElement subtype, IfcElementAssembly +and IfcTransportElement, ).
  • +
+
    +
  • From IfcObjectDefinition it inherits the inverse +attribute IsDecomposedBy pointing to the relationship +class IfcRelAggregates. It provides the hierarchy between +the separate (partial) building systems.
  • +
+

Property Set Use Definition:

+

The property sets relating to this entity are defined by the +IfcPropertySet and attached by the +IfcRelDefinesByProperties relationship. It is accessible +by the inverse IsDefinedBy relationship. The following +property set definitions specific to this entity are part of this +IFC release:

+ + +
" +1621;IfcAsset;" + +

An asset is a uniquely identifiable grouping of elements acting as a single entity that has a financial value or that can be operated on as a single unit.

+ +

An asset is generally the level of granularity at which maintenance operations are undertaken. An asset is a group that can contain one or more elements. Whilst the financial value of a component or element can be defined, financial value is also defined for accounting purposes at the level of the asset.

There are a number of actors that can be associated with an asset, each actor having a role. Actors within the scope of the project are indicated using the IfcRelAssignsToActor relationship in which case roles should be defined through the IfcActorRole class; otherwise principal actors are identified as attributes of the class. In the existence of both, direct attributes take precedence.

There are a number of costs that can be associated with an asset, each cost having a role. These are specified through the OriginalValue, CurrentValue, TotalReplacementCost and DepreciatedValue attributes.

+ +
HISTORY: New entity in IFC2x. In IFC2x4, all attributes made optional and date values changed to use IfcDate.
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Refer to the documentation at the supertype IfcGroup and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Classification Use Definition

+

Classifications may be applied using IfcRelAssociatesClassification where RelatedObjects contains the IfcAsset and RelatingClassification refers to an IfcClassification or IfcClassificationReference.

+
    +
  • IfcClassificationReference: The operating function of an asset within an organization may be particularly valuable in situations where one organization provides and maintains core services and another organization adds and maintains terminal services. It can classify who owns and is responsible for the asset. Operating function can be designated through the use of one or more classification references.
  • +
+

Assignment Use Definition

+

The IfcAsset may be assigned to the following entities using relationships as indicated:

+ +

The IfcAsset may have assignments of its own using the IfcRelAssignsToGroup relationship where RelatingGroup refers to the IfcAsset and RelatedObjects contains one or more objects of the following types:

    +
  • IfcElement: Physical elements that comprise the asset. +
  • +
+ +
" +1631;IfcInventory;" + +

An inventory is a list of items within an enterprise.

+ +

Various types of inventory can be included. These are identified by the range of values within the inventory type enumeration which includes space, asset, and furniture. User defined inventories can also be defined for lists of particular types of element such as may be required in operating and maintenance instructions. Such inventories should be constrained to contain a list of elements of a restricted type.

There are a number of actors that can be associated with an inventory, each actor having a role. Actors within the scope of the project are indicated using the IfcRelAssignsToActor relationship in which case roles should be defined through the IfcActorRole class; otherwise principal actors are identified as attributes of the class. In the existence of both, direct attributes take precedence.

There are a number of costs that can be associated with an inventory, each cost having a role. These are specified through the CurrentValue and OriginalValue attributes.

HISTORY: New entity in IFC2.0. Modified in IFC2x4 to make all attributes optional and remove Where Rule.
+ +

Assignment Use Definition

+

The IfcInventory may have assignments of its own using the IfcRelAssignsToGroup relationship where RelatingGroup refers to the IfcInventory and RelatedObjects contains one or more objects of the following types:

    +
  • IfcAsset: Assets included in the inventory. +
  • +
  • IfcElement: Elements such as furniture included in the inventory. +
  • +
  • IfcSpace: Spaces included in the inventory. +
  • +
+ +
" +1644;IfcOccupant;" + +

An occupant is a type of actor that defines the form of occupancy of a property.

+ +

The principal purpose of IfcOccupant is to determine the nature of occupancy of a property for a particular actor. All characteristics relating to the actor (name and organization details) are inherited from the IfcActor class.

HISTORY: New entity in IFC2x
+ +

Assignment Use Definition

+

The IfcOccupant may have assignments of its own using the IfcRelAssignsToActor relationship where RelatingActor refers to the IfcOccupant and RelatedObjects contains one or more objects of the following types:

    +
  • IfcSpatialStructureElement: Indicates the property to be occupied. Particular details of the agreement relating to the occupancy of a property are dealt within the Pset_PropertyAgreement that is defined for the instance of IfcSpatialStructureElement. This means that an occupant may be related to a site, building, building storey or space through the IfcSpatialStructureElement.ElementComposition attribute. For instance, if the property concerned is several office spaces on a building storey, it might be appropriate to reference IfcBuildingStorey.ElementComposition=PARTIAL. Occupants of a property may be considered to be the parties to an agreement. The roles that the occupant may play in respect to an agreement are defined in the IfcOccupantTypeEnum enumeration. If the role is not specified by the predefined contents of this enumeration, the value USERDEFINED may be set and the ObjectType attribute asserted. +
  • +
+ +
" +1657;IfcSystemFurnitureElement;" + +

A system furniture element defines components of modular furniture which are not directly placed in a building structure but aggregated inside furniture.

+ +
HISTORY: New entity in IFC2x2
+ +

Type Use Definition

+

IfcSystemFurnitureElement defines the occurrence of any furniture element; common information about furniture element types is handled by IfcSystemFurnitureElementType. The IfcSystemFurnitureElementType (if present) may establish the common type name, usage (predefined type), properties, materials, composition, assignments, and representations. The IfcSystemFurnitureElementType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. If the IfcSystemFurnitureElementType has aggregated elements, such objects are reflected at the IfcSystemFurnitureElement occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Property sets may also be specified at the IfcSystemFurnitureElementType, defining the common property data for all occurrences of the same type. They are then accessible by the IsTypedBy inverse attribute pointing to IfcSystemFurnitureElementType.HasPropertySets. If both are given, then the properties directly defined at IfcSystemFurnitureElement override the properties defined at IfcSystemFurnitureElementType. Refer to the documentation at the supertype IfcFurnishingElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSystemFurnitureElement is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSystemFurnitureElementType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Finish': The finish, typically at visible aspects of the furniture.
  • +
  • 'Frame': The frame from which the object is constructed.
  • +
  • 'Hardware': Finish hardware such as knobs or handles.
  • +
  • 'Padding': Padding such as cushions.
  • +
  • 'Panel': Panels such as glass.
  • +
+ +
" +1666;IfcFurniture;" + +

Furniture defines complete furnishings such as a table, desk, chair, or cabinet, which may or may not be permanently attached to a building structure.

+ +

Occurrences of furniture that are built in (where the property Pset_FurnitureTypeCommon.IsBuiltIn is asserted to be TRUE) should have their connection relationship with a building element occurrence defined through the IfcRelConnectsElements relationship.

HISTORY: New entity in IFC2x2
+ +

Type Use Definition

+

IfcFurniture defines the occurrence of any furniture; common information about furniture types is handled by IfcFurnitureType. The IfcFurnitureType (if present) may establish the common type name, usage (predefined type), properties, materials, composition, assignments, and representations. The IfcFurnitureType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. If the IfcFurnitureType has aggregated elements, such objects are reflected at the IfcFurniture occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Property sets may also be specified at the IfcFurnitureType, defining the common property data for all occurrences of the same type. They are then accessible by the IsTypedBy inverse attribute pointing to IfcFurnitureType.HasPropertySets. If both are given, then the properties directly defined at IfcFurniture override the properties defined at IfcFurnitureType. Refer to the documentation at the supertype IfcFurnishingElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFurniture is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFurnitureType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Finish': The finish, typically at visible aspects of the furniture.
  • +
  • 'Frame': The frame from which the object is constructed.
  • +
  • 'Hardware': Finish hardware such as knobs or handles.
  • +
  • 'Padding': Padding such as cushions.
  • +
  • 'Panel': Panels such as glass.
  • +
+ +

Composition Use Definition

+

The IfcFurniture may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcFurniture and RelatedObjects contains one or more components. Composition use is defined for the following predefined types: +

+ +
" +1680;IfcSystemFurnitureElementType;" + +

The furnishing element type IfcSystemFurnitureElementType defines commonly shared information for occurrences of furniture elements. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • applicable assignment of process types
  • +
+

It is used to define a furniture element specification (i.e. the specific product information, that is common to all occurrences of that product type). Furniture Element types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSystemFurnitureElementType are represented by instances of IfcSystemFurnitureElement.

+

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFurnishingElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSystemFurnitureElementType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Finish': The finish, typically at visible aspects of the furniture.
  • +
  • 'Frame': The frame from which the object is constructed.
  • +
  • 'Hardware': Finish hardware such as knobs or handles.
  • +
  • 'Padding': Padding such as cushions.
  • +
  • 'Panel': Panels such as glass.
  • +
+ +
" +1683;IfcFurnitureType;" + +

The furnishing element type IfcFurnitureType defines commonly shared information for occurrences of furnitures. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • applicable assignment of process types
  • +
+

It is used to define a furniture specification (i.e. the specific product information, that is common to all occurrences of that product type). Furniture types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFurnitureType are represented by instances of IfcFurniture.

+

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFurnishingElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFurnitureType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Finish': The finish, typically at visible aspects of the furniture.
  • +
  • 'Frame': The frame from which the object is constructed.
  • +
  • 'Hardware': Finish hardware such as knobs or handles.
  • +
  • 'Padding': Padding such as cushions.
  • +
  • 'Panel': Panels such as glass.
  • +
+ +

Composition Use Definition

+

The IfcFurnitureType may be decomposed into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcFurnitureType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Composition use is defined for the following predefined types: +

+ +
" +1688;IfcDoorStyle;" + +

Definition: The door style, IfcDoorStyle, defines a particular style of doors, which may be included into the spatial context of the building model through instances of IfcDoor. A door style defines the overall parameter of the door style and refers to the particular parameter of the lining and one (or several) panels through the IfcDoorLiningProperties and the IfcDoorPanelProperties.

+ +

The door entity, IfcDoor, defines a particular occurrence of a door inserted in the spatial context of a +project. The actual parameter of the door and/or its shape is defined at the IfcDoorStyle, to which the IfcDoor +is related by the inverse relationship IsDefinedBy pointing to IfcRelDefinedByType. The IfcDoorStyle +also defines the particular attributes for the lining, IfcDoorLiningProperties, and panels, IfcDoorPanelProperties.

+ +
+HISTORYÿNew entity in IFC Release 2x. +
+
+IFC2x4 CHANGE The entity is deprecated and shall not be used. The new entity +IfcDoorType shall be used instead. +
+ +

Geometry use definitions

+ +

The IfcDoorStyle defines the baseline geometry, or the representation map, for all occurrences of the door style, given +by the IfcDoor, pointing to this style. The representation of the door style may be given by the agreed set of minimal +parameters, defined for the door lining and the door panel(s), or it may be given by a geometric representation used by the +IfcRepresentationMap. The attribute ParameterTakesPrecedence decides, whether the set of parameters can be used to exactly represent the shape of the door style (TRUE), or whether the attached IfcRepresentationMap +holds the exact representation (FALSE).

+ +

The IfcDoorStyleOperationTypeEnum defines the general layout of the door style. Depending on the enumerator, the +appropriate instances of IfcDoorLiningProperties and IfcDoorPanelProperties are attached in the list of +HasPropertySets. The IfcDoorStyleOperationTypeEnum mainly determines the hinge side (left hung, or right hung), the +operation (swinging, sliding, folding, etc.)ÿand the number of panels.

+ +

See geometry use definitions at IfcDoorStyleOperationTypeEnum for the correct usage of opening symbols for different operation types.

+ +
" +1722;IfcWindowStyle;" + +

Definition: The window style defines a particular style of windows, which may be included into the spatial context of the building model through instances of IfcWindow. A window style defines the overall parameter of the window style and refers to the particular parameter of the lining and one (or several) panels through IfcWindowLiningProperties and IfcWindowPanelProperties.

+ +

The window entity (IfcWindow) defines a particular occurrence of a window inserted in the spatial context of a project. The actual parameter of the window and/or its shape is defined at the IfcWindowStyle, to which the IfcWindow related by the inverse relationship IsDefinedBy pointing to IfcRelDefinesByType. The IfcWindowStyle also defines the particular attributes for the lining (IfcWindowLiningProperties) and panels (IfcWindowPanelProperties).

+ +
+HISTORY New entity in IFC Release 2x. +
+
+IFC2x4 CHANGE The entity has been deprecated and shall not be used. The new entity IfcWindowType shall be used instead. +
+ +

Geometry use definitions

+

The IfcWindowStyle defines the baseline geometry, or the representation map, for all occurrences of the window style, +given by the IfcWindow, pointing to this style. The representation of the window style may be given by the agreed set +of minimal parameters, defined for the window lining and the window panel(s), or it may be given by a geometric representation +used by the IfcRepresentationMap. The attribute ParameterTakesPrecedence decides, whether the set of +parameters can be used to exactly represent the shape of the window style (TRUE), or whether the attached IfcRepresentationMap holds the exact representation (FALSE).

+ +

The IfcWindowStyleOperationTypeEnum defines the general layout of the window style. Depending on the enumerator, the +appropriate instances of IfcWindowLiningProperties and IfcWindowPanelProperties are attached in the list of +HasPropertySets. See geometry use definitions there.

+ +
" +1748;IfcDoorLiningProperties;" +

The door lining is the frame which +enables the door leaf to be fixed in position. The door lining is +used to hang the door leaf. The parameters of the door lining +(IfcDoorLiningProperties) define the geometrically +relevant parameter of the lining.

+ +
+NOTEÿ The IfcDoorLiningProperties +shall only be applied to construct the 3D shape of a door, if the +attribute IfcDoorStyle.ParameterTakesPrecedence is set +TRUE. +
+ +

The IfcDoorLiningProperties are included in the list of +properties of IfcDoorStyle.HasPropertySets. More +information about the door lining can be included in the same +list of the IfcDoorStyle using another +IfcPropertySet for dynamic extensions.

+ +
+HISTORY New entity in IFC Release 2.0. Has been renamed from IfcDoorLining in IFC Release 2x. +
+
+IFC2x4 CHANGEÿ The following attributes have been added LiningToPanelOffsetX, LiningToPanelOffsetY. The attribute ShapeAspectStyle is deprecated and shall no longer be used. Supertype changed to new IfcPreDefinedPropertySet. +
+ +

Geometry use definitions

+

The IfcDoorLiningProperties does not hold its own +geometric representation. However it defines parameters which can +be used to create the shape of the door style (which is inserted +by the IfcDoor into the spatial context of the +project) as shown in Figure 172.

+

The parameters of the IfcDoorLiningProperties define a +standard door lining, including (if given) a threshold and a +transom. The outer boundary of the lining is determined by the +occurrence parameter assigned to the IfcDoor, which +inserts the IfcDoorStyle.

+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + +
The lining is applied to the left, +right and upper side of the opening reveal. The parameters are: +
    +
  • LiningDepth, if omited, equal to +wall thickness - this only takes effect if a value for +LiningThickness is given. If both parameters are not +given, then there is no lining.
  • +
  • LiningThickness
  • +
  • LiningToPanelOffsetX
  • +
  • LiningToPanelOffsetY
  • +
  • +
    NOTE Parameters added in +IFC2x4.
    +
  • +
+
The lining can only cover part of +the opening reveal. +
    +
  • LiningOffset : given if lining edge has an offset to +the x axis of the local placement.
  • +
+
NOTE ÿIn addition to theÿLiningOffset, +the local placement of the IfcDoor can already have an +offset to the wall edge and thereby shift the lining along the y +axis. The actual position of the lining is calculated from the +origin of the local placement along the positive y axis with the +distance given by LiningOffset.
+
The lining may include a casing, +which covers part of the wall faces around the opening. The +casing covers the left, right and upper side of the lining on +both sides of the wall. The parameters are: +
    +
  • CasingDepth
  • +
  • CasingThickness
  • +
+
The lining may include a threshold, +which covers the bottom side of the opening. The parameters are: +
    +
  • ThresholdDepth +if omited, equal to wall thickness - this +only takes effect if a value for ThresholdThickness is +given. If both parameters are not given, then there is no +threshold.
  • +
  • ThresholdThickness
  • +
  • ThresholdOffset (not shown in figure): given, if the +threshold edge has an offset to the x axis of the local +placement.
  • +
+
The lining may have a transom which +separates the door panel from a window panel. The transom, if +given, is defined by: +
    +
  • TransomOffset : a parallel edge to the x axis of the +local placement
  • +
  • TransomThickness
  • +
+

The depth of the transom is identical to the depth of the +lining and not given as separate parameter.

+
+

Figure 172 — Door lining properties

+ +
NOTE LiningDepth describes the length of the lining along the reveal of the door opening. It can be given by an absolute value if the door lining has a specific depth depending on the door style. However often it is equal to the wall thickness. If the same door style is used (like the same type of single swing door), but inserted into different walls with different thicknesses, it would be necessary to create a special door style for each wall thickness. Therefore several CAD systems allow to set the value to ""automatically aligned"" to wall thickness. This should be exchanged by leaving the optional attribute LiningDepth unassigned. The same agreement applies to ThresholdDepth. +
+ +
" +1767;IfcDoorPanelProperties;" +

A door panel is normally a door leaf that opens to allow people or +goods to pass. The parameters of the door panel define the +geometrically relevant parameter of the panel,

+ +

The IfcDoorPanelProperties are used to parametrically +describe the shape and operation of door panels. The parametric +definition can be added solely or additionally to the explicit +shape representation of the door.

+ +

The IfcDoorStyle can define doors consisting of more +then one panel. In this case, one instance of +IfcDoorPanelProperties has to be included for each door +panel. The PanelPosition attribute, in conjunction with +the IfcDoorStyle.OperationType attribute, determines to +which panel the IfcDoorPanelProperties apply.

+

The IfcDoorPanelProperties are included in the list of +properties , given by attribute HasPropertySets of the +IfcDoorStyle. More information about the door panel can be +included in the same list of the IfcDoorStyle using the +IfcPropertySet for dynamic extensions.

+ +
+HISTORYÿ New Entity in IFC Release 2.0. +
+
+IFC2x4 CHANGE Supertype changed to new IfcPreDefinedPropertySet. +
+ +

Geometry use definitions

+ +

The IfcDoorPanelProperties does not hold a geometric representation. However it defines parameters which can be used to create the shape of the door style (which is inserted by the IfcDoor into the spatial context of the project) as shown in Figure 173.

+

The parameters of the IfcDoorPanelProperties define a standard door panel, including (if given) a proportional width to define non-uniform double swing (or sliding, or folding) doors. The outer boundary of the panel is determined by the occurrence parameter assigned to the IfcDoor, which inserts the IfcDoorStyle. It has to take the lining parameter into account as well.

+ + + +
+ + + + + + + + + + + +
The depth of the panel (swinging, +double-acting, and sliding panels) is defined by the +PanelDepth parameter. +
    +
  • PanelDepth
  • +
+
For door operation types that +include more than one panel, the width of (at least) one panel is +given by a normalised ratio measure. It determines the width of +that panel, which is defined as a ratio of the overall width of +the door opening. +
    +
  • PanelWidth
  • +
+
+

Figure 173 — Door panel properties

+ +
" +1789;IfcWindowPanelProperties;" +

A window panel is a casement, that is, a component, fixed or opening, +consisting essentially of a frame and the infilling. The +infilling of a window panel is normally glazing. The way of +operation is defined in the operation type.

+

The IfcWindowPanelProperties are used to parametrically +describe the shape and operation of window panels. The parametric +definition can be added solely or additionally to the explicit +shape representation of the window.

+

The IfcWindowStyle can define windows consisting of +more then one panel. In this case, one instance of +IfcWindowPanelProperties has to be included for each +window panel. The PanelPosition attribute, in conjunction +with the IfcWindowStyle.OperationType attribute, +determines to which panel the IfcWindowPanelProperties +apply.

+

The IfcWindowPanelProperties are included in the list +of properties (HasPropertySets) of the +IfcWindowStyle. More information about the window panel +can be included in the same list of the IfcWindowStyle +using the IfcPropertySet for dynamic extensions.

+
+HISTORY New entity in +IFC Release 2.0, it had been renamed from IfcWindowPanel in IFC +Release 2x.
+
+IFC2x4 CHANGE Supertype changed to +new IfcPreDefinedPropertySet. +
+ +

Geometry use definitions

+

The IfcWindowPanelProperties does not hold an own +geometric representation. However it defines parameter, which can +be used to create the shape of the IfcWindowStyle (which +is inserted by the IfcWindow into the spatial context of +the project).

+

The parameters at the IfcWindowPanelProperties define a +standard window panel. The outer boundary of the panel is +determined by the occurrence parameter assigned to the IfcWindow, +which inserts the IfcWindowStyle. It has to take the lining +parameter into account as well. The position of the window panel +within the overall window is determined by the +PanelPosition attribute.

+ +

As shown in Figure 176, the panel is applied to the position within the lining as defined by the panel position attribute. The following parameter apply to that panel: FrameDepth, FrameThickness.

+ + + + + +

Figure 176 — Window panel properties

+ +
" +1817;IfcWindowLiningProperties;" +

The window lining is the outer +frame which enables the window to be fixed in position. The +window lining is used to hold the window panels or other +casements. The parameter of the IfcWindowLiningProperties +define the geometrically relevant parameter of the lining.

+ +
+NOTEÿ The IfcWindowLiningProperties +shall only be applied to construct the 3D shape of a window, if +the attribute IfcWindowStyle.ParameterTakesPrecedence is +set TRUE. +
+ +

The IfcWindowLiningProperties are included in the set +of properties of IfcWindowStyle.HasPropertySets. More +information about the window lining can be included in the same +set of the IfcWindowStyle using another +IfcPropertySet for dynamic extensions.

+ +
+HISTORY New Entity in IFC Release 2.0. Has been renamed from IfcWindowLining in +IFC Release 2x. +
+
+IFC2x4 CHANGEÿ The following attributes have been added LiningOffset, +LiningToPanelOffsetX, LiningToPanelOffsetY. The +attribute ShapeAspectStyle is deprecated and shall no +longer be used. Supertype changed to new +IfcPreDefinedPropertySet.
+ +

Geometry use definitions

+

The IfcWindowLiningProperties does not hold a geometric representation. However it defines parameters which can be used to create the shape of the window style (which is inserted by the IfcWindow into the spatial context of the project) as shown in Figure 175.

+

The parameters at the IfcWindowLiningProperties define a standard window lining, including (if given) a mullion and a transom (for horizontal and vertical splits). The outer boundary of the lining is determined by the occurrence parameter assigned to the IfcWindow, which inserts the IfcWindowStyle.

+ + + +
+ + + + + + + + + + + + + + + + + + + + + +
+""liningThe lining is applied to all faces +of the opening reveal. The parameter are: +
    +
  • LiningDepth
  • +
  • LiningThickness
  • +
  • LiningOffset
  • +
  • LiningToPanelOffsetX
  • +
  • LiningToPanelOffsetY
  • +
  • +
    NOTE Parameters added in +IFC2x4.
    +
  • +
+Inner side is defined as the direction of the window panel +opening operation.
+""liningIf the OperationType of the +window style is +
    +
  • DoublePanelVertical (shown)
  • +
  • TriplePanelBottom
  • +
  • TriplePanelTop
  • +
  • TriplePanelLeft
  • +
  • TriplePanelRight
  • +
+the following additional parameter apply: +
    +
  • MullionThickness
  • +
  • FirstMullionOffset - measured as offset to the Z axis +(in XZ plane)
  • +
+
+""liningIf the OperationType of the +window style is +
    +
  • DoublePanelHorizontal
  • +
  • TriplePanelBottom
  • +
  • TriplePanelTop
  • +
  • TriplePanelLeft
  • +
  • TriplePanelRight
  • +
+the following additional parameter apply +
    +
  • TransomThickness
  • +
  • FirstTransomOffset measured as offset to the X axis +(in XZ plane)
  • +
+
+""liningIf the OperationType of the +window style is +
    +
  • TriplePanelVertical
  • +
+the following additional parameter apply +
    +
  • SecondMullionOffset
  • +
+
+""liningIf the OperationType of the +window style is +
    +
  • TriplePanelHorizontal
  • +
+the following additional parameter apply +
    +
  • SecondTransomOffset
  • +
+
+

Figure 175 — Window lining properties

+ +

NOTE

+
    +
  1. All offsets are given as a normalized ratio measure.
  2. +
+ +
" +1834;IfcPermeableCoveringProperties;" + +

This entity is a description of a panel within a +door or window (as fillers for opening) which allows for air +flow. It is given by its properties +(IfcPermeableCoveringProperties). A permeable covering is +a casement, such as a component, fixed or opening, consisting +essentially of a frame and the infilling. The infilling is +normally a grill, a louver or a screen. The way of operation is +defined in the operation type.

+

The IfcPermeableCoveringProperties are included in the +list of properties (HasPropertySets) of the +IfcWindowStyle or the IfcDoorStyle. More +information about the permeable covering can be included in the +same list of the window or door style using the +IfcPropertySet for dynamic extensions. This particularly +applies for additional properties for the various operation +types

+ +
+HISTORY New entity in IFC Release 2.0, it had been renamed from +IfcPermeableCovering in IFC Release 2x. +
+
+IFC2x4 CHANGE Supertype changed to new IfcPreDefinedPropertySet. +
+ +

Geometry use definitions

+

The IfcPermeableCoveringProperties does not hold a geometric representation. However it defines parameters which can be used to create the shape of the IfcWindowStyle (which is inserted by the IfcWindow into the spatial context of the project), or of the IfcDoorStyle (which is inserted by the IfcDoor).

+

The parameters at the IfcPermeableCoveringProperties define a standard permeable covering. The outer boundary of the panel is determined by the occurrence parameter assigned to the +IfcWindow or IfcDoor. It has to take the lining parameter into account as well. The position of the permeable covering within the overall window or door is determined by the +PanelPosition attribute.

+ + +

As shown in Figure 174, the panel is applied to the position within the lining, as defined by the panel position attribute. The following parameters apply to that panel: FrameDepth, FrameThickness.

+ + + + +
+""covering""

Figure 174 — Permeable covering properties

+ +
" +1847;IfcFlowInstrument;"

A flow instrument reads and displays the value of a particular property of a system at a point, or displays the difference in the value of a property between two points.

+

Instrumentation is typically for the purpose of determining the value of the property at a point in time. It is not the purpose of an instrument to record or integrate the values over time (although they may be connected to recording devices that do perform such a function). This entity provides for all forms of mechanical flow instrument (thermometers, pressure gauges etc.) and electrical flow instruments (ammeters, voltmeters etc.)

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcFlowInstrument defines the occurrence of any flow instrument; common information about flow instrument types is handled by IfcFlowInstrumentType. +The IfcFlowInstrumentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcFlowInstrumentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcFlowInstrumentType has ports or aggregated elements, such objects are reflected at the IfcFlowInstrument occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcFlowInstrumentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcFlowInstrumentType.HasPropertySets. +If both are given, then the properties directly defined at IfcFlowInstrument override the properties defined at IfcFlowInstrumentType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcFlowInstrument is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFlowInstrumentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFlowInstrument are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the flow instrument occurrence is defined by IfcFlowInstrumentType, then the port occurrences must reflect those defined at the IfcFlowInstrumentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcFlowInstrument PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +1862;IfcActuator;"

An actuator is a mechanical device for moving or controlling a mechanism or system. An actuator takes energy, usually created by air, electricity, or liquid, and converts that into some kind of motion.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcActuator defines the occurrence of any actuator; common information about actuator types is handled by IfcActuatorType. +The IfcActuatorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcActuatorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcActuatorType has ports or aggregated elements, such objects are reflected at the IfcActuator occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcActuatorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcActuatorType.HasPropertySets. +If both are given, then the properties directly defined at IfcActuator override the properties defined at IfcActuatorType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcActuator is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcActuatorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Connection Use Definition

+

The IfcActuator may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcActuator are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the actuator occurrence is defined by IfcActuatorType, then the port occurrences must reflect those defined at the IfcActuatorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcActuator PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +1874;IfcController;"

A controller is a device that monitors inputs and controls outputs within a building automation system.

+

A controller may be physical (having placement within a spatial structure) or logical (a software interface or aggregated within a programmable physical controller).

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcController defines the occurrence of any controller; common information about controller types is handled by IfcControllerType. +The IfcControllerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcControllerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcControllerType has ports or aggregated elements, such objects are reflected at the IfcController occurrence using the IfcRelDefinesByObject relationship.

+

Figure 177 illustrates controller type use.

+

Figure 177 — Controller type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcControllerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcControllerType.HasPropertySets. +If both are given, then the properties directly defined at IfcController override the properties defined at IfcControllerType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Composition Use Definition

+

The IfcController may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcController and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • PROGRAMMABLE +
      +
    • May contain IfcController components. Programmable Logic Controllers may be decomposed into logical elements for values and operations.
    • +
    +
  • +
+ +

Material Use Definition

+

The material of the IfcController is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcControllerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcController are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the controller occurrence is defined by IfcControllerType, then the port occurrences must reflect those defined at the IfcControllerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcController PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 178 illustrates controller port use.

+

Figure 178 — Controller port use

+ + " +1886;IfcSensor;"

A sensor is a device that measures a physical quantity and converts it into a signal which can be read by an observer or by an instrument.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcSensor defines the occurrence of any sensor; common information about sensor types is handled by IfcSensorType. +The IfcSensorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcSensorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcSensorType has ports or aggregated elements, such objects are reflected at the IfcSensor occurrence using the IfcRelDefinesByObject relationship.

+

Figure 179 illustrates sensor type use.

+

Figure 179 — Sensor type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcSensorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcSensorType.HasPropertySets. +If both are given, then the properties directly defined at IfcSensor override the properties defined at IfcSensorType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcSensor is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSensorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Connection Use Definition

+

The IfcSensor may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcSensor are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the sensor occurrence is defined by IfcSensorType, then the port occurrences must reflect those defined at the IfcSensorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcSensor PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 180 illustrates sensor port use.

+

Figure 180 — Sensor port use

+ + " +1913;IfcAlarm;"

An alarm is a device that signals the existence of a condition or situation that is outside the boundaries of normal expectation or that activates such a device.

+

Alarms include the provision of break glass buttons and manual pull boxes that are used to activate alarms.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcAlarm defines the occurrence of any alarm; common information about alarm types is handled by IfcAlarmType. +The IfcAlarmType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcAlarmType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcAlarmType has ports or aggregated elements, such objects are reflected at the IfcAlarm occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcAlarmType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcAlarmType.HasPropertySets. +If both are given, then the properties directly defined at IfcAlarm override the properties defined at IfcAlarmType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcAlarm is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcAlarmType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAlarm are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the alarm occurrence is defined by IfcAlarmType, then the port occurrences must reflect those defined at the IfcAlarmType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcAlarm PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +1926;IfcUnitaryControlElement;"

A unitary control element combines a number of control components into a single product, such as a thermostat or humidistat.

+

A unitary control element provides a housing for an aggregation of control or electrical distribution elements that, in combination, perform a singular (unitary) purpose. Each item in the aggregation may have its own geometric representation and location.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcUnitaryControlElement defines the occurrence of any unitary control element; common information about unitary control element types is handled by IfcUnitaryControlElementType. +The IfcUnitaryControlElementType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcUnitaryControlElementType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcUnitaryControlElementType has ports or aggregated elements, such objects are reflected at the IfcUnitaryControlElement occurrence using the IfcRelDefinesByObject relationship.

+

Figure 181 illustrates unitary control element type use.

+

Figure 181 — Unitary control element type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcUnitaryControlElementType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcUnitaryControlElementType.HasPropertySets. +If both are given, then the properties directly defined at IfcUnitaryControlElement override the properties defined at IfcUnitaryControlElementType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcUnitaryControlElement is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcUnitaryControlElementType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Connection Use Definition

+

The IfcUnitaryControlElement may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcUnitaryControlElement are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the unitary control element occurrence is defined by IfcUnitaryControlElementType, then the port occurrences must reflect those defined at the IfcUnitaryControlElementType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcUnitaryControlElement PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • THERMOSTAT +
      +
    • Control (CONTROL, SOURCE): Receives power (typically 24V), and closes the circuit for Fan, Heat, and Cool. Port may be aggregated into sub-ports: 'Fan'(SIGNAL,SOURCE), 'Heat'(SIGNAL,SOURCE), and 'Cool'(SIGNAL,SOURCE)
    • +
    +
  • +
+

Figure 182 illustrates unitary control element port use.

+

Figure 182 — Unitary control element port use

+ + " +1941;IfcSensorType;" + +

The distribution control element type IfcSensorType defines commonly shared information for occurrences of sensors. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a sensor specification (i.e. the specific product information, that is common to all occurrences of that product type). Sensor types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSensorType are represented by instances of IfcSensor.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSensorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSensorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcSensor for standard port definitions.

+ +
" +1944;IfcControllerType;" + +

The distribution control element type IfcControllerType defines commonly shared information for occurrences of controllers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a controller specification (i.e. the specific product information, that is common to all occurrences of that product type). Controller types may be exchanged without being already assigned to occurrences. + Occurrences of IfcControllerType are represented by instances of IfcController.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcControllerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcControllerType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcControllerType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

    +
  • PROGRAMMABLE: May contain IfcController components. Programmable Logic Controllers may be decomposed into logical elements for values and operations.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcControllerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcController for standard port definitions.

+ +
" +1947;IfcActuatorType;" + +

The distribution control element type IfcActuatorType defines commonly shared information for occurrences of actuators. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a actuator specification (i.e. the specific product information, that is common to all occurrences of that product type). Actuator types may be exchanged without being already assigned to occurrences. + Occurrences of IfcActuatorType are represented by instances of IfcActuator.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcActuatorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcActuatorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcActuator for standard port definitions.

+ +
" +1950;IfcFlowInstrumentType;" + +

The distribution control element type IfcFlowInstrumentType defines commonly shared information for occurrences of flow instruments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a flow instrument specification (i.e. the specific product information, that is common to all occurrences of that product type). Flow Instrument types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFlowInstrumentType are represented by instances of IfcFlowInstrument.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFlowInstrumentType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFlowInstrumentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcFlowInstrument for standard port definitions.

+ +
" +1953;IfcAlarmType;" + +

The distribution control element type IfcAlarmType defines commonly shared information for occurrences of alarms. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a alarm specification (i.e. the specific product information, that is common to all occurrences of that product type). Alarm types may be exchanged without being already assigned to occurrences. + Occurrences of IfcAlarmType are represented by instances of IfcAlarm.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcAlarmType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAlarmType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcAlarm for standard port definitions.

+ +
" +1956;IfcUnitaryControlElementType;" + +

The distribution control element type IfcUnitaryControlElementType defines commonly shared information for occurrences of unitary control elements. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a unitary control element specification (i.e. the specific product information, that is common to all occurrences of that product type). Unitary Control Element types may be exchanged without being already assigned to occurrences. + Occurrences of IfcUnitaryControlElementType are represented by instances of IfcUnitaryControlElement.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcUnitaryControlElementType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcUnitaryControlElementType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcUnitaryControlElement for standard port definitions.

+ +
" +1960;IfcStructuralItem;" + +

Definition from IAI: The abstract entity IfcStructuralItem is the generalization of structural members and structural connections, i.e. analysis idealizations of elements in the building model. It defines the relation between structural members and connections with structural activities (actions and reactions).

+ +

Relationships between elements in the building model and structural items as their idealizations can be expressed by instances of IfcRelAssignsToProduct.

+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Use definitions and informal proposition added.
+ +

Coordinate Systems:

+ +

The following coordinate systems are distinguished:

+ +
    +
  • The so-called global coordinate system is the coordinate system shared by all items and activities which are grouped in a common IfcStructuralAnalysisModel. This coordinate system is established by SELF\IfcProduct.ObjectPlacement. (This coordinate system is not necessarily the same as the IfcProject's world coordinate system.)
  • +
  • The so-called local coordinate system is a coordinate system local to a structural item (connection or member). This coordinate system is established by a Representation (attribute inherited from IfcProduct) in conjunction with further use definitions and attributes of subtypes of IfcStructuralItem.
  • +
+ +

Representation items in topology representations are always given within the ObjectPlacement, i.e. in so-called global coordinates (global with respect to the IfcStructuralAnalysisModel to which this item belongs). + +

The usage of local coordinate systems is further defined in subtypes.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralItem shall have a topology representation. It includes a placement and a product representation. The IfcProductRepresentation shall be given by an item in a Representation of type IfcTopologyRepresentation.

+ +

Local Placement

+ +

The local placement for IfcStructuralActivity is defined in its supertype IfcProduct. It is defined by the IfcLocalPlacement, which establishes a global coordinate system which shall be common to all items and activities in an IfcStructuralAnalysisModel.

+ +

Topology Representation

+ +

Instances of IfcStructuralItem shall have a topology representation given by an instance of a subtype of IfcTopologicalRepresentationItem, which should be the single item of IfcTopologyRepresentation.Items. Depending on the dimensionality of the structural item, one of the following types of toplogical representation items shall be used:

+ +
    +
  • Point connections shall be represented by an IfcVertexPoint with an underlying IfcCartesianPoint. + The Cartesian point is the reference point of the connection in the so-called global coordinate system. + The following labels are used in the IfcTopologyRepresentation: +
      +
    • RepresentationIdentifier: 'Reference'
    • +
    • RepresentationType: 'Vertex'
    • +
    +
    +
  • + +
  • Curve members and curve connections shall either be represented by an IfcOrientedEdge, + IfcEdgeCurve, or IfcEdge. The curve to which the IfcEdgeCurve (or an + IfcOrientedEdge's underlying IfcEdgeCurve) refers to is the reference curve of the structural + item in the global coordinate system. Start and end vertex of the edge shall be IfcVertexPoints + with underlying IfcCartesianPoints. + The following labels are used in the IfcTopologyRepresentation: +
      +
    • RepresentationIdentifier: 'Reference'
    • +
    • RepresentationType: 'Edge'
    • +
    +
    NOTE  While an IfcEdge (or IfcOrientedEdge with underlying + IfcEdge) does not provide an explicit underlying curve geometry, it may be used to imply an + underlying straight line as reference curve with the origin of the curve parameter at the start vertex + point.
    +
  • + +
  • Surface members and surface connections shall be represented by an IfcFaceSurface. + The underlying surface defeines the reference surface of the structural surface item in the global + coordiante system. All edges in the bounds of the face shall conform to the rules for edge + representations of structural curve item. + The following labels are used in the IfcTopologyRepresentation: +
      +
    • RepresentationIdentifier: 'Reference'
    • +
    • RepresentationType: 'Face'
    • +
    +
  • +
+ +

The reference point, reference curve, or reference surface partially or completely defines the local coordinate system of the represented structural item according to the following rules. In all cases, The local x,y,z directions form a right-handed Cartesian coordinate system.

+ +

Structural point items

+ +
    +
  • The reference point in the representation is the origin of the local coordinate system of the structural item.
  • +
  • The axes of the local coordiante system are either parallel with and directed like the so-called global coordinate axes, or are oriented according to definitions at the respective subtype of IfcStructuralItem.
  • +
+ +

Structural curve items

+ +
    +
  • The u parameter origin of the reference curve in the representation is the origin of the local coordinate system of the structural item.
  • +
  • The local x axis is parallel with the tangent on the curve and directed like the u parameter direction.
  • +
  • The local y and z axes are oriented according to definitions at the respective subtypes of IfcStructuralItem.
  • +
+ +

Structural surface items

+ +
    +
  • The u,v parameter origin of the reference surface in the representation is the origin of the local coordinate system of the structural item.
  • +
  • The local x and y directions follow the tangents on the surface and are in parallel with and directed like u and v respectively.
  • +
  • The local z direction is in parallel with and directed like the surface normal.
  • +
+ +

Informal propositions:

+ +
    +
  1. The ObjectPlacements of all structural items which are grouped into the same instance of IfcStructuralAnalysisModel shall refer to the same instance of IfcObjectPlacement.
  2. +
+ +
NOTE  This rule is necessary to achieve consistent topology representations. The topology representations of structural items in an analysis model are meant to share vertices and edges und must therefore have the same object placement.
+ +
NOTE  A structural item may be grouped into more than one analysis model. In this case, all these models must use the same instance of IfcObjectPlacement.
+ +
" +1964;IfcStructuralMember;" + +

Definition from IAI: The abstract entity IfcStructuralMember is the superclass of all structural items which represent the idealized structural behavior of building elements.

+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Use definitions moved to supertype and subtypes.
+ +
" +1968;IfcStructuralCurveMember;" + +

Definition from IAI: Instances of IfcStructuralCurveMember describe edge members, i.e. structural analysis idealizations of beams, columns, rods etc.. Curve members may be straight or curved.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attribute Axis and WHERE rule added. Use definitions changed.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem. The local coordinate system is established by the reference curve given by topology representation and by the attribute Axis. The local x axis is parallel with the tangent on the reference curve. The local z axis is located in the surface which is created by sweeping Axis along the reference curve and is directed according to Axis. The local y axis is directed such that x,y,z form a right-handed Cartesian coordinate system.

+ +

Material Use Definition

+ +

The material of direct instances IfcStructuralCurveMember (in contrast to instances of the subtype IfcStructuralCurveMemberVarying) is defined by IfcMaterialProfileSetUsage and attached by the IfcRelAssociatesMaterial.RelatingMaterial. It is accessible by the inverse HasAssociations relationship. Composite profile beams can be represented by refering to several IfcMaterialProfiles within the IfcMaterialProfileSet that is referenced from the IfcMaterialProfileSetUsage. In case of tapered members, the material profile usage subtype IfcMaterialProfileSetUsageDual is used which specifies IfcMaterialProfileSets separately at the start and the end of the tapered member.

+ +

The material (IfcMaterial) in each IfcMaterialProfile(Set) is specified minimally by a name which corresponds with an agreed upon standardized structural material designation. An external reference to the source which specifies the material designation should be provided. Alternatively, structural material properties may be provided by means of IfcMechanicalMaterialProperties and IfcExtendedMaterialProperties.

+ +

The profile (IfcProfileDef) in each IfcMaterialProfile(Set) is specified minimally by a name which corresponds with an agreed upon standardized structural profile designation. An external reference to the source which specifies the profile designation should be provided. Alternatively or additionally, explicit profile geometry should be provided by using respective subtypes of IfcProfileDef. Alternatively or additionally, structural profile properties may be provided by means of subtypes of IfcProfileProperties.

+ +

An IfcProfileDef is a two-dimensional geometric object with a xp,yp coordinate system. The profile is inserted into the curve member model thus that the origin of xp,yp is located at the member's reference curve and that xp,yp are parallel with and directed like the local y,z.

+ +
NOTE  Due to convention in structural mechanics, axis names of IfcStructuralCurveMember differ from axis names of building elements like IfcBeamStandardCase: The extrusion axis of IfcStructuralCurveMember is called x while the extrusion axis of IfcBeamStandardCase is called z. Hence x,y,z of IfcStructuralCurveMember correspond with z,x,y of IfcBeamStandardCase.
+ +

If the profile is meant to be inserted centrically in terms of structural section properties, it is necessary that the origin of xp,yp is identical with the geometric centroid of the profile (commonly also called centre of gravity). If subtypes of IfcParameterizedProfileDef are used which are only singly symmetric or are asymmetric, an explicit translation by IfcParameterizedProfileDef.Position.Location is required then.

+ +

If the profile is inserted at its geometric centroid, IfcMaterialProfileSetUsage.CardinalPoint shall be set to 10.

+ +

Otherwise, the profile is inserted eccentrically and a different cardinal point should be set accordingly.

+ +
NOTE  Another eccentricity model is available independently of eccentric profile specification: The reference curve of the member may be located eccentrically relative to the reference points of the connected IfcStructuralPointConnections. The connection relationship is then established by IfcRelConnectsWithEccentricity. Whether one or the other or both eccentricity models may be used is subject to information requirements and local agreements.
+ +

Topology Use Definitions:

+ +

Direct instances of IfcStructuralCurveMember shall have a topology representation which consists of one instance of IfcEdge or a subtype, representing the reference curve of the curve member. See definitions at IfcStructuralItem for further specifications.

+ +

Informal propositions:

+ +
    +
  1. The reference curve must not be parallel with Axis at any point within the curve member's domain.
  2. +
+ +
" +1973;IfcStructuralCurveMemberVarying;" + +

Definition from IAI: Describes edge members with varying profile properties. Each instance of IfcStructuralCurveMemberVarying is composed of two or more instances of IfcStructuralCurveMember with differing profile properties. These subordinate members relate to the instance of IfcStructuralCurveMemberVarying by IfcRelAggregates.

+ +
NOTE  A curve member whose variation of profile properties can be sufficiently described by a start profile and an end profile (e.g. tapers) shall be modeled as a single direct instance of the supertype IfcStructuralCurveMember.
+ +
NOTE  It is recommended that structural activities (actions or reactions) are not connected with aggregated IfcStructuralCurveMemberVarying but only with the IfcStructuralCurveMembers in the aggregation. That way, difficulties in interpretation of local coordinates are avoided.
+ +
HISTORY: New entity in IFC 2x2.
+Use definition changed in IFC 2x4.
+ + +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem and IfcStructuralCurveMember. The local coordinates of the aggregate are derived from those of its parts. Length measures in local x direction of the aggregate depend on continuity and lengths of the parts. The Axis of the aggregate shal be the same as the Axis of the part at the start of the aggregate.

+ +

Material Use Definition

+ +

Only the individual parts (direct instances of IfcStructuralCurveMember) carry material and profile information.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralCurveMemberVarying may have a topology representation which contains a single IfcEdgeLoop, based upon the edges of the parts.

+ +
" +1982;IfcStructuralSurfaceMember;" + +

Definition from IAI: Instances of IfcStructuralSurfaceMember describe face members, i.e. structural analysis idealizations of slabs, walls, shells, etc.. Surface members may be planar or curved.

+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Use definitions changed, WHERE rule added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem. The local coordinate system is established by the reference surface given by topology representation.

+ +

Material Use Definition

+ +

The material of direct instances IfcStructuralSurfaceMember (in contrast to instances of the subtype IfcStructuralSurfaceMemberVarying) is defined by IfcMaterial and attached by the IfcRelAssociatesMaterial.RelatingMaterial. It is accessible by the inverse HasAssociations relationship.

+ +

The material is specified minimally by a name which corresponds with an agreed upon standardized structural material designation. An external reference to the source which specifies the material designation should be provided. Alternatively, structural material properties may be provided by means of IfcMechanicalMaterialProperties and IfcExtendedMaterialProperties.

+ +

Direct instances of IfcStructuralSurfaceMember are assumed to be located centrically relative to their reference surface. Their depth is provided in the attribute Thickness.

+ +

Topology Use Definitions:

+ +

Direct instances of IfcStructuralSurfaceMember shall have a topology representation which consists of one IfcFaceSurface, representing the reference surface of the surface member. See definitions at IfcStructuralItem for further specifications.

+ +
" +1987;IfcStructuralSurfaceMemberVarying;" + +

Definition from IAI: Describes surface members with varying section properties. The properties are provided by means of a property set and IfcRelDefinesByProperties or by means of aggregation: An instance of IfcStructuralSurfaceMemberVarying may be composed of two or more instances of IfcStructuralSurfaceMember with differing section properties. These subordinate members relate to the instance of IfcStructuralSurfaceMemberVarying by IfcRelAggregates.

+ +
NOTE  It is recommended that structural activities (actions or reactions) are not connected with aggregated IfcStructuralSurfaceMemberVarying but only with the IfcStructuralSurfaceMembers in the aggregation. That way, difficulties in interpretation of local coordinates are avoided.
+ +
HISTORY: New entity in IFC 2x2.
+Use definition changed and attributes deleted in IFC 2x4.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem and IfcStructuralSurfaceMember. The local coordinates of an aggregate are generally undefined since continuity of local coordinates of the parts is not ensured.

+ +

Material Use Definition

+ +

In case of aggregation, only the individual parts (direct instances of IfcStructuralSurfaceMember) carry material and thickness information. Otherwise, definitions at IfcStructuralSurfaceMember apply.

+ +

Topology Use Definitions:

+ +

In case of aggregation, instances of IfcStructuralSurfaceMemberVarying may have a topology representation which contains a single IfcConnectedFaceSet, based upon the faces of the parts. Otherwise, definitions at IfcStructuralSurfaceMember apply.

+ +
" +1994;IfcRelConnectsStructuralMember;" + +

The entity IfcRelConnectsStructuralMember defines all needed properties describing the connection between structural members and structural connection objects (nodes or supports).

+ +
HISTORY  New entity in IFC2x2.
+ +

Use Definition

+ +

Point Connection
+Instances of the entity IfcRelConnectsStructuralMember shall be used to describe a connection between an instance of IfcStructuralPointConnection and either an instance of IfcStructuralCurveMember or IfcStructuralSurfaceMember. The RelatedStructuralConnection for point connections has to be of type IfcStructuralPointConnection.

+ +

Curve Connection
+Instances of the entity IfcRelConnectsStructuralMember shall be used to describe a connection between an instance of IfcStructuralCurveConnection and an instance of either IfcStructuralCurveMember or IfcStructuralSurfaceMember. The RelatedStructuralConnection for curve connections has to be of type IfcStructuralCurveConnection.

+ +

Surface Connection
+Instances of the entity IfcRelConnectsStructuralMember shall be used to describe a connection between an instance of IfcStructuralSurfaceConnection and an instance of IfcStructuralSurfaceMember. The RelatedStructuralConnection for curve connections has to be of type IfcStructuralSurfaceConnection.

+ +

Coordinate System for Applied Conditions
+All values defined by AppliedCondition or AdditionalConditions are given within the coordinate system provided by ConditionCoordinateSystem, which is defined relative to the local coordinate system of the structural member. If the ConditionCoordinateSystem is not defined, the local coordinate system of the structural member is used instead.

+ +

Supported Length
+Optionally a supported length can be given, which specifies the length (or width) of the physical connection along a curve connection.

+ +

Figure 235 illustrates the appropriate definition of support lengths.

+ + + + + + + + +
+

+
+

Figure 235 — Structural member support lengths

+
+ +
" +2002;IfcRelConnectsStructuralActivity;" + +

Definition from IAI: The IfcRelConnectsStructuralActivity relationship connects a structural activity (either an action or reaction) to a structural member, structural connection, or element.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2008;IfcStructuralAnalysisModel;" + +

Definition from IAI: The IfcStructuralAnalysisModel is used to assemble all information needed to represent a structural analysis model. It encompasses certain general properties (such as analysis type), references to all contained structural members, structural supports or connections, as well as loads and the respective load results.

+ +

Important functionalities for the description of an analysis model are derived from existing IFC entities:

+ +
    +
  • From IfcSystem it inherits the ability to couple the analysis model via IfcRelServicesBuildings to one or more IfcBuildings as necessary.
  • +
  • From IfcGroup it inherits the inverse attribute IsGroupedBy, pointing to the relationship class IfcRelAssignsToGroup. This allows to group structural members (instances of IfcStructuralMember), and supports (instances of IfcStructuralConnection) which belong to a specific analysis model. +
    NOTE: Loads (as instances of IfcStructuralAction) are not included through IsGroupedBy. Loads are assigned through the LoadedBy attribute relationship, using load groups as a grouping mechanism. Only top-level load groups should be referenced via LoadedBy, i.e. load combinations if any load combinations exist, or load cases if no load combinations exist in this analysis model.
    +
    NOTE: Results (as instances of IfcStructuralReaction) are not included through IsGroupedBy. Results are assigned through the HasResults attribute relationship, using result groups as a grouping mechanism.
    +
  • +
  • From IfcObject it inherits the inverse attribute IsDecomposedBy pointing to the relationship class IfcRelNests. It provides the hierarchy between the separate (partial) analysis models.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attribute SharedPlacement and informal propositions added, allowing for easy retrieval of the common object placement and for specification of the analysis model's coordiante system before any structural item is instantiated. WHERE rule added.
+ +

Informal propositions:

+ +
    +
  1. If one or more structural item (instance of a subtype of IfcStructuralItem) is grouped into an IfcStructuralAnalysisModel, the attribute SharedPlacement shall be provided with a value.
  2. +
  3. The ObjectPlacements of all structural items which are grouped into the same instance of IfcStructuralAnalysisModel shall refer to the same instance of IfcObjectPlacement as IfcStructuralAnalysisModel.SharedPlacement.
  4. +
+ +
NOTE  This rule is necessary to achieve consistent topology representations. The topology representations of structural items in an analysis model are meant to share vertices and edges und must therefore have the same object placement.
+ +
NOTE  A structural item may be grouped into more than one analysis model. In this case, all these models must use the same instance of IfcObjectPlacement.
+ + +
" +2021;IfcStructuralLoadGroup;" + +

Definition from IAI: The entity IfcStructuralLoadGroup is used to structure the +physical impacts. By using the grouping features inherited from IfcGroup, instances of +IfcStructuralAction (or its subclasses) and of IfcStructuralLoadGroup can be used to +define load groups, load cases and load combinations. (See also IfcLoadGroupTypeEnum.)

+ +
NOTE: Important functionality for the description of a load-bearing system +is derived from the existing IFC entity IfcGroup. This class provides, via the relationship +class IfcRelAssignsToGroup, the needed grouping mechanism. In this way, instances of +IfcStructuralAction belonging to a specific load group can be unambiguously determined. +
+ +
NOTE: The relationship class IfcRelAssignsToGroupByFactor is +used to group load cases into load combinations. The factor provided in this assignment relationship +is to applied together with the optional IfcStructuralLoadGroup.Coefficient. Unlike this +coefficient which always affects the load group, the IfcRelAssignsToGroupByFactor.Factor is +specific for a load case—load combination pair. As many instances of +IfcRelAssignsToGroupByFactor are used within one load combination as there are different +Factors to be applied to load cases in the load combination. +
+ +
On the other hand, a load case may appear in more than one load combination +and can have a different Factor in each assignment by IfcRelAssignsToGroupByFactor. +
+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Subtype IfcStructuralLoadCase added. Informal propositions and WHERE rule added. +Predefined type LOAD_COMBINATION_GROUP made obsolete and removed.
+ +

Informal propositions:

+ +
    +
  1. Load groups of type LOAD_GROUP shall only contain instances of IfcStructuralAction.
  2. +
  3. Load groups of type LOAD_CASE shall always be instantiated from the subtype IfcStructuralLoadCase, + not directly from the generic type IfcStructuralLoadGroup itself.
  4. +
  5. Instances of IfcStructuralLoadCase shall only contain instances of IfcStructuralAction + or/ and instances of IfcStructuralLoadGroup of type LOAD_GROUP.
  6. +
  7. Load groups of type LOAD_COMBINATION shall only contain instances of IfcStructuralLoadCase.
  8. +
+ +
" +2031;IfcStructuralResultGroup;" + +

Definition from IAI: Instances of the entity IfcStructuralResultGroup are used to group results of structural analysis calculations and to capture the connection to the underlying basic load group. The basic functionality for grouping inherited from IfcGroup is used to collect instances from IfcStructuralReaction or its respective subclasses.

+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: WHERE rule added.
+ +
" +2044;IfcStructuralLoadCase;" + +

Definition from IAI: A load case is a load group, commonly used to group loads from the same action source.

+ +
HISTORY: New entity in IFC 2x4.
+ +
" +2087;IfcStructuralActivity;" + +

Definition from IAI: The abstract entity IfcStructuralActivity combines the definition of actions (such as forces, displacements, etc.) and reactions (support reactions, internal forces, deflections, etc.) which are specified by using the basic load definitions from the IfcStructuralLoadResource.

+ +

The differentiation between actions and reactions is realized by instantiating objects either from subclasses of IfcStructuralAction or IfcStructuralReaction respectively. They inherit commonly needed attributes from the abstract superclass IfcStructuralActivity, notably the relationship which connects actions or reactions with connections, analysis members, or elements (subtypes of IfcStructuralItem or IfcElement).

+ +
NOTE  Instances of IfcStructuralActivity which are connected with an IfcElement are subject to agreements outside the scope of this specification.
+ +
NOTE  The semantics of IfcStructuralActivity are only fully defined +if an activity instance is connected with exactly one structural item. The inverse attribute +AssignedToStructuralItem can only be empty in incomplete models or in conceptual models +which are not yet ready for analysis.
+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Cardinality of attribute +AssignedToStructuralItem relaxed from 1 to 0..1 in order to allow for schema-compliant +incomplete models as well as conceptual models without load—item relationships.
+ +

Coordinate Systems:

+ +

The following coordinate systems are distinguished:

+ +
    +
  • The so-called global coordinate system is the coordinate system shared by all items and activities which are grouped in a common IfcStructuralAnalysisModel. This coordinate system is established by an ObjectPlacement. (This coordinate system is not necessarily the same as the IfcProject's world coordinate system.)
  • +
  • The so-called local coordinate system is a coordinate system local to a structural item (connection or member). This coordinate system is established by a Representation in conjunction with further use definitions and attributes of subtypes of IfcStructuralItem.
  • +
+ +

Representation items in topology representations are always given within the ObjectPlacement, i.e. in so-called global coordinates (global with respect to the IfcStructuralAnalysisModel to which this activity belongs). + +

Locations of the load objects in the AppliedLoad attribute (if of type IfcStructuralLoadConfiguration) are always given in local coordinates.

+ +

Directions of the load objects in the AppliedLoad attribute refer to global or local coordinates according to the GlobalOrLocal attribute.

+ +

The ObjectPlacement and Representation are sometimes not explicitly instantiated; instead they may be implied as described below. Global and local coordinate systems are then determined in the same way as with explicit placement and representation.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralActivity which are connected with a structural item of same dimensionality, i.e.

+
    +
  • a point action or reaction connected with a point item (IfcStructuralPointConnection),
  • +
  • a curve action or reaction connected with a curve item (IfcStructuralCurveConnection, IfcStructuralCurveMember), or
  • +
  • a surface action or reaction connected with a surface item (IfcStructuralSurfaceConnection, IfcStructuralSurfaceMember) and which acts on the entire surface of the item and is not specified by isocontours
  • +
+

shall not have an ObjectPlacement nor a Representation. It is implied that the placement and representation of the IfcStructuralActivity is the same as the ones of the IfcStructuralItem.

+ +

Instances of IfcStructuralActivity which are connected with

+
    +
  • a curve item (IfcStructuralCurveConnection, IfcStructuralCurveMember) and act on a point of the item
  • , or +
  • a surface item (IfcStructuralSurfaceConnection, IfcStructuralSurfaceMember) and act on a point or on a curve or on a part of the surface of the item
  • +
+

shall have a topology representation as specified below. It includes a placement and a product representation. The IfcProductRepresentation shall be given by an item in a Representation of type IfcTopologyRepresentation.

+ +

Instances of IfcStructuralActivity which are connected with

+
    +
  • a surface item (IfcStructuralSurfaceConnection, IfcStructuralSurfaceMember) and are specified by isocontours
  • +
+

shall have a shape representation as specified below. It includes a placement and a product representation. The IfcProductRepresentation shall be given by items in a Representation of type IfcShapeRepresentation. Shape representation and topology representation may be combined.

+ +

Local Placement

+ +

The local placement for IfcStructuralActivity is defined in its supertype IfcProduct. It is defined by the IfcLocalPlacement, which establishes a global coordinate system which shall be common to all items and activities in an IfcStructuralAnalysisModel.

+ +

Topology Representation

+ +

Instances of IfcStructuralActivity which act on parts of a surface item shall have a topology representation given by a face with underlying surface geometry, IfcFaceSurface, which should be the single item of IfcTopologyRepresentation.Items. The surface establishes a local coordinate system of the activity:

+
    +
  • The origin of surface parameters u,v is the origin of the local coordinate system.
  • +
  • The local x and y directions follow the tangents on the surface and are in parallel with and directed like u and v respectively.
  • +
  • The local z direction is in parallel with and directed like the surface normal.
  • +
+
+
    +
  • RepresentationIdentifier: 'Reference'
  • +
  • RepresentationType: 'Face'
  • +
+
+ +

Instances of IfcStructuralActivity which act on a curve on a surface item shall have a topology representation given by an edge (IfcEdge or subtype), which should be the single item of IfcTopologyRepresentation.Items. The curve geometry shall be compatible with the surface geometry of the connected item. In conjunction with this surface, the curve establishes a local coordinate system of the activity:

+
    +
  • The origin of the curve parameter u is the origin of the local coordinate system.
  • +
  • The local x direction follows the tangent on the curve and is directed like u.
  • +
  • The local z direction is in parallel with and directed like the surface normal of the connected surface item.
  • +
  • The local x,y,z directions form a right-handed Cartesian coordinate system.
  • +
+
+
    +
  • RepresentationIdentifier: 'Reference'
  • +
  • RepresentationType: 'Edge'
  • +
+
+
NOTE  While an IfcEdge (or IfcOrientedEdge with underlying IfcEdge) does not provide an explicit underlying curve geometry, it may be used to imply an underlying straight line as reference curve with the origin of the curve parameter at the start vertex point.
+ +

Instances of IfcStructuralActivity which act on a single point on a curve or surface item shall have a topology representation given by an IfcVertexPoint, which should be the single item of IfcTopologyRepresentation.Items. The point geometry shall be compatible with the curve or surface geometry of the connected item. The local coordinate system of the activity is oriented by the curve or surface geometry of the connected item as described above for activities with edge or face topology.

+
+
    +
  • RepresentationIdentifier: 'Reference'
  • +
  • RepresentationType: 'Vertex'
  • +
+
+ +

Shape Representation

+ +

Instances of IfcStructuralActivity which act on a surface item and are specified by isocontours (level sets) shall have a shape representation given by a set of curves on a surface, IfcPCurve. The basis surface shall comply with or preferably be identical with the surface of the structural item to which the activity is connected. The representation identifier and type of this geometric representation is:

+
+
    +
  • RepresentationIdentifier: 'Level set'
  • +
  • RepresentationType: 'GeometricCurveSet'
  • +
+
+ +
" +2093;IfcStructuralAction;" + +

Definition from IAI: A structural action is a structural activity that acts upon +a structural item or building element.

+ +
HISTORY  New entity in IFC 2x2.
+
IFC 2x4 change: Attribute DestabilizingLoad made optional. Attribute CausedBy deleted; use IfcRelAssignsToProduct via ReferencedBy instead.
+ +

Structural actions are grouped into either an IfcStructuralLoadGroup of predefined +type LOAD_GROUP or, more often, an IfcStructuralLoadCase. This is accomplished via the +inverse relationship HasAssignments and an IfcRelAssignsToGroup relationship object. +IfcStructuralLoadGroup.LoadGroupFor or IfcStructuralLoadCase.LoadGroupFor respectively +refers to the structural analysis model(s) in which the loads are used.

+ +

It is furthermore possible to establish relationships between actions in one analysis model +and reactions in another analysis model which cause the actions. For example, a support reaction +from one structural system may be taken over as a load onto another supporting structural system. +This is expressed by means of the inverse relationship ReferencedBy of the action and an +IfcRelAssignsToProduct relationship object. IfcRelAssignsToProduct.Name is set to +'Causes' and IfcRelAssignsToProduct.RelatedObjects refers to an instance of a subtype of +IfcStructuralReaction.

+ +
" +2098;IfcStructuralPointAction;" + +

Definition from IAI: Defines an action which acts on a point. +A point action is typically connected with a point connection. +It may also be connected with a curve member or curve connection, +or surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attributes in the supertypes +IfcStructuralActivity and IfcStructuralAction changed. Use definitions changed, +informal propositions added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

Standard Case:
+If connected with a point item, instances of IfcStructuralPointAction +shall not have an ObjectPlacement nor a Representation. +It is implied that the placement and representation of the action is the same +as the structural item.

+ +

Special Case 1:
+If connected with a curve item or surface item, instances of IfcStructuralPointAction +shall have an ObjectPlacement and Representation, containing an IfcVertexPoint. +See IfcStructuralActivity for further definitions.

+ +
NOTE In order to model concentrated actions on a curve or surface item, +IfcStructuralCurveAction or IfcStructuralSurfaceAction of type DISCRETE is +preferable since they do not require an extra topology representation in this case. +An IfcStructuralPointAction should be used for a concentrated action on a curve or surface +item only when an explicit vertex point representation is actually desired.
+ +

Special Case 2:
+If not connected with a structural item (which may happen in an incomplete or +conceptual model), a point action should have an ObjectPlacement and +Representation, containing an IfcVertexPoint. +See IfcStructuralActivity for further definitions.

+ +

Informal propositions:

+ +
    +
  1. SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadSingleForce or + IfcStructuralLoadSingleDisplacement.
  2. +
+ +
" +2099;IfcStructuralCurveAction;" + +

Definition from IAI: Defines an action which is distributed over a curve. +A curve action may be connected with a curve member or curve connection, or +surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x4.
+ +
IFC 2x4 change: Former entitiy +IfcStructuralLinearActionVarying from IFC 2x2 has been removed and are replaced +by this entity.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

Standard Case:
+If connected with a curve item, instances of IfcStructuralCurveAction shall not have an +ObjectPlacement nor a Representation. It is implied that the placement and +representation of the IfcStructuralActivity is the same as the ones of the member or +connection.

+ +

Special Case 1:
+If connected with a surface item, instances of IfcStructuralCurveAction shall have an +ObjectPlacement and Representation, containing an IfcEdgeCurve. See +IfcStructuralActivity for further definitions.

+ +

Special Case 2:
+If not connected with a structural item (which may happen in an incomplete or conceptual model), +a curve action should have an ObjectPlacement and Representation, containing an +IfcEdgeCurve. See IfcStructuralActivity for further definitions.

+ +

Informal propositions:

+ +
    +
  1. If the curve action is of the predefined type CONST, SINUS, or PARABOLA, + SELF\IfcStructuralActivity.AppliedLoad must not be of type + IfcStructuralLoadConfiguration. In case of SINUS and PARABOLA, the load item + defines the maximum of the load at the centre of the load distribution.
  2. +
  3. If the curve action is of the predefined type LINEAR, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two items.
  4. +
  5. If the curve action is of the predefined type POLYGONAL, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain three or more items.
  6. +
  7. If the curve action is of the predefined type DISCRETE, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two or more items.
  8. +
  9. In case of types LINEAR, POLYGONAL, and DISCRETE, the load items shall have + one-dimensional IfcStructuralLoadConfiguration.Locations, defining the + location of the load samples in local coordinates of the curve action. + The load items shall be provided in ascending order according to their locations. + The first and the last load item define the extent of the load distribution. +
  10. Point actions must be of type DISCRETE, thus contain two or more load points. + (Single point loads are modeled by IfcStructuralPointAction.)
  11. +
  12. All items in SELF\IfcStructuralActivity.AppliedLoad\IfcStructuralLoadConfiguration.Values + shall be of the same entity type.
  13. +
+ + +
" +2106;IfcStructuralLinearAction;" + +

Definition from IAI: Defines an action with constant value which is distributed over a curve.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Intermediate supertype IfcStructuralCurveAction inserted. Derived attribute PredefinedType added.
+ +
NOTE  Like its supertype IfcStructuralCurveAction, this action type may also act on curved edges.
+ +
" +2121;IfcStructuralSurfaceAction;" + +

Definition from IAI: Defines an action which is distributed over a surface. +A surface action may be connected with a surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x4.
+ +
IFC 2x4 change: Former entity +IfcStructuralPlanarActionVarying from IFC 2x2 has been removed and are replaced +by this entity.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

Standard Case:
+If connected with a surface item and acting on its entirety, instances of +IfcStructuralCurveAction shall not have an ObjectPlacement nor a +Representation. It is implied that the placement and representation of the +IfcStructuralActivity is the same as the ones of the member or connection.

+ +

Special Case 1:
+If connected with a surface item but acting only on a part of it, instances of +IfcStructuralSurfaceAction shall have an ObjectPlacement and +Representation, containing an IfcFaceSurface which topologically +defines the loaded part of the surface. See IfcStructuralActivity for further +definitions.

+ +

Special Case 2:
+If not connected with a structural item (which may happen in an incomplete or conceptual model), +a surface action should have an ObjectPlacement and Representation, containing an +IfcFaceSurface. See IfcStructuralActivity for further definitions.

+ +

Informal propositions:

+ +
    +
  1. If the surface action is of the predefined type CONST, + SELF\IfcStructuralActivity.AppliedLoad must not be of type + IfcStructuralLoadConfiguration.
  2. +
  3. If the surface action is of the predefined type BILINEAR, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain three items + with two-dimensional IfcStructuralLoadConfiguration.Locations, + defining the location of the load samples in local coordinates of the + surface action. +
  4. If the surface action is of the predefined type DISCRETE, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two or more + items with two-dimensional locations. +
  5. Point loads must be of type DISCRETE, thus contain two or more load points. + (Single point loads are modeled by IfcStructuralPointLoad.)
  6. +
  7. All items in SELF\IfcStructuralActivity.AppliedLoad\IfcStructuralLoadConfiguration.Values + shall be of the same entity type.
  8. +
+ +
" +2127;IfcStructuralPlanarAction;" + +

Definition from IAI: Defines an action with constant value which is distributed over a surface.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Intermediate supertype IfcStructuralSurfaceAction inserted. Derived attribute PredefinedType added.
+ +
NOTE  Like its supertype IfcStructuralSurfaceAction, this action type may also act on curved faces.
+ +
" +2136;IfcStructuralReaction;" + +

Definition from IAI: A structural reaction is a structural activity that results from a +structural action imposed to a structural item or building element. Examples are support reactions, +internal forces, and deflections.

+ +
HISTORY  New entity in IFC 2x2.
+ +
IFC 2x4 change: Inverse attribute Causes deleted; use IfcRelAssignsToProduct via HasAssignments instead.
+ +

Structural reactions are grouped into IfcStructuralResultGroups via the inverse +relationship HasAssignments and an IfcRelAssignsToGroup relationship object. +IfcStructuralResultGroup.ResultGroupFor finally refers to the structural analysis model +in which the results occur.

+ +

It is furthermore possible to establish relationships between reactions in one analysis model +and actions which they cause in another analysis model. For example, a support reaction from one +structural system may be taken over as a load onto another supporting structural system. This is +expressed by means of the inverse relationship HasAssignments of the reaction and an +IfcRelAssignsToProduct relationship object. IfcRelAssignsToProduct.Name is set to +'Causes' and IfcRelAssignsToProduct.RelatingProduct refers to an instance of a subtype of +IfcStructuralAction.

+ + +
" +2140;IfcStructuralPointReaction;" + +

Definition from IAI: Defines a reaction which occurs at a point. +A point reaction is typically connected with a point connection. +It may also be connected with a curve member or curve connection, +or surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attributes in the supertypes IfcStructuralActivity and IfcStructuralReaction changed. Use definitions changed, informal propositions added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

Standard Case:
+If connected with a point item, instances of IfcStructuralPointReaction +shall not have an ObjectPlacement nor a Representation. +It is implied that the placement and representation of the reaction is the same +as the structural item.

+ +

Special Case 1:
+If connected with a curve item or surface item, instances of IfcStructuralPointReaction +shall have an ObjectPlacement and Representation, containing an IfcVertexPoint. +See IfcStructuralActivity for further definitions.

+ +
NOTE In order to model concentrated reactions on a curve or surface item, +IfcStructuralCurveReaction or IfcStructuralSurfaceAction of type DISCRETE is +preferable since they do not require an extra topology representation in this case. +An IfcStructuralPointReaction should be used for a concentrated reaction on a curve or surface +item only when an explicit vertex point representation is actually desired.
+ +

Special Case 2:
+If not connected with a structural item (which may happen in an incomplete or +conceptual model), a point action should have an ObjectPlacement and +Representation, containing an IfcVertexPoint. +See IfcStructuralActivity for further definitions.

+ +

Informal propositions:

+ +
    +
  1. SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadSingleForce or + IfcStructuralLoadSingleDisplacement.
  2. +
+ +
" +2141;IfcStructuralCurveReaction;" + +

Definition from IAI: Defines a reaction which occurs distributed over a curve. +A curve reaction may be connected with a curve member or curve connection, +or surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x4.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

Standard Case:
+If connected with a curve item, instances of IfcStructuralCurveRection shall not +have an ObjectPlacement nor a Representation. It is implied that the +placement and representation of the IfcStructuralActivity is the same as the ones +of the member or connection.

+ +

Special Case:
+If connected with a surface item, instances of IfcStructuralCurveReaction shall +have an ObjectPlacement and Representation, containing an IfcEdgeCurve. +See IfcStructuralActivity for further definitions.

+ +

Informal propositions:

+ +
    +
  1. If the curve reaction is of the predefined type CONST, + SELF\IfcStructuralActivity.AppliedLoad must not be of type + IfcStructuralLoadConfiguration.
  2. +
  3. If the curve reaction is of the predefined type LINEAR, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two items.
  4. +
  5. If the curve reaction is of the predefined type POLYGONAL, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain three or more items.
  6. +
  7. If the curve action is of the predefined type DISCRETE, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two or more items.
  8. +
  9. In case of types LINEAR, POLYGONAL, and DISCRETE, the load items shall have + one-dimensional IfcStructuralLoadConfiguration.Locations, defining the + location of the result samples in local coordinates of the curve reaction. + The load items shall be provided in ascending order according to their locations. + The first and the last load item define the extent of the result distribution. +
  10. If the curve reaction is of the predefined type EQUIDISTANT, + SELF\IfcStructuralActivity.AppliedLoad shall be of type + IfcStructuralLoadConfiguration and shall contain two or more items. + IfcStructuralLoadConfiguration.Locations shall be omitted as it is implicit. + The load items shall be provided in ascending order. The first and the last load + item are located at the beginning and end of the result distribution, respectively.
  11. +
  12. All items in SELF\IfcStructuralActivity.AppliedLoad\IfcStructuralLoadConfiguration.Values + shall be of the same entity type.
  13. +
+ +
" +2145;IfcStructuralSurfaceReaction;" + +

Definition from IAI: Defines a reaction which occurs distributed over a surface. A surface reaction may be connected with a surface member or surface connection.

+ +
HISTORY: New entity in IFC 2x4.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralActivity.

+ +

Topology Use Definitions:

+ +

See definitions at IfcStructuralActivity.

+ +

Informal propositions:

+ +
    +
  1. If the surface reaction is of the predefined type CONST, SELF\IfcStructuralActivity.AppliedLoad must not be of type IfcStructuralLoadConfiguration.
  2. +
  3. If the surface reaction is of the predefined type BILINEAR, SELF\IfcStructuralActivity.AppliedLoad shall be of type IfcStructuralLoadConfiguration and shall contain three items with two-dimensional IfcStructuralLoadConfiguration.Locations, defining the location of the result samples in local coordinates of the surface reaction. +
  4. If the surface reaction is of the predefined type DISCRETE, SELF\IfcStructuralActivity.AppliedLoad shall be of type IfcStructuralLoadConfiguration and shall contain two or more items with two-dimensional locations. +
  5. If the surface reaction is of the predefined type ISOCONTOUR, SELF\IfcStructuralActivity.AppliedLoad shall be of type IfcStructuralLoadConfiguration and shall contain the same number of items as the set SELF.IfcProduct.Representation.Representations[?].Items. Each item in the load configuration shall have a two-dimensional location, defining the location of the result samples in local coordinates of the surface reaction. Each item in SELF\IfcStructuralActivity.AppliedLoad shall be located at exactly one of the isocontours. +
    NOTE  The set of representation items is unordered, hence result locations are required to correlate result values and isocontours.
    +
    NOTE  Isocontours are represented as IfcPCurves which are defined in terms of surface parameters u,v, while result locations are given in local surface item coordinates x,y. It is strongly recommended that the surface parameterization u,v is scaled 1:1 in order to avoid different scales of u,v versus x,y. If u,v are scaled 1:1 and the IfcPCurve's base surface is identical with the surface item's base surface, u,v and local x,y are identical.
    +
  6. +
  7. All items in SELF\IfcStructuralActivity.AppliedLoad\IfcStructuralLoadConfiguration.Values shall be of the same entity type.
  8. +
+ +
" +2148;IfcRelConnectsWithEccentricity;" + +

Definition from IAI: The entity IfcRelConnectsWithEccentricity adds the definition of eccentricity to the connection between a structural member and a structural connection (representing either a node or support).

+ +
NOTE  Another eccentricity model is available independently of eccentric connection specification: The section profile of a curve member may be inserted eccentrically with respect to the member's reference curve, see definitions at IfcStructuralCurveMember. Whether one or the other or both eccentricity models may be used is subject to information requirements and local agreements.
+ +
HISTORY  New entity in IFC 2x3.
+Use definitions changed in IFC 2x4 to always require two topology items.
+ +

Use Definition

+ +

Point Connection
+ConnectionConstraint shall be of type IfcConnectionPointGeometry and shall refer to two instances of IfcVertexPoint.

+ +

Curve Connection
+ConnectionConstraint shall be of type IfcConnectionCurveGeometry and shall refer to two instances of IfcEdge or subtypes.

+ +

Surface Connection
+ConnectionConstraint shall be of type IfcConnectionSurfaceGeometry and shall refer to two instances of IfcFaceSurface.

+ +
" +2150;IfcStructuralConnection;" + +

Definition from IAI: An IfcStructuralConnection represents a structural connection object (node i.e. vertex connection, or edge connection, or surface connection) or supports.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2156;IfcStructuralCurveConnection;" + +

Definition from IAI: Instances of IfcStructuralCurveConnection describe edge 'nodes', i.e. edges where two or more surface members are joined, or edge supports. Edge curves may be straight or curved.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attribute Axis added, allowing for skewed supports. Use definitions added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem. The local coordinate system is established by the reference curve given by topology representation and by the attribute Axis. The local x axis is parallel with the tangent on the reference curve. The local z axis is located in the surface which is created by sweeping Axis along the reference curve and is directed according to Axis. The local y axis is directed such that x,y,z form a right-handed Cartesian coordinate system.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralCurveConnection shall have a topology representation which consists of one instance of IfcEdge or a subtype, representing the reference curve of the curve connection. See definitions at IfcStructuralItem for further specifications.

+ +

Informal propositions:

+ +
    +
  1. The reference curve must not be parallel with Axis at any point within the curve connections's domain.
  2. +
+ +
" +2158;IfcStructuralPointConnection;" + +

Definition from IAI: Instances of IfcStructuralPointConnection describe structural nodes or point supports.

+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: Attribute ConditionCoordinateSystem added, allowing for skewed supports. Use definitions added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem. The local coordinate system is established by the reference point given by topology representation and by the attribute ConditionCoordinateSystem.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralPointConnection shall have a topology representation which consists of one IfcVertexPoint, representing the reference point of the point connection. See definitions at IfcStructuralItem for further specifications.

+ +
" +2160;IfcStructuralSurfaceConnection;" + +

Definition from IAI: Instances of IfcStructuralSurfaceConnection describe face 'nodes', i.e. faces where two or more surface members are joined, or face supports. Face surfaces may be planar or curved.

+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Use definitions added.
+ +

Coordinate Systems:

+ +

See definitions at IfcStructuralItem. The local coordinate system is established by the reference surface given by topology representation.

+ +

Topology Use Definitions:

+ +

Instances of IfcStructuralSurfaceConnection shall have a topology representation which consists of one IfcFaceSurface, representing the reference surface of the surface connection. See definitions at IfcStructuralItem for further specifications.

+ +
" +2166;IfcGeometricRepresentationContext;" + +

Definition from ISO/CD 10303-42:1992: A geometric +representation context is a representation context in which the +geometric representation items are geometrically founded. A +geometric representation context is a distinct coordinate space, +spatially unrelated to other coordinate spaces.

+ +

IfcGeometricRepresentationContext defines the context that +applies to several shape representations of products within a +project. It defines the type of the context in which the shape +representation is defined, and the numeric precision applicable +to the geometric representation items defined in this context. In +addition it can be used to offset the project coordinate system +from a global point of origin, using the +WorldCoordinateSystem attribute.

+ +

As shown in Figure 329, the TrueNorth attribute should be provided if the y axis of the WorldCoordinateSystem does not point to the global northing. Direction of the true north, or geographic northing direction, relative to the underlying project coordinate +system as established by the attribute WorldCoordinateSystem. It is given by a 2 dimensional direction within the xy-plane of the project coordinate system. If not resent, it defaults to [0.,1.] - i.e. the positive Y axis of the project coordinate system equals the geographic northing direction. The direction is provided within project coordinate system and identifies the true north direction (see +figure).

+ + + + +

Figure 329 — Geometric representation context true north

+ +
+NOTE ÿThe inherited attribute +ContextType shall have one of the following recognized +values: 'Sketch', 'Outline', 'Design', 'Detail', +'Model', 'Plan', +'NotDefined'. +
+

The use of one instance of +IfcGeometricRepresentationContext to represent the model +(3D) view is mandatory, the use of a second instance of +IfcGeometricRepresentationContext to represent the plan +(2D) view is optional (but needs to be given, if there are scale +dependent plan views), the additional scale or view dependent +contexts need to be handled by using the subtype +IfcGeometricRepresentationSubContext pointing to the model +view (or the plan view) as the ParentContext.

+ +

Figure 330 illustrates use of representation contexts defined at IfcProject for 3D model and 2D plan context, including sub +context definitions for different target scales.

+ + + + +

Figure 330 — Geometric representation context use

+ +
+NOTE  The definition of this class relates to the ISO 10303 entity geometric_representation_context. Please refer to ISO/IS 10303-42:1994 for the final definition of the formal standard. +
+ +
+HISTORY ÿNew Entity in IFC Release 2.0 +
+ +
+IFC2x3 CHANGE ÿApplicable values for ContextType are only 'Model',ÿ 'Plan', andÿ'NotDefined'. All other sub contexts are now handled by the new subtype in IFC2x Edition 2 IfcGeometricRepresentationSubContext. Upward compatibility for file based exchange is guaranteed. +
+ +
" +2174;IfcRepresentationContext;" + +

Definition from ISO/CD 10303-42:1992: A representation context is a context in which a set of representation items are related.

+ +

The IfcRepresentationContext defines the context to which the IfcRepresentation of a product is related.

+ +
+NOTE  The definition of this class relates to the ISO 10303 entity representation_context. Please refer to ISO/IS 10303-43:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC Release 1.5. +
+ +
+IFC2x4 CHANGE Entity made abstract, had been deprecated from instantiation since +IFC2x2. +
+ +
" +2179;IfcRepresentation;" +

+ Definition from ISO/CD 10303-43:1992: A + representation is one or more representation items that are + related in a specified representation context as the + representation of some concept. +

+

+ IfcRepresentation + defines the general concept of representing product + properties. +

+

Representation Use Definition

+

+ Each representation, either IfcShapeRepresentation, or + IfcTopologyRepresentation shall have a well defined: +

+
    +
  • + ContextOfItems: Reference to an + IfcGeometricRepresentationContext as agreed for + this representation. +
  • +
  • + RepresentationIdentifier: Name of the + representation, for example, 'Body' for 3D shape, 'FootPrint' for + 2D ground view, 'Axis' for reference axis. +
  • +
  • + RepresentationType: Name for the geometric, or + topological representation type, for example, 'SweptSolid' for 3D + swept solids, 'Brep' for boundary representation. +
  • +
+

+ Values and guidelines for these three items are provided in + the geometry use definition section at each subtype of + IfcElement, or in view definitions / implementer + agreements. +

+
+ NOTE ÿThe definition of this + entity relates to the ISO 10303 entity representation. Please + refer to ISO/IS 10303-43:1994 for the final definition of + the formal standard. +
+
+ HISTORY  New entity in IFC Release 2.0 +
+
+ IFC2x3 CHANGE  The + inverse attributes LayerAssignments + andRepresentationMap have been added with upward + compatibility. +
+
+ IFC2x4 CHANGE  Entity + IfcRepresentation has been changed into an ABSTRACT + supertype. +
+ +
" +2189;IfcStyleModel;" + +

IfcStyleModel represents the concept of a particular presentation style defined for a material (or other characteristic) of a product or a product component within a representation context. This representation context may (but has not to be) a geometric representation context.

+ +

IfcStyleModel can be a style representation (presentation style) of a material (via IfcMaterialDefinitionRepresentation), potentially differentiated for different representation contexts (for example, different material hatching depending on the scale of the target representation context).

+ +
+HISTORY  New entity in IFC2x3. +
+ +
" +2191;IfcStyledRepresentation;" + +

The IfcStyledRepresentation represents the concept of a styled presentation being a representation of a product or a product component, like material. within a representation context. This representation context does not need to be (but may be) a geometric representation context.

+ +
+NOTE  Current usage of IfcStyledRepresentation is restricted to the assignment of presentation information to an material. The IfcStyledRepresentation includes only presentation styles (IfcCurveStyle, FillAreaStyle, IfcSurfaceStyle) that define how a material should be presented within a particular (eventually view and scale dependent) representation context. All instances of IfcStyledRepresentation are referenced by IfcMaterialDefinitionRepresentation, and assigned to IfcMaterial by IfcMaterialDefinitionRepresentation.RepresentedMaterial. +
+ +

A styled representation has to include one or several styled items with the associated style information (curve, symbol, text, fill area, or surface styles). It shall not contain the geometric representation items that are styled.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +2193;IfcShapeModel;" + +

IfcShapeModel represents +the concept of a particular geometric and/or topological +representation of a product's shape or a product component's shape +within a representation context. This representation context has to +be a geometric representation context (with the exception of +topology representations without associated geometry). The two +subtypes are IfcShapeRepresentation to cover geometric +models that represent a shape, and IfcTopologyRepresentation +to cover the conectivity of a product or product component. The +topology may or may not have geometry associated.

+ +

The IfcShapeModel can be a shape representation +(geometric and/or topologogical) of a product (via +IfcProductDefinitionShape), or a shape representation +(geometric and/or topologogical)  of a component of a product +shape (via IfcShapeAspect).

+ +
+HISTORY  New entity in IFC2x3. +
+ +
" +2198;IfcShapeRepresentation;" + +

The IfcShapeRepresentation represents the concept of a +particular geometric representation of a product or a product +component within a specific geometric representation context. The +inherited attribute RepresentationType is used to define +the geometric model used for the shape representation (for example, +'SweptSolid', or 'Brep'), the inherited attribute +RepresentationIdentifier is used to denote the part of the +representation captured by the IfcShapeRepresentation +(for example, 'Axis', 'Body').

+ +

Several representation identifiers for shape representation are +included as predefined values for RepresentationIdentifier:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
BoxBounding box as simplified 3D box +geometry of an element
Annotation2D annotations not representing +elements
Axis2D or 3D Axis, or single line, +representation of an element
FootPrint2D Foot print, or double line, +representation of an element, projected to ground view
Surface3D Surface representation, e.g. of an +analytical surface, of an elementplane)
Body3D Body representation, e.g. as +wireframe, surface, or solid model, of an element
LightingRepresentation of emitting light as a +light source within a shape representation
+

Several representation types for shape representation are +included as predefined values for RepresentationType:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+Curve2D2 dimensional curve
+Curve3D3 dimensional curve
+Surface2D2 dimensional surface (a region on +ground view)
+Surface3D3 dimensional surface
+GeometricSetpoints, curves, surfaces (2 or 3 +dimensional)
+GeometricCurveSetpoints, curves (2 or 3 +dimensional)
Annotation2Dpoints, curves (2 or 3 dimensional), hatches and text (2 +dimensional)
+SurfaceModelface based and shell based surface +model
+SolidModelincluding swept solid, Boolean +results and Brep bodies
+more specific types are:
SweptSolidswept area solids, by extrusion and +revolution, excluding tapered sweeps
+AdvancedSweptSolidswept area solids created by sweeping +a profile along a directrix, and tapered sweeps
Brepfaceted Brep's with and without +voids
AdvancedBrepBrep's based on advanced faces, with +b-spline surface geometry, with and without voids
CSGBoolean results of operations between +solid models, half spaces and Boolean results
ClippingBoolean differences between swept +area solids, half spaces and Boolean results

+additional types

+some additional representation types are provided:
BoundingBoxsimplistic 3D representation by a +bounding box
+SectionedSpinecross section based representation of +a spine curve and planar cross sections. It can represent a surface +or a solid and the interpolations of the between the cross sections +is not defined
LightSourcelight source with (depending on type) +position, orientation, light colour, intensity and attenuation
+MappedRepresentationrepresentation based on mapped +item(s), referring to a representation map. Note: it can be seen as +an inserted block reference. The shape representation of the mapped +item has a representation type declaring the type of its +representation items.
+

Table 1: string values for the inherited attribute +'RepresentationType'.

+ +
+NOTE  The definition of this entity relates to the ISO 10303 entity shape_representation. Please refer to ISO/IS 10303-41:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC Release 1.5. +
+ +
+IFC2x4 CHANGE  The RepresentationType's 'Curve3D', 'Surface2D', 'Surface3D', 'AdvancedBrep', 'LightSource', and the RepresentationIdentifier 'Lighting' have been added. +
+ +
" +2203;IfcTopologyRepresentation;" +

IfcTopologyRepresentation +represents the concept of a particular topological representation of a +product or a product component within a representation context. This +representation context does not need to be (but may be) a geometric +representation context. Several representation types for shape +representation are included as predefined types:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
Vertextopological vertex +representation (with or without assigned geometry)
Edgetopological edge +representation (with or without assigned geometry)
Pathtopological path +representation (with or without assigned geometry)
Facetopological face +representation (with or without assigned geometry)
Shelltopological shell +representation (with or without assigned geometry)
Undefinedno constraints imposed
+

The representation type is +given as a string value at the inherited attribute 'RepresentationType'.
+

+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +2207;IfcShapeAspect;" +

+ Definition from ISO/CD 10303-41:1992: The shape + aspect is an identifiable element of the shape of a + product. +

+

+ IfcShapeAspect + allows for grouping of shape representation items that + represent aspects (or components) of the shape of a + product. Thereby shape representations of components of the + product shape represent a distinctive part to a product + that can be explicitly addressed.
+

+
+ NOTE ÿThe definition of + this class relates to the ISO 10303 entity shape_aspect. Please + refer to ISO/IS 10303-41:1994 for the final definition of + the formal standard. +
+
+ HISTORY  New Entity in IFC Release 2.0 +
+
+ IFC 2x4 CHANGE  Attribute + PartOfProductDefinitionShape declared OPTIONAL with + upward compatibility for file based exchange. +
+

+ Informal propositions:
+

+
    +
  1. If ShapeRepresentations points to shape + representations that are part of an + IfcProductDefinitionShape, + PartOfProductDefinitionShape must refer to this + instance of IfcProductDefinitionShape. +
    + NOTEÿ PartOfProductDefinitionShape is + only to be omitted if the shape representations are + attached to an IfcRepresentationMap. ÿThis + enables the use of IfcShapeAspect with + IfcRepresentationMap's that are used by an + IfcTypeProduct through the + RepresentationMaps attribute.
    +
    +
  2. +
+
" +2213;IfcProductDefinitionShape;" + +

The IfcProductDefinitionShape defines all shape relevant information about an IfcProduct. It allows for multiple geometric shape representations of the same product. The shape relevant information includes:

+
    +
  • the shape representation including geometric representation items (for 3D solids, 2D annotations, etc.) and: +
      +
    • associated presentation information (line color, line type, surface rendering properties)
    • +
    • assignment to presentation layers (CAD layers for visibility control)
    • +
    +
  • +
  • or the topological representation items for connectivity systems (vertex, edge, face representations) that may include geometric representation items (vertex points, edge curves, face surfaces)
  • +
+ +
+NOTE  The definition of this entity relates to the ISO 10303 entity product_definition_shape. Please refer to ISO/IS 10303-41:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New Entity in IFC Release 1.5 +
+ +
" +2217;IfcProductRepresentation;" + +

IfcProductRepresentation defines a representation of a +product, including its (geometric or topological) representation. +A product can have zero, one or many geometric representations, +and a single geometric representation can be shared among various +products using mapped representations.

+ +
+NOTE: The definition +of this entity relates to the ISO 10303 entity property_definition. +The use of the term ‘property’ was avoided since it +conflicts with the property, property type, and property set +definitions elsewhere in the IFC model. +
+ +
+HISTORY New entity in IFC Release 2.0 +
+ +
+IFC2x3 NOTE ÿUsers should not instantiate the entity from IFC2x Edition 3 onwards. +
+ +
+IFC2x4 CHANGE  Entity made abstract. +
+ +
" +2223;IfcMaterialDefinitionRepresentation;" + +

IfcMaterialDefinitionRepresentation defines presentation information relating to IfcMaterial. It allows for multiple presentations of the same material for different geometric representation contexts.

+ +
+NOTE  The IfcMaterialDefinitionRepresentation is currently only used +to define presentation information to material used at element +occurrences, defined as subtypes of IfcElement, or at +element types, defined as subtypes of IfcElementType. The +IfcMaterial is assigned to the subtype of +IfcElement, or IfcElementType using the +IfcRelAssociatesMaterial relationship (eventually via +other material related entities IfcMaterialLayerSetUsage, +IfcMaterialLayerSet, IfcMaterialLayer, or +IfcMaterialProfileSetUsage, IfcMaterialProfileSet, +IfcMaterialProfile). +
+ +

The IfcMaterialDefinitionRepresentation can apply

+
    +
  • different presentation styles for different representation contexts, for example, a different style for sketch view, model view or plan view, or for different target scales,
  • +
  • for each representation context is can apply curve style, fill area style (hatching), symbol, text and surface style.
  • +
+ +
+HISTORY  New entity in IFC2x3. +
+ +
+IFC2x3 CHANGE  The entity IfcMaterialDefinitionRepresentation has been added. Upward compatibility for file based exchange is guaranteed. +
+ +
+IFC2x4 CHANGE  The assignment of curve, surface and other styles to an IfcStyledItem has been simplified by IfcStyleAssignmentSelect. The use of intermediate IfcPresentationStyleAssignment is deprecated. +
+ +

Use definition

+ +

As shown in Figure 331, the presentation assignment can be specific to a representation context by adding one and more IfcStyledRepresentation's. Each of them includes a single IfcStyledItem with exactly zero or one style for either curve, fill area, surface, text or symbol style that is applicable.

+ + + + +

Figure 331 — Material definition representation

+ +
" +2226;IfcGeometricRepresentationSubContext;" + +

IfcGeometricRepresentationSubContext defines the context that applies to several shape representations of a product being a sub context, sharing the WorldCoordinateSystem, CoordinateSpaceDimension, Precision and TrueNorth attributes with the parent IfcGeometricRepresentationContext.

+ +

The IfcGeometricRepresentationSubContext is used to define semantically distinguished representation types for different information content, dependent on the representation view and the target scale. It can be used to control the level of detail of the shape representation that is most applicable to this geometric representation context. addition the sub context is used to control the later appearance of the IfcShapeRepresentation within a plot view.

+ +
+NOTE  If the IfcShapeRepresentation using this sub context has IfcStyledItem's assigned to the Items, the presentation style information (e.g. IfcCurveStyle, IfcTextStyle) associated with the IfcStyledItem is given in target plot dimensions. For example, a line thickness (IfcCurveStyle.CurveWidth) is given by a thickness measure relating to the thickness for a plot within the (range of) target scale. +
+ +

Each IfcProduct can then have several instances of subtypes of IfcRepresentation, each being assigned to a different geometric representation context (IfcGeometricRepresentationContext or IfcGeometricRepresentationSubContext). The application can then choose the most appropriate representation for showing the geometric shape of the product, depending on the target view and scale.

+ +
+NOTE  The provision of a model view (IfcGeometricRepresentationContext.ContextType = 'Model') is mandatory. Instances of IfcGeometricRepresentationSubContext relate to it as its ParentContext. +
+ +
+EXAMPLE  Instances of IfcGeometricRepresentationSubContext can be used to handle the multi-view blocks or macros, which are used in CAD programs to store several scale and/or view dependent geometric representations of the same object. +
+ +
+HISTORY  New entity in Release IFC 2x2. +
+ +
" +2258;IfcCoordinateReferenceSystem;" + +

Definition from OpenGIS® Abstract Specification, Topic +2: A coordinate reference system is a coordinate system which +is related to the real world by a datum. The coordinate system is +composed of a set of coordinate axes with specified units of +measure. The datum specifies the relationship of a coordinate +system to the earth. The resulting combination of coordinate +system and datum is a coordinate reference system.

+ +

IfcCoordinateReferenceSystem is a definition of a coordinate +reference system by means of qualified identifiers only. The +interpretation of the identifier is expected to be well-known to +the receiving software.

+ +
+NOTE  One widely-used, publicly-available +authority is the European Petroleum Survey Group (EPSG), and use +of this authority is currently specified in several OGC +Implementation Specifications. Software used to transport IFC +engineering models into GIS applications (and vice versa) is +expected to have knowledge about the OGC Implementation +Specifications. +
+ +
+HISTORY  New entity in IFC2x4. +
+ +
" +2264;IfcProjectedCRS;" + +

Definition from OpenGIS® Abstract Specification, + Topic 2: A 2D (or with vertical coordinate axis 3D) + coordinate reference system used to approximate the shape + of the earth on a planar surface, but in such a way that + the distortion that is inherent to the approximation is + carefully controlled and known. Distortion correction is + commonly applied to calculated bearings and distances to + produce values that are a close match to actual field + values.

+

IfcProjectedCRS is a coordinate reference system of + the map to which the map translation of the local + engineering coordinate system of the construction or + facility engineering project relates. The + MapProjection and MapZone attributes uniquely + identify the projection to the underlying geographic + coordinate reference system, provided that they are + well-known in the receiving application.

+

The projected coordinate reference system is assumed to be + a 2D or 3D right-handed Cartesian coordinate system, the + optional MapUnit attribute can be used determine the + length unit used by the map.

+ +
+ HISTORY  New entity in IFC2x4. +
+ +
" +2269;IfcCoordinateOperation;" +

+ Definition from OpenGIS® Abstract Specification, + Topic 2: If the relationship between any two coordinate + reference systems is known, coordinates can be transformed + or converted to another coordinate reference system. + Coordinate operations are divided into two subtypes: +

+
    +
  • + Coordinate conversion – mathematical + operation on coordinates that does not include any change + of datum. The best-known example of a coordinate + conversion is a map projection. The parameters describing + coordinate conversions are defined rather than + empirically derived. Note that some conversions have no + parameters. +
  • +
  • + Coordinate transformation – mathematical + operation on coordinates that usually includes a change + of datum. The parameters of a coordinate transformation + are empirically derived from data containing the + coordinates of a series of points in both coordinate + reference systems. This computational process is usually + ‘over-determined’, allowing derivation of + error (or accuracy) estimates for the transformation. + Also, the stochastic nature of the parameters may result + in multiple (different) versions of the same coordinate + transformation. Because of this several transformations + may exist for a given pair of coordinate reference + systems, differing in their transformation method, + parameter values and accuracy characteristics. +
  • +
+

+ The coordinate operation is an + abstract supertype to handle any operation (transformation + or conversion) between two coordinate reference systems. It + is meant to provide expandability for future versions, + since currently only the conversion of a local engineering + coordinate system into a map coordinate reference system is + dealt with by the subtype IfcMapConversion. +

+

+ By convention, a coordinate operation is given between the + SourceCRS being the more local, or child coordinate + reference system, and the TargetCRS being the more + remote or parent coordinate reference system, in + theÿspecial case the coordinate operation between the local + engineering coordinate system of the construction project + and any map or other coordinate reference system. +

+
+ HISTORY  New entity in IFC2x4. +
+
" +2273;IfcMapConversion;" + +

The map conversion deals with transforming the local engineering coordinate system, often called world coordinate system, into the coordinate reference system of the underlying map.

+ +
+NOTE  The IfcMapConversion does not handle the projection of a map from the geodetic coordinate reference system. +
+ +

The map conversion allows to convert the local origin of the local engineering coordinate system to its place within a map (easting, northing, orthogonal height) and to rotate the x-axis of the local engineering coordinate system within the horizontal (easting/westing) plane of the map.

+ +
+NOTE  The z axis of the local engineering coordinate system is always parallel to the z axis of the map coordinate system. +
+ +

The scale factor can be used when the length unit for the 3 axes of the map coordinate system are not identical with the length unit established for this project (seeÿIfcProject.UnitsInContext), if omitted, the scale factor 1.0 is assumed.

+ +
+HISTORY  New entity in IFC2x4. +
+ +
" +2281;IfcStructuralLoadOrResult;" + +

Definition from IAI: Abstract superclass of simple load or result classes.

+ +
HISTORY: New abstract superclass in IFC 2x4, upwards compatibility of all subtypes is preserved.
+ +
" +2284;IfcStructuralLoad;" + +

Definition from IAI: The abstract entity IfcStructuralLoadOrResult is the supertype of all loads (actions or reactions) or of certain requirements resulting from structural analysis, or certain provisions which influence structural analysis.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2288;IfcStructuralLoadConfiguration;" + +

Definition from IAI: This class combines one or more load or result values in a 1- or 2-dimensional configuration.

+ +
HISTORY: New entity in IFC 2x4.
+ +

Informal propositions:

+ +
    +
  1. All items in Values shall be of the same type.
  2. +
  3. If the loads or results comprise a curve activity, 1-dimensional locations shall be given, measured locally along the curve. The location shall not exceed the bounds of the curve actvity. The load samples and corresponding locations shall be given in ascending order of locations.
  4. +
  5. If the loads or results comprise a surface activity, 2-dimensional locations shall be given, measured in the surface activity's local x and y directions. The location shall not exceed the bounds of the surface activity.
  6. +
+ +
NOTE  There are no ordering requirements in the 2-dimensional case, but the 1-dimensional case shall be spatially ordered for simplicity.
+ +
" +2293;IfcStructuralLoadStatic;" + +

Definition from IAI: The abstract entity IfcStructuralLoadStatic is the supertype of all static loads (actions or reactions) which can be defined. Within scope are single i.e. concentrated forces and moments, linear i.e. one-dimensionally distributed forces and moments, planar i.e. two-dimensionally distributed forces, furthermore displacements and temperature loads.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2299;IfcStructuralLoadSingleForce;" + +

Definition from IAI: Instances of the entity + IfcStructuralLoadSingleForce shall be used to define the forces and + moments of an action operating on a single point.

+
+

HISTORY: New entity in Release IFC2x + edition 2.

+ +
" +2307;IfcStructuralLoadSingleForceWarping;" + +

Definition from IAI: Instances of the entity + IfcStructuralLoadSingleForceWarping, as a subtype of + IfcStructuralLoadSingleForce, shall be used to define an action operation + on a single point. In addition to forces and moments defined by its supertype a + warping moment can be defined.

+
+

HISTORY: New entity in Release IFC2x + edition 2.

+ +
" +2309;IfcStructuralLoadLinearForce;" + +

Definition from IAI: An instance of the entity + IfcStructuralLoadLinearForce shall be used to define actions on curves. +

+
+

HISTORY: New entity in Release IFC2x + edition 2.

+ +
" +2316;IfcStructuralLoadPlanarForce;" + +

Definition from IAI: An instance of the entity + IfcStructuralLoadPlanarForce shall be used to define actions on faces. +

+
+

HISTORY: New entity in Release IFC2x + edition 2.

+ +
" +2320;IfcStructuralLoadSingleDisplacement;" + +

Definition from IAI: Instances of the entity + IfcStructuralLoadSingleDisplacement shall be used to define displacements.

+
+

HISTORY: New entity in Release IFC2x + edition 2.

+ +
" +2328;IfcStructuralLoadSingleDisplacementDistortion;" + +

Definition from IAI: Defines a displacement with warping.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2330;IfcStructuralLoadTemperature;" + +

An instance of the entity IfcStructuralLoadTemperature shall be used to define actions which are caused by a temperature change. As shown in Figure 332, the change of temperature is given with a constant value which is applied to the complete section and values for temperature differences between outer fibres of the section.

+ +
HISTORY  New entity in IFC2x2.
+ + + + +

Figure 332 — Structural load temperature

+ +
" +2334;IfcSurfaceReinforcementArea;" + +

Definition from IAI: Describes required or provided reinforcement area of surface members.

+ +
NOTE  Member design parameters like concrete cover, effective depth, orientation of meshes or rebars (two, optionally three directions) etc. are not specified in IfcStructuralLoadResource schema. They shall be specified at the level of structural members.
+ +
HISTORY: New entity in IFC 2x4.
+ +
" +2342;IfcBoundaryCondition;" +

Definition +from IAI: The abstract entity IfcBoundaryCondition +is the supertype of all boundary conditions that can be applied to +structural connection definitions, either directly for the connection +(e.g. the joint) or for the relation between a structural member and +the connection.

+
NOTE: The boundary conditions are used +within other parts, mainly by instances of IfcStructuralConnection +(for the definition of supports) and instances of IfcRelConnectsStructuralMember +(for the definition of connections between structural members and +structural connections).
+
+

HISTORY: New entity +in Release IFC2x Edition +2.

+
+
" +2347;IfcBoundaryNodeCondition;" + +

Definition from IAI: Describes linearly elastic support conditions or connection conditions.

+ +

Applicability:

+
    +
  • Point supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Attributes LinearStiffnessX/Y/Z renamed to TranslationalStiffnessX/Y/Z.
+ +
IFC 2x4 change: All attribute data types changed from numeric to SELECT between Boolean and numeric. Stiffnesses may now also be negative, for example to capture destabilizing effects in boundary conditions. The IFC 2x3 convention of -1. representing infinite stiffness is no longer valid and must not be used. Infinite stiffness, i.e. fixed supports, are now modeled by the Boolean value TRUE.
+ +
" +2355;IfcBoundaryNodeConditionWarping;" + +

Definition from IAI: Describes linearly elastic support conditions or connection conditions, including linearly elastic warping restraints.

+ +

Applicability:

+
    +
  • Point supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+ +
IFC 2x4 change: All attribute data types changed from numeric to SELECT between Boolean and numeric. Stiffnesses may now also be negative, for example to capture destabilizing effects in boundary conditions. The IFC 2x3 convention of -1. representing infinite stiffness is no longer valid and must not be used. Infinite stiffness, i.e. fixed supports, are now modeled by the Boolean value TRUE.
+ +
" +2366;IfcBoundaryEdgeCondition;" + +

Definition from IAI: Describes linearly elastic support conditions or connection conditions.

+ +

Applicability:

+
    +
  • Curve supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Attributes LinearStiffnessX/Y/Z renamed to TranslationalStiffnessX/Y/Z.
+ +
IFC 2x4 change: All attribute data types changed from numeric to SELECT between Boolean and numeric. Stiffnesses may now also be negative, for example to capture destabilizing effects in boundary conditions. The IFC 2x3 convention of -1. representing infinite stiffness is no longer valid and must not be used. Infinite stiffness, i.e. fixed supports, are now modeled by the Boolean value TRUE.
+ +
" +2379;IfcBoundaryFaceCondition;" + +

Definition from IAI: Describes linearly elastic support conditions or connection conditions.

+ +

Applicability:

+
    +
  • Surface supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+IFC 2x4 change: Attributes LinearStiffnessX/Y/Z renamed to TranslationalStiffnessX/Y/Z.
+ +
IFC 2x4 change: All attribute data types changed from numeric to SELECT between Boolean and numeric. Stiffnesses may now also be negative, for example to capture destabilizing effects in boundary conditions. The IFC 2x3 convention of -1. representing infinite stiffness is no longer valid and must not be used. Infinite stiffness, i.e. fixed supports, are now modeled by the Boolean value TRUE.
+ +
" +2386;IfcSlippageConnectionCondition;" + +

Definition from IAI: Describes slippage in support conditions or connection conditions. Slippage means that a relative displacement may occur in a support or connection before support or connection reactions are awoken.

+ +

Applicability:

+
    +
  • Point supports and connections,
  • +
  • curve supports and connections,
  • +
  • surface supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2390;IfcStructuralConnectionCondition;" + +

Definition from IAI: Describe more rarely needed connection properties.

+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2394;IfcFailureConnectionCondition;" + +

Definition from IAI: Defines forces at which a support or connection fails.

+ +

Applicability:

+
    +
  • Point supports and connections.
  • +
+ +
HISTORY: New entity in IFC 2x2.
+ +
" +2402;IfcClosedShell;" +

Definition from ISO/CD 10303-42:1992: A closed shell is a shell + of the dimensionality 2 which typically serves as a bound for a region in R3. A + closed shell has no boundary, and has non-zero finite extent. If the shell has + a domain with coordinate space R3, it divides that space into two connected + regions, one finite and the other infinite. In this case, the topological + normal of the shell is defined as being directed from the finite to the + infinite region.

+

The shell is represented by a collection of faces. The domain of the + shell, if present, contains all those faces, together with their bounds. + Associated with each face in the shell is a logical value which indicates + whether the face normal agrees with (TRUE) or is opposed to (FALSE) the shell + normal. The logical value can be applied directly as a BOOLEAN attribute of an + oriented face, or be defaulted to TRUE if the shell boundary attribute member + is a face without the orientation attribute.

+

The combinatorial restrictions on closed shells and geometrical + restrictions on their domains are designed to ensure that any domain associated + with a closed shell is a closed, orientable manifold. The domain of a closed + shell, if present, is a connected, closed, oriented 2-manifold. It is always + topologically equivalent to an H-fold torus for some H + ³ 0. The number H is referred to as the + surface genus of the shell. If a shell of genus H has a domain within + coordinate space R3, then the finite region of space inside + it is topologically equivalent to a solid ball with H tunnels drilled + through it.

+

The Euler equation (7) applies with B=0, because in this case + there are no holes. As in the case of open shells, the surface genus H + may not be known a priori, but shall be an integer ³ 0. Thus a necessary, but not sufficient, condition + for a well-formed closed shell is the following:

+

+

In the current IFC Release only poly loops + (IfcPolyLoop) are defined for bounds of face bound + (IfcFaceBound). This will allow for faceted B-rep only.

+ +
+NOTE: Corresponding ISO 10303 entity: closed_shell, please refer to ISO/IS 10303-42:1994, p.149 for the final definition of the formal standard. +
+
+HISTORY  New class in IFC Release 1.0 +
+ +

Informal propositions:

+
    +
  1. Every edge shall be referenced exactly twice by the loops of the face.
  2. +
  3. Each oriented edge shall be unique.
  4. +
  5. No edge shall be referenced by more than two faces.
  6. +
  7. Distinct faces of the shell do not intersect, but may share edges or vertices.
  8. +
  9. Distinct edges do not intersect but may share vertices.
  10. +
  11. Each face reference shall be unique.
  12. +
  13. The loops of the shell shall not be a mixture of poly loop and other loop types. Note: this is given, since only poly loop is defined as face bound definition.
  14. +
  15. The closed shell shall be an oriented arcwise connected 2-manifold.
  16. +
  17. The Euler equation shall be satisfied. Note: Please refer to ISO/IS + 10303-42:1994, p.149 for the equation.
  18. +
+
" +2403;IfcConnectedFaceSet;" + +

Definition from ISO/CD 10303-42:1992: A connected_face_set is a set of faces such that the domain of faces together with their bounding edges and vertices is connected.

+ +
+NOTE  Corresponding ISO 10303 entity: connected_face_set, the subtype closed_shell is included as IfcClosedShell and the subtype open_shell is included as IfcOpenShell. Please refer to ISO/IS 10303-42:1994, p. 144 for the final definition of the formal standard. +
+ +
+HISTORY  New class in IFC Release 1.0 +
+ +

Informal proposition:

+
    +
  1. The union of the domains of the faces and their bounding loops shall be arcwise connected.
  2. +
+ +
" +2407;IfcTopologicalRepresentationItem;" + +

Definition from ISO/CD 10303-42:1992: The topological representation item is the supertype for all the topological representation items in the geometry resource.

+ +
+NOTE  Corresponding ISO 10303 entity: topological_representation_item. Please refer to ISO/IS 10303-42:1994, p.129 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 1.5 +
+ +
" +2415;IfcEdge;" +

Definition from ISO/CD 10303-42:1992: An edge is the +topological construct corresponding to the connection of two +vertices. More abstractly, it may stand for a logical +relationship between two vertices. The domain of an edge, if +present, is a finite, non-self-intersecting open curve in +RM, that is, a connected 1-dimensional +manifold. The bounds of an edge are two vertices, which need not +be distinct. The edge is oriented by choosing its traversal +direction to run from the first to the second vertex. If the two +vertices are the same, the edge is a self loop. The domain of the +edge does not include its bounds, and 0 ≤ Ξ ≤ ∞. +Associated with an edge may be a geometric curve to locate the +edge in a coordinate space; this is represented by the edge curve +(IfcEdgeCurve) subtype. The curve shall be finite and +non-self-intersecting within the domain of the edge. An edge is a +graph, so its multiplicity M and graph genus Ge +may be determined by the graph traversal algorithm. Since +M = E = 1, the Euler equation (1) reduces in the +case to

+
+

+
+

where V = 1 or 2, and Ge = 1 or 0. +Specifically, the topological edge defining data shall +satisfy:

+
+
- an edge has two vertices +
+
+
+
+
- the vertices need not be distinct +
+
+
+
+
- Equation (2) shall hold. +
+
+
+
+
+

The geometry between the two +vertices defaults to a straight line if no curve geometry is +assigned using the subtype IfcEdgeCurve. The +IfcEdge can therefore be used to exchange straight edges +without an associated geometry provided by IfcLine or +IfcPolyline thought IfcEdgeCurve.EdgeGeometry.

+ +

Figure 333 illustrates an example where the bounds of the IfcEdge are given by the EdgeStart and EdgeEnd; this also determines the direction of the edge. The location within a coordinate space is determined by the IfcVertexPoint type for EdgeStart and EdgeEnd. Since no edge geometry is assigned, it defaults to a straight line agreeing to the direction sense.

+ + + + +

Figure 333 — Edge representation

+ +
+NOTE  Corresponding ISO 10303 entity: edge. Please refer to ISO/IS 10303-42:1994, p. 130 for the final definition of the formal standard. +
+ +
+HISTORY  New Entity in IFC Release 2.0 +
+ +

Informal propositions:

+
    +
  1. The edge has dimensionality 1.
  2. +
  3. The extend of an edge shall be finite and nonzero.
  4. +
+ +
" +2421;IfcOrientedEdge;" + +

Definition from ISO/CD 10303-42:1992: An oriented edge is an edge constructed from another edge and contains a BOOLEAN direction flag to indicate whether or not the orientation of the constructed edge agrees with the orientation of the original edge. Except for perhaps orientation, the oriented edge is equivalent to the original edge.

+ +
+NOTE  A common practice is solid modelling systems is to have an entity that represents the ""use"" or ""traversal"" of an edge. This ""use"" entity explicitly represents the requirement in a manifold solid that each edge must be traversed exactly twice, once in each direction. The ""use"" functionality is provided by the edge subtype oriented edge. +
+ +
+NOTE  Corresponding ISO 10303 entity: oriented_edge. Please refer to ISO/IS 10303-42:1994, p. 133 for the final definition of the formal standard. +
+ +
+HISTORY  New Entity in IFC Release 2.0. +
+ +
" +2427;IfcVertex;" + +

Definition from ISO/CD 10303-42:1992: A vertex is the topological construct corresponding to a point. It has dimensionality 0 and extent 0. The domain of a vertex, if present, is a point in m dimensional real space RM; this is represented by the vertex point subtype.

+ +
+NOTE  Corresponding ISO 10303 entity: vertex. Please refer to ISO/IS 10303-42:1994, p. 129 for the final definition of the formal standard. +
+ +
+HISTORY  New Entity in IFC Release 2.0 +
+ +

Informal proposition:

+
    +
  1. The vertex has dimensionality 0. This is a fundamental property of the vertex.
  2. +
  3. The extent of a vertex is defined to be zero.
  4. +
+ +
" +2429;IfcVertexPoint;" + +

Definition from ISO/CD 10303-42:1992: A vertex point is a vertex which has its geometry defined as a point.

+ +
+NOTE  Corresponding ISO 10303 entity: vertex_point. Please refer to ISO/IS 10303-42:1994, p. 130 for the final definition of the formal standard. Due to the general IFC model specification rule not to use multiple inheritance, the subtype relationship to geometric_representation_item is not included. +
+ +
+HISTORY  New Entity in IFC2x. +
+ +

Informal proposition:

+
    +
  1. The domain of the vertex is formally defined to be the domain of its vertex point.
  2. +
+ +" +2431;IfcEdgeCurve;" + +

Definition from ISO/CD 10303-42:1992: An edge curve is +a special subtype of edge which has its geometry fully defined. +The geometry is defined by associating the edge with a curve +which may be unbounded. As the topological and geometric +directions may be opposed, an indicator (same sense) is used to +identify whether the edge and curve directions agree or are +opposed. The Boolean value indicates whether the curve direction +agrees with (TRUE) or is in the opposite direction (FALSE) to the +edge direction. Any geometry associated with the vertices of the +edge shall be consistent with the edge geometry. Multiple edges +can reference the same curve.

+ +

Figure 334 illustrates an example where the edge geometry is given by an unbounded curve, here IfcCircle. The bounds are provided by the EdgeStart and EdgeEnd, the topological direction of the IfcEdgeCurve opposes the direction of the IfcCircle by SameSense = FALSE.

+ + + + +

Figure 334 — Edge curve

+ +
+NOTE  Corresponding ISO 10303 entity: edge_curve. Please refer to ISO/IS 10303-42:1994, p. 132 +for the final definition of the formal standard. Due to the general IFC model specification rule not to use multiple inheritance, the subtype relationship to geometric_representation_item is not included. +
+ +
+ +

Informal propositions:

+
    +
  1. The domain of the edge curve is formally defined to be the +domain of its edge geometry as trimmed by the vertices. This +domain does not include the vertices.
  2. +
  3. An edge curve has non-zero finite extent.
  4. +
  5. An edge curve is a manifold.
  6. +
  7. An edge curve is arcwise connected.
  8. +
  9. The edge start is not a part of the edge domain.
  10. +
  11. The edge end is not a part of the edge domain.
  12. +
  13. Vertex geometry shall be consistent with edge geometry.
  14. +
+ +" +2434;IfcSubedge;" + +

Definition from ISO/DIS 10303-42:1999(E): A subedge is an edge whose domain is a connected portion of the domain of an existing edge. The topological constraints on a subedge are the same as those on an edge.

+ +

Informal propositions:

+
    +
  1. The domain of the subedge is formally defined to be the domain of the parent edge, as trimmed by the subedge start vertex and subedge end vertex.
  2. +
  3. The start vertex and end vertex shall be within the union of the domains of the vertices of the parent edge and the domain of the parent edge.
  4. +
+ +
+NOTE  Corresponding ISO 10303 entity: subedge. Please refer to ISO/DIS 10303-42:1999(E), p. 194 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +2436;IfcFace;" +

Definition from ISO/CD 10303-42:1992: A face is a topological + entity of dimensionality 2 corresponding to the intuitive notion of a piece of + surface bounded by loops. Its domain, if present, is an oriented, connected, + finite 2-manifold in Rm. A face domain shall not have handles + but it may have holes, each hole bounded by a loop. The domain of the + underlying geometry of the face, if present, does not contain its bounds, and 0 + < Ξ < ∞.

+

A face is represented by its bounding loops, which are defined as face + bounds. A face has a topological normal n and the tangent to a loop is t. For a + loop bounding a face with defined geometry, the cross product n x t points + toward the interior of the face. That is, each loop runs counter-clockwise + around the face when viewed from above, if we consider the normal n to point + up. With each loop is associated a BOOLEAN flag to signify whether the loop + direction is oriented with respect to the face normal (TRUE) or should be + reversed (FALSE).

+

A face shall have at least one bound, and the loops shall not intersect. + One loop is optionally distinguished as the outer loop of the face. If so, it + establishes a preferred way of embedding the face domain in the plane, in which + the other bounding loops of the face are inside the outer bound. Because the + face domain is arcwise connected, no inner loop will contain any other loop. + This is true regardless of which embedding in the plane is chosen.

+

The edges and vertices referenced by the loops of a face form a graph, + of which the individual loops are the connected components. The Euler equation + (1) for this graph becomes:

+
+
+

+

where Gli is the graph genus of the + i th loop.

+
+ NOTE  Corresponding ISO 10303 entity: face. No subtypes of face have been incorporated + into this IFC Release. Please refer to ISO/IS 10303-42:1994, p. 140 for the + final definition of the formal standard. The WR1 has not been incorporated, + since it is always satisfied, due to the fact that only poly loops exist for + face bounds. +
+
+ HISTORY  New class in IFC Release 1.0 +
+

Informal propositions:

+
    +
  1. No edge shall be referenced by the face more than twice.
  2. +
  3. Distinct face bounds of the face shall have no common vertices.
  4. +
  5. If geometry is present, distinct loops of the same face shall not + intersect.
  6. +
  7. The face shall satisfy the Euler Equation: (number of vertices) - + (number of edges) - (number of loops) + (sum of genus for loops) = 0.
  8. +
+
" +2440;IfcFaceSurface;" +

Definition from ISO/CD 10303-42:1992: A face surface + (IfcFaceSurface) is a subtype of face in which the geometry is defined by an + associated surface. The portion of the surface used by the face shall be + embeddable in the plane as an open disk, possibly with holes. However, the + union of the face with the edges and vertices of its bounding loops need not be + embeddable in the plane. It may, for example, cover an entire sphere or torus. + As both a face and a geometric surface have defined normal directions, a + BOOLEAN flag (the orientation attribute) is used to indicate whether the + surface normal agrees with (TRUE) or is opposed to (FALSE) the face normal + direction. The geometry associated with any component of the loops of the face + shall be consistent with the surface geometry, in the sense that the domains of + all the vertex points and edge curves are contained in the face geometry + surface. A surface may be referenced by more than one face surface.

+
+ NOTE  Corresponding ISO 10303 entity: + face_surface. Please refer to ISO/IS 10303-42:1994, p. 204 for the final + definition of the formal standard. Due to the general IFC model specification + rule not to use multiple inheritance, the subtype relationship to + geometric_representation_item is not included. +
+
+ HISTORY  New class in IFC2x +
+

Informal propositions:

+
    +
  1. The domain of the face surface is formally defined to be the domain + of its face geometry as trimmed by the loops, this domain does not include the + bounding loops.
  2. +
  3. A face surface has non zero finite extent.
  4. +
  5. A face surface is a manifold.
  6. +
  7. A face surface is arcwise connected.
  8. +
  9. A face surface has surface genus 0.
  10. +
  11. The loops are not part of the face domain.
  12. +
  13. Loop geometry shall be consistent with face geometry. This implies + that any edge - curves or vertex points used in defining the loops bounding the + face surface shall lie on the face geometry.
  14. +
  15. The loops of the face shall not intersect.
  16. +
+
" +2444;IfcAdvancedFace;" + +

An advanced face is a specialization of a face surface that has to meet requirements on using particular topological and geometric representation items for the definition of the faces, edges and vertices.

+ +

An IfcAdvancedFace is restricted to:

+
    +
  • have a face surface geometry of type IfcElementarySurface, IfcSweptSurface or IfcBSplineSurface
  • +
  • have at least on IfcFaceOuterBound as the bound of the face
  • +
  • have all faces to be bound by IfcEdgeLoop or IfcVertexLoop
  • +
  • have all edges to have an edge curve geometry
  • have the edge curve geometry restricted to IfcLine, IfcConic, IfcPolyline, or IfcBSplineCurve
  • +
+ +
+NOTE  Corresponding ISO 10303 entity: advanced_face. Please refer to ISO/IS 10303-511:1999 for +the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x4 +
+ +
" +2448;IfcFaceBound;" + +

Definition from ISO/CD 10303-42:1992: A face bound is a loop which is intended to be used for bounding a face.

+ +
+NOTE  Corresponding ISO 10303 entity: face_bound. Please refer to ISO/IS 10303-42:1994, p. 139 for the final definition of the formal standard. +
+ +
+HISTORY  New class in IFC Release 1.0 +
+ +
" +2452;IfcFaceOuterBound;" + +

Definition from ISO/CD 10303-42:1992: A face outer bound is a special subtype of face bound which carries the additional semantics of defining an outer boundary on the face. No more than one boundary of a face shall be of this type.

+ +
+NOTE Corresponding ISO 10303 entity: face_outer_bound. Please refer to ISO/IS 10303-42:1994, p. 139 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +
" +2453;IfcLoop;" +

Definition from ISO/CD 10303-42:1992: A loop is a topological + entity constructed from a single vertex, or by stringing together connected + (oriented) edges, or linear segments beginning and ending at the same vertex. + It is typically used to bound a face lying on a surface. A loop has + dimensionality of 0 or 1. The domain of a 0-dimensional loop is a single point. + The domain of a 1-dimensional loop is a connected, oriented curve, but need not + to be manifold. As the loop is a circle, the location of its beginning/ending + point is arbitrary. The domain of the loop includes its bounds, an 0 ≤ Ξ + < ∞.

+

A loop is represented by a single vertex, or by an ordered collection of + oriented edges, or by an ordered collection of points. A loop is a graph, so + M and the graph genus Gl may be determined by the + graph traversal algorithm. Since M = 1, the Euler equation (1) reduces + in this case to

+
+
+

where V and El are the number of unique + vertices and oriented edges in the loop and Gl is the genus + of the loop.

+
NOTE  Corresponding ISO 10303 entity: loop, the following subtypes have been incorporated into IFC: poly_loop as IfcPolyLoop, vertex_loop as IfcVertexLoop, edge_loop as IfcEdgeLoop. Please refer to ISO/IS 10303-42:1994, p. 136 for the final definition of the formal standard.
+
+ HISTORY  New Entity in IFC2x.
+

Informal propositions:

+
    +
  1. A loop has a finite extent.
  2. +
  3. A loop describes a closed (topological) curve with coincident start + and end vertices.
  4. +
+
" +2457;IfcPolyLoop;" +

Definition from ISO/CD 10303-42:1992: A +poly loop is a loop with straight edges bounding a planar region in +space. A poly loop is a loop of genus 1 where the loop is represented +by an ordered coplanar collection of points forming the vertices of the +loop. The loop is composed of straight line segments joining a point in +the collection to the succeeding point in the collection. The closing +segment is from the last to the first point in the collection. 

+

The direction of the loop is in the direction of the line +segments.

+ +
+NOTE  This entity exists primarily to facilitate the efficient communication of faceted B-rep models. +
+ +

A poly loop shall conform to the following topological +constraints:

+
+
- the loop has the genus of one.
+
- the following equation shall be satisfied +
+
+
+
+
+

The IfcPolyLoop +is always closed and the last segment is from the last IfcCartesianPoint +in the list of Polygon's to the first IfcCartesianPoint. +Therefore the first point shall not be repeated at the end of the list, +neither by referencing the same instance, nor by using an additional +instance of IfcCartesianPoint having the +coordinates as the first point.

+ +
+NOTE  Corresponding ISO 10303 entity: poly_loop. Please refer to ISO/IS +10303-42:1994, p. 138 for the final definition of the formal standard. +Due to the general IFC model specification rule not to use multiple +inheritance, the subtype relationship to geometric_representation_item +is not included. The derived attribute Dim has been +added at this level. +
+ +
+HISTORY   New class in IFC Release 1.0 +
+ +

Informal propositions:

+
    +
  1. All the points in the polygon defining the poly loop shall be coplanar.
  2. +
  3. The first and the last Polygon shall be different by value.
  4. +
+ +
" +2460;IfcVertexLoop;" +

Definition from ISO/CD 10303-42:1992: A vertex_loop is a loop of + zero genus consisting of a single vertex. A vertex can exist independently of a + vertex loop. The topological data shall satisfy the following constraint:

+
+
+

Informal propositions:

+
    +
  1. A vertex loop has zero extent and dimensionality.
  2. +
  3. The vertex loop has genus 0.
  4. +
+
+NOTE  Corresponding ISO 10303 entity: vertex_loop. Please refer to ISO/IS 10303-42:1994, p. 121 for the final definition of the formal standard. +
+
+HISTORY  New Entity in IFC2x2. +
+ +
" +2462;IfcEdgeLoop;" + +

Definition from ISO/CD 10303-42:1992: An edge_loop is a loop with nonzero extent. It is a path in which the start and end vertices are the same. Its domain, if present, is a closed curve. An edge_loop may overlap itself.

+ +

Informal propositions:

+
    +
  1. The genus of the IfcEdgeLoop shall be 1 or greater.
  2. +
  3. The Euler formula shall be satisfied:
    (number of vertices) + genus - (number of edges) = 1;
  4. +
  5. No edge may be referenced more than once by the same IfcEdgeLoop with the same sense. For this purpose, an edge which is not an oriented edge is considered to be referenced with the sense TRUE.
  6. +
+
+NOTE  Corresponding ISO 10303 entity: edge_loop. Please refer to ISO/IS 10303-42:1994, p. 122 for the final definition of the formal standard. +
+
+HISTORY  New Entity in IFC2x2. +
+ +
" +2467;IfcPath;" + +

Definition from ISO/CD 10303-42:1992: A path is a topological entity consisting of an ordered collection of oriented edges, such that the edge start vertex of each edge coincides with the edge end of its predecessor. The path is ordered from the edge start of the first oriented edge to the edge end of the last edge. The BOOLEAN value sense in the oriented edge indicates whether the edge direction agrees with the direction of the path (TRUE) or is the opposite direction (FALSE).

+ +

An individual edge can only be referenced once by an individual path. An edge can be referenced by multiple paths. An edge can exist independently of a path.

+ +
+NOTE  Corresponding ISO 10303 entity: path. Please refer to ISO/IS 10303-42:1994, p. 133 for the final definition of the formal standard. +
+ +
+HISTORY  New Entity in IFC Release 2.0 +
+ +

Informal proposition:

+
    +
  1. A path has dimensionality 1.
  2. +
  3. A path is arcwise connected.
  4. +
  5. The edges of the path do not intersect except at common vertices.
  6. +
  7. A path has a finite, non-zero extent.
  8. +
+ +
" +2470;IfcOpenShell;" +

Definition from ISO/CD 10303-42:1992: An open shell is a shell of + the dimensionality 2. Its domain, if present, is a finite, connected, oriented, + 2-manifold with boundary, but is not a closed surface. It can be thought of as + a closed shell with one or more holes punched in it. The domain of an open + shell satisfies 0 + < Ξ < 1. An open shell is + functionally more general than a face because its domain can have handles.

+

The shell is defined by a collection of faces, which may be oriented + faces. The sense of each face, after taking account of the orientation, shall + agree with the shell normal as defined below. The orientation can be supplied + directly as a BOOLEAN attribute of an oriented face, or be defaulted to TRUE if + the shell member is a face without the orientation attribute.

+

The following combinatorial restrictions on open shells and geometrical + restrictions on their domains are designed, together with the informal + propositions, to ensure that any domain associated with an open shell is an + orientable manifold.

+
    +
  • Each face reference shall be unique.
  • +
  • An open shell shall have at least one face.
  • +
  • A given face may exist in more than one open shell.
  • +
+

The boundary of an open shell consists of the edges that are referenced + only once by the face - bounds (loops) of its faces, together with all of their + vertices. The domain of an open shell, if present, contains all edges and + vertices of its faces.

+
+ NOTE  Note that this is slightly different from the + definition of a face domain, which includes none of its bounds. For example, a + face domain may exclude an isolated point or line segment. An open shell domain + may not. (See the algorithm for computing below.)
+

In the current IFC Release only poly loops + (IfcPolyLoop) are defined for bounds of face bound + (IfcFaceBound.Bound). This will allow for faceted B-rep only. For + further specification, including the Euler formulas to be satisfied, please + refer to ISO 10303-42:1994.

+
+ NOTE  Corresponding ISO 10303 entity: + open_shell, please refer to ISO/IS 10303-42:1994, p.148 for the final + definition of the formal standard. +
+
+ HISTORY  New class in IFC2x. +
+

Informal propositions:

+
    +
  1. Every edge shall be referenced exactly twice by the face bounds of + the face.
  2. +
  3. Each oriented edge shall be unique.
  4. +
  5. No edge shall be referenced by more than two faces.
  6. +
  7. Distinct faces of the shell do not intersect, but may share edges or + vertices.
  8. +
  9. Distinct edges do not intersect but may share vertices.
  10. +
  11. Each face reference shall be unique.
  12. +
  13. The loops of the shell shall not be a mixture of poly loop and other + loop types. Note: this is given, since only poly loop is defined as face bound + definition.
  14. +
  15. The closed shell shall be an oriented arcwise connected 2-manifold. +
  16. +
  17. The Euler equation shall be satisfied. Note: Please refer to ISO/IS + 10303-42:1994, p.148 for the equation.
  18. +
+
" +2478;IfcTask;" +

+ An IfcTask is an identifiable unit of work to be + carried out in a construction project. +

+

+ A task is typically used to describe an activity for the + construction or installation of products, but is not + limited to these types. For example it might be used to + describe design processes, move operations and other + design, construction and operation related activities as + well. +

+
+ HISTORY  New entity in IFC 1.0. Renamed from IfcWorkTask in IFC 2x. +
+
+IFC2x4 CHANGE  Attributes TaskTime and PredefinedType added. IfcMove and IfcOrderRequest has been removed in IFC2x4 and are now represented by IfcTask. Further information can be found in the description below. +
+

Type use definition

+

+ IfcTask defines the anticipated or actual occurrence + of any task; common information about task types is handled + by IfcTaskType. The IfcTaskType (if present) + may establish the common type name, usage (or predefined) + type, common set of properties, and common product + assignment using IfcRelAssignsToProduct. The + IfcTaskType is attached using the + IfcRelDefinesByType.RelatingType objectified + relationship and is accessible by the inverse + IsTypedBy attribute. Special type information + relating to a task occurrence is asserted using + IfcTask.ObjectType (inherited from + IfcObject). Examples that may be used include fixed + duration, fixed unit or fixed work. IfcTask can be + aggregated to a task type in order to specify a task + sequence or any time related information, e.g. the duration + of a task. Please see the documentation of + IfcTaskType for further information. +

+

Attribute use definition

+

+ Each occurrence of IfcTask is given a name that is + indicative of its content (IfcRoot.Name). A textual + description of the task may be provided and this may be + further elaborated by a narrative long description + (IfcProcess.LongDescription). A work method may be + declared for the method of work used in carrying out a + task. A task is identified as being either a milestone task + or not. A milestone task is defined by the marker + IsMilestone. and has no duration. A status and + priority for each task may also be set. +

+

Property set use definition

+

+ The property sets relating to IfcTask are defined by + IfcPropertySet and attached by the + IfcRelDefinesByProperties relationship. They are + accessible by the inverse IsDefinedBy relationship. + Such property sets may define task parameters. No property + sets for IfcTask are currently defined by IFC. +

+

Connectivity Use Definition

+

+ The relationship IfcRelSequence is used to indicate + control flow. An IfcTask as a successor to an + IfcTask indicates logical sequence how these tasks + should be performed. IfcTask's can be triggered or + can trigger IfcEvent's, which is also defined + through the relationship IfcRelSequence. +

+

Composition use definition

+

+ IfcTask may be contained within an IfcTask + using the IfcRelNests relationship. An + IfcTask may in turn nest other IfcTask, + IfcProcedure or IfcEvent entities. Such + nesting indicates decomposed level of detail. From IFC2x4 + onwards it is required to have a summary task (root of all + tasks), which is used to define a link to the work plan or + work schedule. All subtasks of the summary tasks are then + implicitly linked to this work plan or work schedule. + Please note that the summary task is used for data + organization and not meant to store typical task + information as defined by the user. It is therefore + recommended that the summary task is hidden from the user + to avoid confusion. Please also note that + IfcRelNests is used to show the dependency between + regular tasks and recurring task definitions (please see + the section about time and duration use definitions). +

+ +

+ As shown in Figure 13, the installation of a number of items of equipment within a + particular space may be the subject of a single task which + is identified as 'fix equipment in space 123'. + IfcTask represents the occurrence of a work + performance of a type of process in a construction plan. +

+ + +
+

Figure 13 — Task visualization

+

+ A task may nest other tasks as sub-items; the nesting + relationship is modeled by IfcRelNests as shown in Figure 14. For example, + the construction of a stud wall may be designated as a + nesting task named 'install wall #1' including other tasks + such as 'install dry wall', 'install studs', 'wall taping', + and 'erect wall' as sub-processes. A value that indicates + the relative tree view position of the task (in comparison + to the tree view position of other tasks and the task + hierarchy defined by IfcRelNests). +

The task order information that is used for viewing + purposes is derived from the order defined by the + IfcRelNests relationship and thus is independent of + the logical task order defined through + IfcRelSequence. The hierarchy and order defined + through IfcRelNests enables to order the tasks in a + tree view or list view structure. +

+ + + +

Figure 14 — Task nesting relationships

+ +

+

Time and duration use definition

+

+ Compared to previous IFC releases, basic task time + information (scheduled start time, scheduled finish + time, duration) is now directly attached to IfcTask + through the TaskTime attribute. Regular tasks are + defined through IfcTaskTime. Recurring tasks are + defined through IfcTaskTimeRecurring. In case a + regular task is derived from a recurring task both tasks + should be linked together through a IfcRelNests + relationship, where IfcRelNests.IsNestedBy points to + the recurring task and IfcRelNests.Nests points to + all regular tasks that have been derived from the recurring + task. +

+

Assignment use definition

+

+ Occurrences of IfcTask may be assigned to an + IfcWorkControl (either a work plan or a work + schedule) through IfcRelAssignsToControl. From + IFC2x4 onwards it is suggested to use the 'summary task' + (root element of the task hierarchy that is required for + task management purposes) to assign all subtask to a work + plan or work schedule. Resources used by tasks are assigned + by IfcRelAssignsToProcess. Quantities of resources + consumed by the task are dealt with by defining the + IfcElementQuantity for the resource and not at the + instance of IfcTask. Please note that the + IfcRelAssignsTasks relationship class has been + removed in IFC2x4 and is no longer available. +

+

+ An IfcTask may be assigned a Work Breakdown + Structure (WBS) code. A WBS code is dealt with as a + classification of task and is associated to a task + occurrence using the IfcRelAssociatesClassification + relationship class. As well as being to designate the code, + the classification structure of the IFC model also enables + the source of the work breakdown structure classification + to be identified. +

+

Constraint use definition

+

+ Constraints may be applied to a task to indicate fixed task + duration, fixed start or fixed finish (see Figure 15). The relationship + IfcRelAssociatesConstraint is used where + RelatingConstraint points to an IfcMetric and + RelatedObjects includes the IfcTask. + IfcRelAssociatesConstraint.Name identifies the + attribute to be constrained using a period (""."") to + dereference; for example, ""TaskTime.ScheduleStart"" refers + to the ScheduleStart attribute on the + IfcTaskTime entity referenced on the TaskTime + attribute. The following attributes may be constrained: +

+
    +
  • + 'TaskTime.ScheduleDuration': Indicate fixed + duration of task with ConstraintGrade=HARD and + Benchmark=EQUALTO such that changes to an assigned + IfcConstructionResource.ResourceTime.ScheduleWork + should impact + IfcConstructionResource.ResourceTime.ScheduleUsage, + and vice-versa. +
  • +
  • + 'TaskTime.ScheduleStart': Indicate constrained + start date with ConstraintGrade=HARD and Benchmark of + EQUALTO, GREATERTHANOREQUALTO, or LESSTHANOREQUALTO to + indicate ""must start on"", ""start no earlier than"" or + ""start no later than"" respectively where + IfcMetric.DataValue indicates the specific + IfcDateTime. Use SOFT constraint having LESSTHAN + benchmark to indicate ""start as soon as possible"". +
  • +
  • + 'TaskTime.ScheduleFinish': Indicate constrained + finish date with ConstraintGrade=HARD and Benchmark of + EQUALTO, GREATERTHANOREQUALTO, or LESSTHANOREQUALTO to + indicate ""must finish on"", ""finish no earlier than"" or + ""finish no later than"" respectively where + IfcMetric.DateValue indicates the specific + IfcDateTime. Use SOFT constraint having + GREATERTHAN benchmark to indicate ""finish as late as + possible"". +
  • +
+

+ A ""manual scheduled task"" is indicated with + ConstraintGrade=HARD and Benchmark=EQUALTO for both + TaskTime.ScheduleStart and + TaskTime.ScheduleFinish. +

+ + + + +

Figure 15 — Task constraints

+ +

+ Use Definition to represent other activities +

+

+ The use definitions for IfcTask have been generalised to + represent other activities as well, including actitities + that had been defined by own entities in previous IFC + releases. This includes +

+
    +
  • Order actions
  • +
  • Move operations
  • +
+

+ IfcTask represents an order that might be carried + out by a Helpdesk acting the role of interface for the + organization between the facility user and the functional + requirement of fulfilling their needs. The actual task + represented by the IfcTask entity is turning a + request into an order and initiating the action that will + enable the order to be completed. The + IfcProjectOrder or one of its subtypes including + maintenance work order, is related to the IfcTask + using IfcRelAssignsToControl. +

+

+ IfcTask can also be used to describe an activity + that moves people, groups within an organization or + complete organizations together with their associated + furniture and equipment from one place to another. It thus + replaces the previous IFC entity IfcMove. The functionality + is represented in IfcTask as follows:
+

+
    +
  • Move from: The place from which actors and their + associated equipment are moving.
    + Use IfcRelAssignsToProcess where + RelatingProcess points to the task and + RelatedObjects holds the location(s) from which to + move.
  • +
  • Move to: The place to which actors and their + associated equipment are moving.
    + Use IfcRelAssignsToProduct where + RelatedObjects points to the task(s) and + RelatingProduct points to the location to which to + move.
  • +
  • Punch list: A list of points concerning a move that + require attention.
    + Use LongDescription or else identify sub-tasks to + track punch list items individually via IfcRelNests.
  • +
+ +
" +2502;IfcProcedure;" +

+ An IfcProcedure is a + logical set of actions to be taken in response to an event + or to cause an event to occur. +

+
+ HISTORY  New entity in IFC2x2 +
+
+ IFC2x4 CHANGE  ProcedureType renamed to PredefinedType and made optional (upward compatible). Where rules WR1 and WR2 have been removed. +
+

Use definitions

+

+ IfcProcedure is used to capture information about + stepped processes such as calibration, start/stop + procedures for equipment items, designated actions to take + in the event of an emergency etc. A procedure is not a + task, but may describe a set of tasks and their order of + occurrence in response to or to cause an event. +

+

Type use definition

+

+ IfcProcedure defines the anticipated or actual + occurrence of any procedure; common information about + procedure types is handled by IfcProcedureType. The + IfcProcedureType (if present) may establish the + common type name, usage (or predefined) type, common nested + procedures (using IfcRelNests), common set of + properties, and common product assignment using + IfcRelAssignsToProduct. The IfcProcedureType + is attached using the + IfcRelDefinesByType.RelatingType objectified + relationship and is accessible by the inverse + IsTypedBy attribute. +

+

Property set use definition

+

+ The property sets relating to IfcProcedure are + defined by IfcPropertySet and attached by the + IfcRelDefinesByProperties relationship. They are + accessible by the inverse IsDefinedBy relationship. + Such property sets may define procedure parameters. No + property sets for IfcProcedure are currently defined + by IFC. +

+

Connectivity use definition

+

+ The relationship IfcRelSequence is used to indicate + control flow. An IfcProcedure as a successor to an + IfcEvent indicates that the procedure should be + performed in response to the event. An IfcProcedure + as a predecessor to an IfcEvent indicates that the + event should be trigerred following the procedure. As + procedures have arbitrary duration, the + IfcRelSequence.SequenceType attribute has no effect + on an IfcProcedure but still applies to the opposite + end of the relationship if IfcTask is used. +

+

Composition use definition

+

+ IfcProcedure may be contained within an + IfcTask or IfcProcedure using the + IfcRelNests relationship. An IfcProcedure may + in turn nest other IfcProcedure or IfcEvent + entities. Such nesting indicates decomposed level of + detail. +

+

+ Note that a particular type of IfcProcedure is a + caution, warning or other form of advisory note. Typically, + it is anticipated that such a procedure would be assigned + to the specific IfcProcess for which it gives advice + using IfcRelAssignsToProcess. +

+

Assignment use definition

+

+ An IfcProcedure may be assigned to an + IfcWorkCalendar to indicate times when such + procedure may be performed using + IfcRelAssignsToControl; otherwise the effective + calendar is determined by the nearest IfcProcess + ancestor with a calendar assigned. Advisory notes should be + assigned to the specific IfcProcess for which it + gives advice using IfcRelAssignsToProcess. +

+

+ For building operation scenarios, IfcProcedure may + be assigned to a product (IfcElement subtype) using + IfcRelAssignsToProduct to indicate a specific + product occurrence that performs the procedure. For + example, an IfcActuator may have a ""Close"" + procedure. If the IfcProcedure is defined by an + IfcProcedureType and the IfcProcedureType is + assigned to a product type (using + IfcRelAssignsToProduct), then the + IfcProcedure must be assigned to one or more + occurrences of the specified product type using + IfcRelAssignsToProduct. +

+ +

As shown in Figure 12, IfcProcedure does not restrict anything but + describes specific steps of how something should happen. + While a procedure does control/restrict in the sense of + indicating ""this is how the task should be performed"" by + nature of describing inner detail, this is not different than + parts of a product indicating ""this is how the parts should + be assembled"". Consequently, it doesn't restrict the outer + item as a whole but provides inner detail of the item.

+ + + +

Figure 12 — Procedure relationships

+

+
" +2516;IfcEvent;" +

+ An IfcEvent is something + that happens that triggers an action or response. +

+
+ HISTORY  New entity in IFC2x4 +
+

Use definitions

+

+ IfcEvent is used to capture information about + particular things that happen or that may happen. + Particularly used in work plans (or process maps) they + identify e.g. a point at which a message containing + information may be issued or at which a rule or constraint + is invoked. +

+

Type use definition

+

+ IfcEvent defines the anticipated or actual occurrence of + any event; common information about event types is handled + by IfcEventType. The IfcEventType (if present) may + establish the common type name, usage (or predefined) type, + common set of properties, and common product assignment + using IfcRelAssignsToProduct. The IfcEventType is attached + using the IfcRelDefinesByType.RelatingType objectified + relationship and is accessible by the inverse IsTypedBy + attribute. +

+

Property set use definition

+

+ The property sets relating to IfcEvent are defined by + IfcPropertySet and attached by the + IfcRelDefinesByProperties relationship. They are accessible + by the inverse IsDefinedBy relationship. Such property sets + may define event parameters. No property sets for IfcEvent + are currently defined by IFC. +

+

Connectivity use definition

+

+ The relationship IfcRelSequence is used to indicate control + flow. An IfcEvent as a predecessor + (IfcRelSequence.RelatingProcess) indicates that the + succeeding process (typically IfcProcedure or IfcTask) is + triggered in response to the event. An IfcEvent as a + successor (IfcRelSequence.RelatedProcess) indicates that + the completion of the preceeding process causes the event + to be triggered. As events have zero duration, the + IfcRelSequence.SequenceType attribute has no effect on an + IfcEvent but still applies to the opposite end of the + relationship if IfcTask is used. +

+

Composition use definition

+

+ IfcEvent may be contained within an IfcTask using the + IfcRelNests relationship. The event is considered active + during the time period of the enclosing task (including any + assigned IfcWorkCalendar); that is such event may be + triggered within the task time period but not outside of + it. As an IfcEvent is considered to be atomic, no use is + anticipated for nesting processes inside the event. +

+

Assignment use definition

+

+ An IfcEvent may be assigned to an IfcWorkCalendar to + indicate times when such event is active using + IfcRelAssignsToControl; otherwise the effective calendar is + determined by the nearest IfcProcess ancestor with a + calendar assigned. +

+

+ For building operation scenarios, IfcEvent may be assigned + to a product (IfcElement subtype) using + IfcRelAssignsToProduct to indicate a specific product + occurrence that sources the event. For example, an + IfcSensor for a motion sensor may have a ""Motion Sensed"" + event. If the IfcEvent is defined by an IfcEventType and + the IfcEventType is assigned to a product type (using + IfcRelAssignsToProduct), then the IfcEvent must be assigned + to one or more occurrences of the specified product type + using IfcRelAssignsToProduct. +

+
" +2536;IfcWorkControl;" +

+ An IfcWorkControl is an abstract supertype which captures information that is common to both IfcWorkPlan and IfcWorkSchedule. +

+
+ HISTORY  New class in IFC 2x +
+
+ CHANGE IFC2x4  Corrected assignment of resources to work control in documentation. Assignment of tasks to work control updated based on changes of task time definitions and the introduction of a summary task. Identifier has been renamed (now Identification) and promoted to supertype IfcControl +
+

+ A work control may have resources assigned to it, this is + handled by the IfcRelAssignsToControl relationship. + A work control should also define a context that gives + further information about its usage. If no special context + information is required then the IfcProject instance + as a global context should be used instead. An explicit + link between the work control and the IfcProject via + IfcRelDeclares should then be provided. +

+

+ From IFC2x4 onwards the assignment of tasks to the work + control is handled by the IfcRelAssignsToControl + relationship. IfcRelAssignsTasks as used in previous + IFC releases has been deleted and can not be used any + longer. Another change in IFC2x4 is that it is not + necessary to assign each task to a work control as it is + regarded to be sufficient if the summary task (root task in + the task hierarchy defined through IfcRelNests + relationships) is assigned to a work control. +

+

+ The attribute IfcWorkControl.Purpose is used to + define the purpose of either a work schedule or a work + plan. In the case of IfcWorkPlan, the purpose + attribute can be used to determine if the work plan is for + cost estimating, task scheduling or some other defined + purpose. +

+

Property set use definition

+

+ The property sets relating to the IfcWorkControl are + defined by IfcPropertySet and attached by the + IfcRelDefinesByProperties relationship. It is + accessible by the inverse IsDefinedBy relationship. + The following property set definition specific to the + IfcWorkControl and its subtype are part of this IFC + release: +

+ +
" +2546;IfcWorkPlan;" +

+ An IfcWorkPlan represents work plans in a construction or a facilities management project. +

+
+ HISTORY: New Entity in IFC 2.0 +
+

+ A work plan contains a set of work schedules for different + purposes (including construction and facilities + management). Contained work schedules are defined through + the IfcRelAggregates relationship. Through + inheritance from IfcWorkControl it is also possible + to define references to activities (for example, IfcTask) + and resources used in the work plan. +

+

+ A work plan has information such as start date, finish + date, total free float, and so on. IfcWorkPlan can + also refer to the construction project represented by the + single IfcProject instance (please also check the + definition of IfcWorkControl). +

+

+ Figure 18 shows the backbone structure of a work plan that + defines (1) contained work schedules through + IfcRelAggregates and (2), if not assigned otherwise + to contained work schedules, assigned tasks and resources + through IfcRelAssignsToControl. +

+ + + +
+

Figure 18 — Work plan relationships

+ +
" +2555;IfcWorkSchedule;" +

+ An IfcWorkSchedule + represents a task schedule of a work plan, which in turn + can contain a set of schedules for different purposes. +

+
+ HISTORY: New Entity in IFC + Release 2.0 +
+ +

Assignment Use Definition

+

+ An IfcWorkSchedule controls a set of tasks and + resources defined through IfcRelAssignsToControl. + Additionally, through the IfcWorkControl abstract + supertype, the actors creating the schedule can be + specified and schedule time information such as start time, + finish time, and total float of the schedule can also be + specified. +

+

Declaration Use Definition

+

+ IfcWorkSchedule can reference a project (the + single IfcProject instance) via + IfcRelDeclares. The documents of the + IfcWorkSchedule can be referenced by the + IfcRelAssociatesDocuments relationship.

+ +

Composition Use Definition

+

A work schedule can include other work schedules as sub-items + through IfcRelNests relationship. If not included in + another work schedule it might be a part of a work plan + (IfcWorkPlan) defined through + IfcRelAggregates relationship. +

+ +

+ Figure 19 shows the backbone structure of a work schedule + that defines (1) a context through IfcRelDeclares + (not necessarily the project) and (2) controls tasks + (typically the schedule summary task) and resources. Please + note that a work calendar shall be assigned to the summary + task and not the work schedule. +

+ + + + +
+

Figure 19 — Work schedule relationships

+ +
" +2564;IfcWorkCalendar;" + +

An IfcWorkCalendar defines working and non-working time periods for tasks and resources. It enables to define both specific time periods, such as from 7:00 till 12:00 on 25th August 2009, as well as repetitive time periods based on frequently used recurrence patterns, such as each Monday from 7:00 till 12:00 between 1st March 2009 and 31st December 2009.

+ +
+HISTORY  New entity in IFC2x4. +
+ +

A work calendar is a subtype of IfcControl and thus inherits the feature for controlling other objects through IfcRelAssignsToControl, which is used to define a work calendar for tasks (IfcTask) and resources (IfcResource). It also inherits a name and description attribute, whereas a name shall be given and a description may be given as an indication of its content and usage.

+ +

The definition of time periods can be derived from a base calendar and/or modified/defined by a set of working times and non-working exception times. All time periods defined by IfcWorkCalendar.ExceptionTimes override the time periods inherited from the base calendar (base calendar is defined as the next applicable calendar for the task or resource). Thus, exception times replace the working times from the base calendar.

+ +

The base calendar of a work calendar is defined by IfcRelAssignsToControl, where IfcRelAssignsToControl.RelatingControl is linked with the base calendar and IfcRelAssignsToControl.RelatedObjects is linked with work calendars that are derived from the base calendar. Although not restricted by the IfcRelAssignsToControl relationship it is only allowed to have one base calendar.

+ +

Figure 17 shows the definition of a work calendar, which is defined by a set of work times and exception times. The work times are defined as recurring patterns with optional boundaries (applying from and/or to a specific date). The shown example defines a simple work calendar with working times Monday to Thursday 8:00 to 12:00 and 13:00 to 17:00, Friday 8:00 to 14:00 and as exception every 1st Monday in a month the work starts one hour later - i.e. the working time on every 1st Monday in a month is overriden to be 9:00 to 12:00 and 13:00 to 17:00. Both the working time and the exception time is valid for the period of 01.09.2010 till 30.08.2011.

+ + + + +

Figure 17 — Work calendar instantiation

+ +
" +2575;IfcRelSequence;" +

+ IfcRelSequence is a + sequential relationship between processes where one process + must occur before the other in time and where the timing of + the relationship may be described as a type of sequence. + The relating process + (IfcRelSequence.RelatingProcess) is considered to be + the predecessor in the relationship (has precedence) whilst + the related process (IfcRelSequence.RelatedProcess) + is the successor. +

+

+ IfcRelSequence is defined as one-to-one + relationship; therefore it assigns one predecessor to one + successor. +

+
+ HISTORY  New entity in IFC 1.0. +
+
+ IFC2x4 CHANGE  Relocated to IfcProcessExtension schema. + TimeLag and SequenceType made optional. + USERDEFINED added to the IfcSequenceType + enumeration. UserDefinedSequenceType attribute + added. WHERE rule controlling use of the USERDEFINED + enumeration added. +
+

Use definitions

+

+ IfcRelSequence is used to describe the logical + sequence relationship that exists between two processes. + This logical relationship identifies that there is a + predecessor or relating process and a successor or related + process. In IFC, there may be one predecessor and one + successor in the relationship. Many occurrences of + IfcRelSequence may exist to describe the sequence + relationships of a predecessor task with many successor + tasks or of many predecessor tasks with one successor task, + thus enabling a m:n sequence relationship between tasks. + Please note that sequence relationships always should stay + within the limits of a directed, non-cyclic graph. +

+

+ A sequence type may be set for a sequence. For tasks + assigned to a work schedule, it is expected that the + sequence type will be asserted. For a process map, where + the sequence relationship between processes is simply a + logical flow, it need not be asserted. +

+

+ A time lag may be assigned to a sequence, and the sequence + type defines the way in which the time lag applies to the + sequence either as a ratio or percentage of time duration + (e.g. start successor task when predecessor is 50% + complete) or as a time measure (e.g. start successor task 1 + week after commencement of the predecessor task). Care + should be used when assigning a time lag to a sequence + depending on the setting of the sequence type since there + is no checking that the time lag value is in keeping with + the sequence type set. +

+
" +2590;IfcTaskType;" +

+ An IfcTaskType defines a + particular type of task that may be specified for use + within a work control. +

+
+HISTORY  New entity in IFC2x4 +
+

+ An IfcTaskType provides for all forms of types of + task that may be specified. +

+

+ Usage of IfcTaskType defines the parameters for one + or more occurrences of IfcTask. Parameters may be + specified through property sets that may be enumerated in + the IfcTaskTypeEnum data type or through explict + attributes of IfcTaskType. Task occurrences + (IfcTask entities) are linked to the task type + through the IfcRelDefinesByType relationship. +

+

Composition use definition

+

+ IfcTaskType may nest other IfcTaskType or + IfcTask entities using the IfcRelNests + relationship. Such nesting indicates decomposed level of + detail. Nesting of IfcTask entities is used if a + task type shall be detailed by a sequence of tasks or if + there is a need to include additional time information such + as the duration of subtasks. Please note that + IfcTask entities being contained within an + IfcTaskType are linked with their task occurrences + via IfcRelDefinesByObject relationships. It is also + possible to define a task type for these IfcTask + entities via IfcRelDefinesByType relationships. For + further information please see the documentation of + IfcRelDefinesByObject. +

+

Figure 16 shows the definition of a task type that is part + of a task template library. Please note that in this + example the task type is further subdivided into tasks that + define task times (for example, duration) and/or a task sequence. +

+ + +

Figure 16 — Task type relationships

+ +
" +2594;IfcProcedureType;" +

An IfcProcedureType defines a particular type of procedure that may be specified.

+
+HISTORY  New entity in IFC2x4 +
+

An IfcProcedureType provides for all forms of types of procedure that may be specified.

+

+ Usage of IfcProcedureType defines the parameters for + one or more occurrences of IfcProcedure. Parameters + may be specified through property sets that may be + enumerated in the IfcProcedureTypeEnum data type or + through explict attributes of IfcProcedure. Procedure occurrences + (IfcProcedure entities) are linked to the procedure type + through the IfcRelDefinesByType relationship. +

+
" +2597;IfcEventType;" +

An IfcEventType defines a particular type of event that may be specified.

+
+HISTORY  New entity in IFC2x4 +
+

An IfcEventType provides for all forms of types of event that may be specified.

+

Usage of IfcEventType defines the parameters for one or more occurrences of IfcEvent. Parameters may be specified through property sets that may be enumerated in the IfcEventTypeEnum data type or through explicit attributes of IfcEvent. Event occurrences (IfcEvent entities) are linked to the event type through the IfcRelDefinesByType relationship.

+
" +2604;IfcCostSchedule;" + +

An IfcCostSchedule brings together instances of IfcCostItem either for the purpose of identifying purely cost information as in an estimate for constructions costs or for including cost information within another presentation form such as a work order.

+ +
+HISTORY New Entity in IFC Release 2.0. Modified in IFC 2x2
+IFC2x4 CHANGE Attribute 'ID' changed to Identification and promoted to supertype IfcControl, PredefinedType made optional, attributes PreparedBy, SubmittedBy, TargetUsers removed. +
+ +

Declaration Use Definition

+

The IfcCostSchedule may be declared within the project using the IfcRelDeclares relationship where RelatingContext refers to the single IfcProject and RelatedDefinitions contains the IfcCostSchedule. Alternatively, if the IfcCostSchedule is aggregated within another IfcControl object, then it shall not have a direct declaration relationship (whereas the containing object may have a declaration relationship).

+ +

Assignment Use Definition

+

The IfcCostSchedule may be assigned to the following entities using relationships as indicated:

+ +

The IfcCostSchedule may have assignments of its own using the IfcRelAssignsToControl relationship where RelatingControl refers to the IfcCostSchedule and RelatedObjects contains one or more objects of the following types:

    +
  • IfcCostItem: Indicates costs published within this cost schedule, typically a single root cost item forming a hierarchy of nested cost items.
  • +
+ +

Classification Use Definition

+

Classifications may be applied using IfcRelAssociatesClassification where RelatedObjects contains the IfcCostSchedule and RelatingClassification refers to an IfcClassification or IfcClassificationReference.

+
    +
  • IfcClassification: Classifications to be used for cost items within the cost schedule.
  • +
+ +

Approval Use Definition

+

Approvals may be associated to indicate the status of acceptance or rejection using the IfcRelAssociatesApproval relationship where RelatingApproval refers to an IfcApproval and RelatedObjects contains the IfcCostSchedule. Approvals may be split into sub-approvals using IfcApprovalRelationship to track approval status separately for each party where RelatingApproval refers to the higher-level approval and RelatedApprovals contains one or more lower-level approvals. The hierarchy of approvals implies sequencing such that a higher-level approval is not executed until all of its lower-level approvals have been accepted.

+ + +
" +2619;IfcProjectOrder;" + +

A project order is a directive to purchase products and/or perform work, such as for construction or facilities management.

+ +

Project orders are typically formal contracts between two organizations, where cost and time information may be rigid or flexible according to contained schedule types and constraints.

+ +
HISTORY New entity in IFC 2.0
+
IFC2x4 CHANGE Attribute 'ID' changed to Identification and promoted to supertype IfcControl. Attribute 'LongDescription' added.
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Refer to the documentation at the supertype IfcControl and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Declaration Use Definition

+

The IfcProjectOrder may be declared within the project using the IfcRelDeclares relationship where RelatingContext refers to the single IfcProject and RelatedDefinitions contains the IfcProjectOrder. Alternatively, if the IfcProjectOrder is aggregated within an IfcWorkPlan, then it shall not have a direct declaration relationship (whereas the containing work plan may have a declaration relationship).

+ +

Composition Use Definition

+

As shown in Figure 160, an IfcProjectOrder may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcProjectOrder and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcCostSchedule components. A cost schedule may indicate costs and quantities where the cost schedule type may designate whether rates and/or quantities are estimated or final. Such cost schedule may have assigned cost items indicating detail, where each cost item may have assigned products, processes, or resources.
  • +
  • WORKORDER: May contain IfcWorkSchedule components. A work schedule may indicate tasks and scheduled times where the work schedule type may designate whether tasks and/or times are planned or actual. Such work schedule may have assigned tasks indicating detail, where tasks may be assigned to products and may have assigned resources.
  • +
+

The IfcProjectOrder may be nested into sub-items using IfcRelNests where RelatingObject refers to the enclosing IfcProjectOrder and RelatedObjects contains one or more sub-items. Nesting use is defined for the following predefined types: +

    +
  • WORKORDER: May contain IfcProjectOrder sub-items having PredefinedType CHANGEORDER. A work order may be nested into change orders to indicate contract ammendment, in order of issue.
  • +
+ + + +

Figure 161 — Project order composition

+ +

Assignment Use Definition

+

As shown in Figure 161, an IfcProjectOrder may be assigned to the following entities using relationships as indicated:

+ +

The IfcProjectOrder may have assignments of its own using the IfcRelAssignsToControl relationship where RelatingControl refers to the IfcProjectOrder and RelatedObjects contains one or more objects of the following types:

    +
  • IfcActor: Organization(s) contracted to fulfill the order, typically a single contractor, subcontractor, or supplier. +
  • +
+ + + +

Figure 162 — Project order assignment

+ +

Approval Use Definition

+

Approvals may be associated to indicate the status of acceptance or rejection using the IfcRelAssociatesApproval relationship where RelatingApproval refers to an IfcApproval and RelatedObjects contains the IfcProjectOrder. Approvals may be split into sub-approvals using IfcApprovalRelationship to track approval status separately for each party where RelatingApproval refers to the higher-level approval and RelatedApprovals contains one or more lower-level approvals. The hierarchy of approvals implies sequencing such that a higher-level approval is not executed until all of its lower-level approvals have been accepted.

+ +
" +2631;IfcCostItem;" + +

An IfcCostItem describes a cost or financial value together with descriptive information that describes its context in a form that enables it to be used within a cost schedule. An IfcCostItem can be used to represent the cost of goods and services, the execution of works by a process, lifecycle cost and more.

+ +

Each instance of IfcCostItem may have a name and a description. Depending on the use for which the cost is intended, these values should be asserted on the basis of agreement. For instance, the Name attribute could be used to provide a common value that enables distinct instances to be brought together in a nesting arrangement (see below) while the Description attribute may be used to provide text used for item description in a costing schedule.

+ +

An IfcCostItem can link one or many IfcCostValue's representing a unit cost, total cost, or a unit cost with one or many quantities used to generate the total cost. The quantities can be given as individual quantities, or those quantities are provided as element quantities by one or many building elements. The IfcCostValue.CostType attribute indicates the category of cost, which may be used to present the value in a particular column. For nested cost items (having IfcRelNests relationship), IfcCostValue.CostType is significant such that IfcCostValue.AppliedValue is calculated as the sum of all nested costs having the same IfcCostValue.CostType or if set to an asterisk ('*'), then the sum of all nested costs of all cost types. An IfcCostValue may represent an original value or a value derived from formulas using IfcAppliedValueRelationship. For example, taxes may be calculated as a percentage of a subtotal.

+ +
HISTORY New Entity in IFC Release 2.0.
+
IFC2x4 CHANGE Attribute PredefinedType, CostValues, and CostQuantities added.
+ +

Classification Use Definition

+ +

Instances of IfcCostItem are used for cost estimates, budgets, and other forms, where a variety of identification codes are used extensively to identify the meaning of the cost. Examples include project phase codes, CSI codes, takeoff sequence numbers, and cost accounts. The model allows for all classes that are ultimately subtypes of IfcObject to inherit the ability to have one or more instances of IfcClassificationReference to be assigned. Where identification codes are required, the generic IfcRelAssociatesClassification facility should be used.

+ + +

Composition Use Definition

+ +

An IfcCostItem can nest other instances of IfcCostItem through its relationships to IfcRelNests. This can be used to enable the development of complex groups of costs as may be found in cost schedules through to pages, sections and complete cost schedules.

+ +

There is always a summary cost item as the root item of the tree representing the cost item nesting. Subsequent instances of IfcCostItem are assigned to the summary cost item using IfcRelNests. The summary cost item itself is assigned to IfcCostSchedule through the IfcRelAssignsToControl relationship.

+ +

Figure 157 illustrates a cost item composition used for a cost schedule. Each line item has a quantity and separate unit costs where IfcCostValue.CostType indicates the category of cost. The summary item has a hierarchy of costs calculated according to IfcAppliedValueRelationship.ArithmeticOperator, where IfcCostValue.CostType identifies the category to be totalled. The Tax component has IfcCostValue.CostType set to 'Material' which indicates it is the sum of all nested values of the 'Material' category ($3 x 3000 + $118 x 100 = $20800). The Subtotal component has IfcCostValue.CostType set to an asterisk ('*') which indicates it is the sum of all nested values of all categories.

+ + + + +

Figure 157 — Cost composition

+ + +

Assignment Use Definition

+ +

An IfcCostItem can be calculated based on quantities from objects through its relationship to IfcRelAssignsToControl.

+ +

For quantity-based costing, IfcElement, IfcTask, or IfcResource occurrence subtypes may be used. Multiple elements may be assigned of the same or different types, using IfcPhysicalQuantity entities defined at each object. Each IfcPhysicalQuantity type must be identical (for example, all values are IfcAreaQuantity) such that they can be added together.

+ +

For rate-based costing (specifically for IfcCostScheduleTypeEnum.SCHEDULEOFRATES), a single IfcTypeProduct, IfcTypeProcess, or IfcTypeResource subtype may be used to reflect rates for occurrences of such types. This enables the possibility to generate a quantity-based cost schedule for occurrences based on types with rate-based cost schedules.

+ +

IfcRelAssignsToControl is also used in the opposite direction to link the root IfcCostItem to an IfcCostSchedule where RelatingControl is the IfcCostSchedule. + +

Figure 158 illustrates cost item assignment derived from building elements. The IfcRelAssignsToControl relationship indicates building elements for which quantities are derived. Not shown, costs may also be derived from building elements by traversing assignment relationships from the assigned IfcProduct to IfcProcess to IfcResource, where all costs ultimately originate at resources. It is also possible for cost items to have assignments from processes or resources directly.

+ + + + +

Figure 168 — Cost assignment

+ +
" +2638;IfcPermit;" + +

A permit is a permission to perform work in places and on artifacts where regulatory, security or other access restrictions apply.

+ +
HISTORY New entity in IFC2x2
+
IFC2x4 CHANGE PermitID renamed to Identification and promoted to supertype IfcControl, Attributes PredefinedType, Status, and LongDescription added.
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Refer to the documentation at the supertype IfcControl and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Declaration Use Definition

+

The IfcPermit may be declared within the project using the IfcRelDeclares relationship where RelatingContext refers to the single IfcProject and RelatedDefinitions contains the IfcPermit. Alternatively, if the IfcPermit is aggregated within an IfcWorkPlan, then it shall not have a direct declaration relationship (whereas the containing work plan may have a declaration relationship).

+ +

Composition Use Definition

+

The IfcPermit may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcPermit and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types: +

    +
  • ACCESS: May contain IfcWorkCalendar components. A work calendar may indicate the time period of the permit and allowed times when work may be performed. Such work calendar may have assigned resources indicating equipment or labor permitted at various times.
  • +
  • WORK: May contain IfcWorkSchedule components. A work schedule may indicate tasks and scheduled times where the work schedule type may designate whether tasks and/or times are planned or actual. Such work schedule may have assigned tasks indicating detail, where tasks may be assigned to products and may have assigned resources.
  • +
+

As shown in Figure 159, an IfcPermit may be nested into sub-items using IfcRelNests where RelatingObject refers to the enclosing IfcPermit and RelatedObjects contains one or more sub-items. Nesting use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcPermit sub-items. A permit may be nested to indicate permit ammendments, in order of issue.
  • +
+ + + +

Figure 159 — Permit composition

+ +

Assignment Use Definition

+

As shown in Figure 160, an IfcPermit may be assigned to the following entities using relationships as indicated:

+ +

The IfcPermit may have assignments of its own using the IfcRelAssignsToControl relationship where RelatingControl refers to the IfcPermit and RelatedObjects contains one or more objects of the following types:

    +
  • IfcActor: Organization(s) bound to the permit, typically a single contractor. +
  • +
+ + + +

Figure 160 — Permit assignment

+ +

Approval Use Definition

+

Approvals may be associated to indicate the status of acceptance or rejection using the IfcRelAssociatesApproval relationship where RelatingApproval refers to an IfcApproval and RelatedObjects contains the IfcPermit. Approvals may be split into sub-approvals using IfcApprovalRelationship to track approval status separately for each party where RelatingApproval refers to the higher-level approval and RelatedApprovals contains one or more lower-level approvals. The hierarchy of approvals implies sequencing such that a higher-level approval is not executed until all of its lower-level approvals have been accepted.

+ + +
" +2648;IfcActionRequest;" + +

A request is the act or instance of asking for something, such as a request for information, bid submission, or performance of work.

+ +

Requests may take many forms depending on the need including fault reports for maintenance, requests for small works, and purchase requests (where these are to be made through a help desk or buying function).

+ +
HISTORY: New entity in IFC2x2
+
IFC2x4 CHANGE RequestID renamed to Identification and promoted to supertype IfcControl, attributes PredefinedType, Status, and LongDescription added.
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. They are accessible by the IsDefinedBy inverse attribute. Refer to the documentation at the supertype IfcControl and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Declaration Use Definition

+

The IfcActionRequest may be declared within the project using the IfcRelDeclares relationship where RelatingContext refers to the single IfcProject and RelatedDefinitions contains the IfcActionRequest. Alternatively, if the IfcActionRequest is aggregated within an IfcWorkPlan, then it shall not have a direct declaration relationship (whereas the containing work plan may have a declaration relationship).

+ +

Composition Use Definition

+

As shown in Figure 155, an IfcActionRequest may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcActionRequest and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcCostSchedule components. A cost schedule may indicate costs and quantities where the cost schedule type may designate whether rates and/or quantities are estimated or final. Such cost schedule may have assigned cost items indicating detail, where each cost item may have assigned products, processes, or resources.
  • +
+

The IfcActionRequest may be nested into sub-items using IfcRelNests where RelatingObject refers to the enclosing IfcActionRequest and RelatedObjects contains one or more sub-items. Nesting use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcActionRequest sub-items. A request may be nested into follow-up requests, in order of issue.
  • +
+ + + +

Figure 155 — Action request composition

+ +

Assignment Use Definition

+

As shown in Figure 156, an IfcActionRequest may be assigned to the following entities using relationships as indicated:

+ +

The IfcActionRequest may have assignments of its own using the IfcRelAssignsToControl relationship where RelatingControl refers to the IfcActionRequest and RelatedObjects contains one or more objects of the following types:

    +
  • IfcActor: Person or organization(s) fulfilling the request such as a facilities manager or contractor. +
  • +
+ + + +

Figure 156 — Action request assignment

+ +

Approval Use Definition

+

Approvals may be associated to indicate the status of acceptance or rejection using the IfcRelAssociatesApproval relationship where RelatingApproval refers to an IfcApproval and RelatedObjects contains the IfcActionRequest. Approvals may be split into sub-approvals using IfcApprovalRelationship to track approval status separately for each party where RelatingApproval refers to the higher-level approval and RelatedApprovals contains one or more lower-level approvals. The hierarchy of approvals implies sequencing such that a higher-level approval is not executed until all of its lower-level approvals have been accepted.

+ + +
" +2661;IfcConstructionResource;" + +

IfcConstructionResource is an abstract generalization of the different resources used in +construction projects, mainly labor, material, equipment and product resources, plus subcontracted resources and aggregations such as a crew resource.

+ +

A resource represents ""use of something"" and does not necessarily correspond to a single item such as a person or vehicle, but +represents a pool of items having limited availability such as general labor or an equipment fleet. A resource can represent either a generic resource pool (not having any task assignment) or a task-specific resource allocation (having an IfcTask +assignment).

+ +
+HISTORY  New entity in IFC2x2. +
+
+IFC2x4 CHANGE  Modified in to promote ResourceIdentifer and ResourceGroup (renamed to LongDescription) to supertype IfcResource and add attributes as described. +
+ +

Type use definition

+

IfcConstructionResource defines the occurrence of any construction resource; common information about construction resource types is handled by IfcConstructionResourceType. The IfcConstructionResourceType (if present) may establish the common type name, common properties, common cost rates, and common productivities applied to specific task types. The IfcConstructionResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute as shown in Figure 186.

+

The resource type may provide shared productivity and cost information, allowing tasks and resources to be selected according to lowest cost and/or shortest duration. Given an IfcProduct of a particular IfcTypeProduct type, an IfcTypeProcess may be selected from those assigned to the product type using IfcRelAssignsToProduct, and an IfcTypeResource may be selected from those assigned to the process type using IfcRelAssignsToProcess. Then IfcTask and IfcConstructionResource occurrences may be instantiated from the type definitions, applying productivitity and rate information to assigned quantities to calculate ResourceTime.ScheduleWork. Task durations can then be calculated by dividing ResourceTime.ScheduleWork by ResourceTime.ScheduleUsage.

+ + + +

Figure 186 — Construction resource type use

+ +

Composition use definition

+

Resources may be decomposed into allocation pools using the IfcRelNests relationship as shown in Figure 187. For example, an IfcLaborResource for ""Electrician"" may be decomposed into three task-specific IfcLaborResource objects: ""Electrical Rough-in"", ""First Floor Circuits"", and ""Second Floor Circuits"". Both relating and related sides may represent the same ResourceTime.ScheduleUsage quantity (for example, 6 workers time-shared), or the related side may break out ResourceTime.ScheduleUsage quantities for reserved use (for example, 4 workers and 2 workers).

+

A common scenario is two nesting levels where the first-level resources have no task assignments; while second-level resources have specific task assignments indicating that the resource is subdivided into allocations for specific tasks. While the model allows unlimited nesting of resources, implementer agreements may restrict to two nesting levels with task assignments specifically at the second level.

+ + + +

Figure 187 — Construction resource composition use

+ +

Declaration use definition

+

A root-level resource (specifically IfcCrewResource or IfcSubContractResource) is declared within the project by IfcRelDeclares where RelatingContext refers to the single IfcProject and RelatedObjects refers to one or more IfcConstructionResource, and other root-level objects within the project.

+ +

Assignment use definition

+

A resource may be assigned to an actor by IfcRelAssignsToActor where RelatingActor refers to an IfcActor and RelatedObjects refers to one or more IfcConstructionResource or other objects. Such relationship indicates the actor responsible for allocating the resource such as partitioning into task-specific allocations, delegating to other actors, and/or scheduling over time. Note that this assignment does not indicate the person or organization performing the work; that is indicated by IfcRelAssignsToResource. The actor responsible for the resource may or may not be the same as any actor(s) performing work.

+

A resource may be assigned to a control by IfcRelAssignsToControl where RelatingProduct refers to an IfcControl and RelatedObjects refers to one or more IfcConstructionResource or other objects. Most commonly an IfcWorkCalendar is assigned indicating availability of the resource, where such calendar is nested within a base calendar or an IfcWorkPlan which in turn is assigned to the IfcProject.

+

A resource may be assigned to a group by IfcRelAssignsToGroup where RelatingGroup refers to an IfcGroup and RelatedObjects refers to one or more IfcConstructionResource or other objects. Most commonly an IfcAsset is assigned indicating the asset to be tracked, where such asset is nested within an IfcInventory which in turn is assigned to the IfcProject.

+

A resource may be assigned to a product by IfcRelAssignsToProduct where RelatingProduct refers to an IfcProduct and RelatedObjects refers to one or more IfcConstructionResource or other objects. Most commonly an IfcElement subtype is assigned indicating the product to be constructed, where such product is connected to a spatial +structure which in turn is aggregated within the IfcProject.

+

A resource may be assigned to a process by IfcRelAssignsToProcess where RelatingProcess refers to an IfcProcess and RelatedObjects refers to one or more IfcConstructionResource or other objects. Most commonly an IfcTask is assigned indicating the task to be performed by the resource, where such task is nested within a summary task which in turn is assigned to the IfcProject.

+

A resource may have assignments of other objects using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionResource and RelatedObjects refers to one or more objects such as IfcActor or IfcProduct subtypes. This relationship indicates specific objects assigned to fulfill resource usage.

+

Figure 188 illustrates resource assignment.

+ + + +

Figure 188 — Construction resource assignment use

+ +

Constraint use definition

+

Constraints may be applied to a resource to indicate fixed work (such as total person-hours) or fixed usage (such as simultaneous workers). The relationship IfcRelAssociatesConstraint is used where RelatingConstraint points to an IfcMetric and RelatedObjects includes the IfcConstructionResource as shown in Figure 189. IfcRelAssociatesConstraint.Name identifies the attribute to be constrained using a period (""."") to dereference; for example, ""ResourceTime.ScheduleWork"" refers to the ScheduleWork attribute on the IfcResourceTime entity referenced on the ResourceTime attribute. The following attributes may be constrained:

+
    +
  • 'ResourceTime.ScheduleUsage': Indicate fixed usage (e.g. +simultaneous workers) with ConstraintGrade=HARD and +Benchmark=EQUALTO such that changes to +ResourceTime.ScheduleWork should impact the assigned +IfcTask.TaskTime.ScheduleDuration and vice-versa
  • +
  • 'ResourceTime.ScheduleWork': Indicate fixed work (e.g. +total person-hours) with ConstraintGrade=HARD and +Benchmark=EQUALTO such that changes to +ResourceTime.ScheduleUsage should impact the assigned +IfcTask.TaskTime.ScheduleDuration and vice-versa.
  • +
+ + + +

Figure 189 — Construction resource constraint use

+ +

Time series use definition

+

Time series may be applied to a resource to indicate the break-out of attribute values over time. The relationship IfcRelAssociatesTimeSeries is used where RelatingTimeSeries points to an IfcTimeSeries (either IfcRegularTimeSeries or IfcIrregularTimeSeries) and RelatedObjects includes the IfcConstructionResource as shown in Figure 190. IfcRelAssociatesTimeSeries.Name identifies the attribute to be constrained using a period (""."") to dereference; for example, ""ResourceTime.ScheduleWork"" refers to the ScheduleWork attribute on the IfcResourceTime entity referenced on the ResourceTime attribute. Refer to attribute descriptions on IfcResourceTime for attribute-specific usage.

+

Each IfcTimeSeriesValue indicates a LIST of values, where the sequence of the value corresponds to the IfcCostValue at IfcConstructionResource.CostRatesConsumed. For example, if CostRatesConsumed has two IfcCostValue items in the LIST, ""Standard"" and ""Overtime"", then IfcTimeSeriesValue(IfcDuration('T8H0M0S'),IfcDuration('T2H0M0S')) would indicate 8 hours at Standard rate and 2 hours at Overtime rate. If the list of values at IfcTimeSeriesValue.ListValues is less than the size of CostRatesConsumed, then subsequent values are considered to be zero.

+ + + +

Figure 190 — Construction resource time series use

+ +

Document use definition

+

Documents may be published for work plans consisting of schedules, calendars, tasks, and resources. The relationship IfcRelAssociatesDocument may be used to preserve mappings to such document where RelatingDocument points to an IfcDocumentReference and RelatedObjects includes the IfcConstructionResource as shown in Figure 191. +IfcDocumentReference.ItemReference identifies the resource within the scope of the document, such as an integer or guid. The IfcDocumentReference.ReferencedDocument corresponds to the document which is uniquely identified by IfcDocumentInformation.DocumentId and/or IfcDocumentInformation.PublicationLocation. Such document mapping allows items in the document to be updated from the building information model and vice-versa.

+ + + +

Figure 191 — Construction resource document use

+ +

Baseline use definition

+

A resource may have any number of baselines defined using the relationship IfcRelDefinesByObject where RelatingObject is the ""current"" resource and RelatedObjects consists of multiple ""baseline"" resources, each representing a copy of the resource as it existed at an earlier point in time as shown in Figure 192. Each baseline IfcConstructionResource is identified by its nested IfcRelAssignsToControl relationship to an IfcWorkSchedule having +PredefinedType=BASELINE, IfcWorkSchedule.CreationDate indicating the date of the baseline, and +IfcWorkSchedule.Name indicating the name of the baseline.

+ + + +

Figure 192 — Construction resource baseline use

+ +
" +2675;IfcConstructionEquipmentResource;" + +

IfcConstructionEquipmentResource is usage of construction equipment to assist in the performance of construction. Construction Equipment resources are wholly or partially consumed or occupied in the performance of construction. +

+ +
+HISTORY: New Entity in IFC Release 2.0. Base type and documentation extended in IFC2x4. +
+ +

Occurrences of IfcConstructionEquipmentResource are products that are used as resources to assist the process of construction. More specifically, they are products that are standalone items brought to a project to fulfil a particular purpose. Examples might be a tower crane or other mobile crane, a screwing machine, a lifting hoist etc. They are explicitly instances of IfcProduct and may be drawn from various of the subtype, for instance IfcTransportElement, IfcDiscreteAccessory, IfcProxy (for particular cases where more precise usage details are not available).

+ +

A product that is used as an IfcConstructionEquipmentResource is referenced using the IfcRelAssignsToResource.RelatedObjects relationship.

+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcConstructionEquipmentResource defines the occurrence of any construction equipment resource; common information about construction equipment resource types is handled by IfcConstructionEquipmentResourceType. The IfcConstructionEquipmentResourceType (if present) may establish the common type name, common properties, and common productivities for various task types using IfcRelAssignsToProcess. The IfcConstructionEquipmentResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+

+ +

Quantity use definition

+

The quantities relating to the IfcConstructionEquipmentResource are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. It is accessible by the inverse IsDefinedBy relationship. The following base quantities are defined and should be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. Other quantities can be defined being subjected to local standard of measurement with another string value assigned to Name and a value provided for MethodOfMeasurement. +

+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResource, a construction equipment resource may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionEquipmentResource and RelatedObjects contains one or more IfcProduct subtypes as shown in Figure 183. Such relationship indicates the equipment used as input for the resource. Such products are not contained within a building structure but are referenced within a construction spatial zone, specifically IfcSpatialZone with PredefinedType=CONSTRUCTION, which is aggregated within the IfcProject. There may be multiple chains of production such that the assigned equipment may have their own task and resource assignments for assembling such equipment.

+ + + +

Figure 183 — Construction equipment resource assignment

+ +

+ +
" +2689;IfcLaborResource;" + +

An IfcLaborResource is used in construction with particular skills or crafts required to perform certain types of construction or management related work.

+ +
+HISTORY: New Entity in IFC Release 2.0. Base type and documentation extended in IFC 2x4. +
+ +
+IFC2x4 CHANGE: The attribute Skillset has been deleted; use LongDescription to describe the skillset. +
+ +

The purpose of an IfcLaborResource is to identify a skillset that may be required or used. The skillset identified may be (for instance) chargehand, foreman, labourer, plumbers mate etc. and provides a designation of a particular level of skill. It can be used to identify the generic type of labor resource that is required for a purpose without having to be specific about the actor (person or organization) providing the resource occurrence. It may be particularly useful when creating an overall plan for a process or processes. For instance, within maintenance or work planning there may be a known task that needs to be done which is planned to require a 'chargehand pipe fitter'. There may be several such labor resources available and so the need to identify which will be used is not necessary at the planning stage.

+ +

At a later stage, individual actors can be determined for the labor resources. This is achieved through specifiying the actor through IfcActor. The actor is then identified as the labour resource occurrence through the IfcRelAssignsToResource.RelatedResource attribute. The IfcLaborResource provides the IfcRelAssignsToResource.RelatingResource attribute.

+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcLaborResource defines the occurrence of any labor resource; common information about labor resource types is handled by IfcLaborResourceType. The IfcLaborResourceType (if present) may establish the common type name, common properties, common productivities for various task types using IfcRelAssignsToProcess. The IfcLaborResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+

+ +

Quantity use definition

+

The quantities relating to the IfcLaborResource are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. It is accessible by the inverse IsDefinedBy relationship. The following base quantities are defined and should be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. Other quantities can be defined being subjected to local standard of measurement with another string value assigned to Name and a value provided for MethodOfMeasurement. +

+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResource, a labor resource may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcLaborResource and RelatedObjects contains one or more IfcActor subtypes as shown in Figure 194. Such relationship indicates the specific people used as input for the resource. Such actors are nested according to organizational structure with the root organization assigned to the IfcProject. The IfcActor entity is used to represent the people or organizations.

+ + + + +

Figure 194 — Labor resource assignment use

+ +
" +2714;IfcCrewResource;" + +

IfcCrewResource represents a collection of internal resources used in construction processes.

+ +
+HISTORY: New Entity in IFC Release 2.0. Base type and documentation extended in IFC2x4 +
+ +

Identification of people and equipment of a crew is achieved through their specification at the level of the component. Therefore, knowing which persons are within a crew is achieved through identifying the persons assigned to each IfcLaborResource within the IfcCrewResource. Similarly, identifying that a screwing machine for pipe fitting forms part of the crew is achieved by relating an appropriate instance of IfcElementComponent to the IfcConstructionEquipmentResource forming an element of the IfcCrewResource.

+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcCrewResource defines the occurrence of any crew resource; common information about crew resource types is handled by IfcCrewResourceType. The IfcCrewResourceType (if present) may establish the common type name, common properties, and common productivities for various task types using IfcRelAssignsToProcess. The IfcCrewResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+ +
" +2722;IfcSubContractResource;" + +

IfcSubContractResource is a construction resource needed in a construction process that represents a sub-contractor.

+ +
+HISTORY: New Entity in IFC Release 2.0. Base type and documentation extended in IFC 2x4. +
+
+IFC2x4 CHANGE: The attribute SubContractor has been deleted; use IfcRelAssignsToResource to assign an IfcActor to fulfill the role as the subcontractor. The attribute JobDescription has been deleted; use LongDescription to describe the job. +
+ +

An IfcSubContractResource can be used in cost estimating and work planning with or without specifying the subcontractor and contract agreement.

+

The purpose of an IfcSubContractResource is to indicate work of a particular type that is that is to be engaged through the use of a sub-contract. It's aim is to identify the description of the sub-contract work required. It can be used to identify the generic type of sub-contract resource that is required for a purpose without having to be specific about the actor (person or organization) providing the resource occurrence. It may be particularly useful when creating an overall plan for a process or processes. For instance, within maintenance or work planning there may be a known task that needs to be done which is planned to require an 'insulation specialist'.

+

A subcontract resource may be described at various stages and levels of detail through its assignments:

+
    +
  • Subcontract resource designated for particular tasks
  • +
  • Actors identified to request bids
  • +
  • Cost schedules (bids) received from actors
  • +
  • Project order (work order, change order, etc.) executed
  • +
+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcSubContractResource defines the occurrence of any subcontract resource; common information about subcontract resource types is handled by IfcSubContractResourceType. The IfcSubContractResourceType (if present) may establish the common type name, common properties, and common productivities for various task types using IfcRelAssignsToProcess. The IfcSubContractResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+

+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResource, a subcontract resource may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcSubContractResource and RelatedObjects contains one or more IfcActor, IfcCostSchedule, and/or IfcWorkOrder objects as shown in Figure 195. An IfcActor indicates a specific organization to be considered to fulfill the resource or invited to bid on the resource. An IfcCostSchedule indicates a bid or price quote made on behalf of an organization. An IfcProjectOrder indicates a specific work order committed to fulfill the resource.

+ + + + +

Figure 195 — Subcontract assignment use

+ +
" +2730;IfcConstructionProductResource;" + +

IfcConstructionProductResource defines the role of a product that is consumed (wholly or partially), or occupied in the performance of construction.

+ +
+HISTORY: New Entity in IFC Release 2.0. Renamed from IfcProductResource in IFC 2x. Base type and documentation extended in IFC2x4. +
+ +

Occurrences of IfcConstructionProductResource are usage of products to assist the process of construction. More specifically, they are usage of products that result from some construction processes and that are then used as resources to facilitate further construction. For instance, formworks can be instantiated as products resulting from the process ‘constructing formwork’. However, they are used as resources in the process ‘pouring concrete’ in a later stage of the project. IfcConstructionProductResource occurrences are explicitly instances of IfcProduct and may be drawn from various of the subtypes, for instance IfcElementComponent, IfcElementAssembly, IfcProxy (for particular cases where more precise usage details are not available). The product that is used as a construction resource is referenced using the IfcRelAssignsToResource.RelatedObjects relationship.

+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcConstructionProductResource defines the occurrence of any product resource; common information about product resource types is handled by IfcConstructionProductResourceType. The IfcConstructionProductResourceType (if present) may establish the common type name, common properties, and common productivities for various task types using IfcRelAssignsToProcess. The IfcConstructionProductResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+

+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResource, a construction product resource may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionProductResource and RelatedObjects contains one or more IfcProduct subtypes as shown in Figure 185. Such relationship indicates the products used as input for the resource. Such products are not contained within a building structure but are referenced within a construction spatial zone, specifically IfcSpatialZone with PredefinedType=CONSTRUCTION, which is aggregated within the IfcProject. There may be multiple chains of production such that the assigned products may have their own task and resource assignments.

+ + + +

Figure 185 — Construction product resource assignment

+ + +
" +2738;IfcConstructionMaterialResource;" + +

IfcConstructionMaterialResource identifies a material resource type in a construction project.

+ +
+HISTORY: New Entity in IFC Release 2.0. Base type and documentation extended in IFC2x4. +
+ +
+IFC2x4 NOTE: The attribute Suppliers has been deleted; use IfcRelAssignsToResource to assign an IfcActor to fulfill the role as a supplier. The attribute UsageRatio has been deleted; use BaseQuantityConsumed and BaseQuantityProduced to indicate material usage. +
+ +

Occurrences of IfcConstructionMaterialResource are consumed (wholly or partially), or occupied during a construction work task (IfcTask).

+ +

Similar to IfcConstructionProductResource, sometimes things such as 5000kg of gravel are already instantiated as an IfcProduct because it is a result of a work task (for example, ‘transporting gravel’). In this case, the instance of IfcConstructionMaterialResource can be associated with the product instance ‘5000kg of gravel’ to provide more information for resource uses. Nevertheless, IfcConstructionMaterialResource should only be used to represent resource usage (for example ‘gravel’), but not product substances (for example, ‘5000kg of gravel’).

+

Note: This class is not the same as IfcMaterial; the former can typically represent the type of bulk materials such as sand, gravels, nails and so on (note these can be instantiated from IfcProduct as well depending their uses in the system) used in a construction process. The latter is about physical materials used in a physical building element typically with detailed positioning (e.g. offset) and layering information.

+

Quantities for an IfcConstructionMaterialResource are defined through IfcRelDefinesByProperty and use IfcElementQuantity.

+ +

Use definitions for composition, assignment, constraints, time series, and baselines are described at the base type IfcConstructionResource.

+ +

Type use definition

+

IfcConstructionMaterialResource defines the occurrence of any material resource; common information about material resource types is handled by IfcConstructionMaterialResourceType. The IfcConstructionMaterialResourceType (if present) may establish the common type name, common properties, and common productivities for various task types using IfcRelAssignsToProcess. The IfcConstructionMaterialResourceType is attached using the IfcRelDefinesByType.RelatingType objectified relationship and is accessible by the inverse IsTypedBy attribute.

+

+ +

Quantity use definition

+

The quantities relating to the IfcConstructionMaterialResource are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. It is accessible by the inverse IsDefinedBy relationship. The following base quantities are defined and should be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. Other quantities can be defined being subjected to local standard of measurement with another string value assigned to Name and a value provided for MethodOfMeasurement. +

+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResource, a construction material resource may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionMaterialResource and RelatedObjects contains one or more IfcProduct subtypes as shown in Figure 184. Such relationship indicates the physical material used as input for the resource. Such products are not contained within a building structure but are referenced within a construction spatial zone, specifically IfcSpatialZone with PredefinedType=CONSTRUCTION, which is aggregated within the IfcProject. The IfcGeographicElement object is used to represent the physical material occurrence, which may optionally have placement and representation indicating intended storage on the construction site. There may be multiple chains of production such that the assigned product material(s) may have their own task and resource assignments for transporting or extracting such material.

+ + + +

Figure 184 — Construction material resource assignment

+ +
" +2762;IfcConstructionResourceType;" + +

IfcConstructionResourceType is an abstract generalization of the different resource types used in construction projects, mainly labor, material, equipment and product resource types, plus subcontracted resource types and aggregations such as a crew resource type.

+ +

A resource type represents a model of ""use of something"" and does not necessarily correspond to a specific type of object such as a person or vehicle, but represents possible usages of such objects such as general labor or an equipment fleet. A resource type can either represent usage in general (consumption attributes defined but no task type assignment) or a task-specific resource type (production attributes defined and having an IfcTask assignment).

+ +

A construction resource type captures common productivities and cost rates for applying resources to particular task types.

+ +
+HISTORY: New entity in IFC2x4. +
+ +

Composition use definition

+

Resource types may be decomposed into nested resource types indicating productivities when applying the resource to specific task types using the IfcRelNests relationship where IfcRelNests.RelatingObject refers to the general resource type and IfcRelNests.RelatedObjects refers to one or more task-specific productivities. For example, an IfcLaborResourceType may be defined for ""Carpenter"" which may have a nested IfcLaborResourceType for ""Carpenter - Wall Framing"" and another nested IfcLaborResourceType for ""Carpenter - Drywall"", each of which may have productivities based according to specific task types (IfcTaskType).

+ +

Assignment use definition

+

Resource types may be assigned to process types (IfcTypeProcess subtypes) using the IfcRelAssignsToProcess relationship as shown in Figure 193. Such relationship indicates that the resource type applies to the process type for the use indicated (e.g. IfcTaskType.PredefinedType). Such relationship enables a scenario of placing an IfcProduct of a particular IfcTypeProduct, querying for a set of IfcTypeProcess process types for constructing such product (e.g. IfcTaskTypeEnum.CONSTRUCTION), querying each IfcTypeProcess for a set of IfcTypeResource resource types for carrying out the process, and finally choosing an IfcTypeProcess and IfcTypeResource combination resulting in the shortest time for instantiated IfcTask occurrence(s) and/or lowest-cost for instantiated IfcConstructionResource occurrence(s).

+ + + +

Figure 193 — Construction resource type assignment

+ +
" +2774;IfcCrewResourceType;" + +

The resource type IfcCrewResourceType defines commonly shared information for occurrences of crew resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+

It is used to define a crew resource specification the specific resource information that is common to all occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+

Occurrences of the IfcCrewResourceType are represented by instances of IfcCrewResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +
" +2777;IfcLaborResourceType;" +

The resource type IfcLaborResourceType defines commonly shared information for occurrences of labor resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+ +

It is used to define a labor resource specification (i.e. the specific resource information that is common to all occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+ +

Occurrences of the IfcLaborResourceType are represented by instances of IfcLaborResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +
" +2780;IfcSubContractResourceType;" + +

The resource type IfcSubContractResourceType defines commonly shared information for occurrences of subcontract resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+

It is used to define a subcontract resource specification (the specific resource information that is common to all +occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+

Occurrences of the IfcSubContractResourceType are represented by instances of IfcSubContractResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +
" +2783;IfcConstructionMaterialResourceType;" +

The resource type IfcConstructionMaterialType defines commonly shared information for occurrences of construction material resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+

It is used to define a construction material resource specification (i.e. the specific resource information that is common to all occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+

Occurrences of the IfcConstructionMaterialResourceType are represented by instances of IfcConstructionMaterialResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +

Assignment Use Definition

+

In addition to assignments specified at the base class IfcConstructionResourceType, a construction material resource type may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionMaterialResourceType and RelatedObjects contains one or more IfcTypeProduct subtypes. Such relationship indicates material specifications to be used as input, which is instantiated as an occurrence assigned for each resource occurrence. The IfcGeographicElementType product type may be used to hold the material representation (via IfcRelAssociatesMaterial. There may be multiple chains of production where such product type may have its own task and resource types assigned indicating how to transport or extract such material.

+ +
" +2786;IfcConstructionEquipmentResourceType;" + +

The resource type IfcConstructionEquipmentType defines commonly shared information for occurrences of construction equipment resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+

It is used to define a construction equipment resource specification (the specific resource information that is common to all occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+

Occurrences of the IfcConstructionEquipmentResourceType are represented by instances of IfcConstructionEquipmentResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResourceType, a construction equipment resource type may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionEquipmentResourceType and RelatedObjects contains one or more IfcTypeProduct subtypes. Such relationship indicates the type of equipment to be used as input, which is instantiated as an occurrence assigned for each resource occurrence. There may be multiple chains of production where such product type may have its own task and resource types assigned indicating how to assemble such equipment.

+ +
" +2789;IfcConstructionProductResourceType;" + +

The resource type IfcConstructionProductType defines commonly shared information for occurrences of construction product resources. The set of shared information may include:

+
    +
  • common productivities
  • +
  • common cost rates
  • +
  • common properties within shared property sets
  • +
+

It is used to define a construction product resource specification (i.e. the specific resource information that is common to all occurrences of that resource). Resource types may be exchanged without being already assigned to occurrences.

+

Occurrences of the IfcConstructionProductResourceType are represented by instances of IfcConstructionProductResource.

+ +
+HISTORY New entity in IFC2x4. +
+ +

Assignment use definition

+

In addition to assignments specified at the base class IfcConstructionResourceType, a construction product resource type may have assignments of its own using IfcRelAssignsToResource where RelatingResource refers to the IfcConstructionProductResourceType and RelatedObjects contains one or more IfcTypeProduct subtypes. Such relationship indicates the type of product to be used as input, which is instantiated as an occurrence assigned for each resource occurrence. There may be multiple chains of production where such product type may have its own task and resource types assigned.

+ +
" +2793;IfcMotorConnectionType;" + +

The energy conversion device type IfcMotorConnectionType defines commonly shared information for occurrences of motor connections. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a motor connection specification (i.e. the specific product information, that is common to all occurrences of that product type). Motor Connection types may be exchanged without being already assigned to occurrences. + Occurrences of IfcMotorConnectionType are represented by instances of IfcMotorConnection.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcMotorConnectionType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcMotorConnectionType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcMotorConnection for standard port definitions.

+ +
" +2796;IfcOutletType;" + +

The flow terminal type IfcOutletType defines commonly shared information for occurrences of outlets. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a outlet specification (i.e. the specific product information, that is common to all occurrences of that product type). Outlet types may be exchanged without being already assigned to occurrences. + Occurrences of IfcOutletType are represented by instances of IfcOutlet.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcOutletType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Conductor': Material from which the conductors are constructed.
  • +
  • 'Surface': Material from which the outlet plate is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcOutletType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcOutlet for standard port definitions.

+ +
" +2807;IfcElectricApplianceType;" + +

The flow terminal type IfcElectricApplianceType defines commonly shared information for occurrences of electric appliances. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a electric appliance specification (i.e. the specific product information, that is common to all occurrences of that product type). Electric Appliance types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricApplianceType are represented by instances of IfcElectricAppliance.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcElectricApplianceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricApplianceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricAppliance for standard port definitions.

+ +
" +2829;IfcLightFixtureType;" + +

The flow terminal type IfcLightFixtureType defines commonly shared information for occurrences of light fixtures. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a light fixture specification (i.e. the specific product information, that is common to all occurrences of that product type). Light Fixture types may be exchanged without being already assigned to occurrences. + Occurrences of IfcLightFixtureType are represented by instances of IfcLightFixture.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcLightFixtureType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcLightFixtureType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcLightFixture for standard port definitions.

+ +
" +2838;IfcLampType;" + +

The flow terminal type IfcLampType defines commonly shared information for occurrences of lamps. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a lamp specification (i.e. the specific product information, that is common to all occurrences of that product type). Lamp types may be exchanged without being already assigned to occurrences. + Occurrences of IfcLampType are represented by instances of IfcLamp.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcLampType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Bulb': Material from which the bulb is constructed (e.g. glass).
  • +
  • 'Conductor': Material from which the conductor is constructed.
  • +
  • 'Filament': Material from which the filament is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcLampType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcLamp for standard port definitions.

+ +
" +2853;IfcAudioVisualApplianceType;" + +

The flow terminal type IfcAudioVisualApplianceType defines commonly shared information for occurrences of audio-visual appliances. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a audio-visual appliance specification (i.e. the specific product information, that is common to all occurrences of that product type). Audio-Visual Appliance types may be exchanged without being already assigned to occurrences. + Occurrences of IfcAudioVisualApplianceType are represented by instances of IfcAudioVisualAppliance.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcAudioVisualApplianceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcAudioVisualApplianceType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcAudioVisualApplianceType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

+ +

Port Use Definition

+

The distribution ports relating to the IfcAudioVisualApplianceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcAudioVisualAppliance for standard port definitions.

+ +
" +2870;IfcCommunicationsApplianceType;" + +

The flow terminal type IfcCommunicationsApplianceType defines commonly shared information for occurrences of communications appliances. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a communications appliance specification (i.e. the specific product information, that is common to all occurrences of that product type). Communications Appliance types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCommunicationsApplianceType are represented by instances of IfcCommunicationsAppliance.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCommunicationsApplianceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcCommunicationsApplianceType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCommunicationsApplianceType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

    +
  • COMPUTER: May contain IfcAudioVisualAppliance components. Computers may be aggregated into audio-visual components such as displays, cameras, speakers, or microphones.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCommunicationsApplianceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCommunicationsAppliance for standard port definitions.

+ +
" +2888;IfcSwitchingDeviceType;" + +

The flow controller type IfcSwitchingDeviceType defines commonly shared information for occurrences of switching devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a switching device specification (i.e. the specific product information, that is common to all occurrences of that product type). Switching Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSwitchingDeviceType are represented by instances of IfcSwitchingDevice.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSwitchingDeviceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Conductor': Material from which the conductors are constructed.
  • +
  • 'Surface': Material from which the switch surface is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSwitchingDeviceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcSwitchingDevice for standard port definitions.

+ +
" +2903;IfcElectricTimeControlType;" + +

The flow controller type IfcElectricTimeControlType defines commonly shared information for occurrences of electric time controls. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a electric time control specification (i.e. the specific product information, that is common to all occurrences of that product type). Electric Time Control types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricTimeControlType are represented by instances of IfcElectricTimeControl.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcElectricTimeControlType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricTimeControlType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricTimeControl for standard port definitions.

+ +
" +2912;IfcProtectiveDeviceType;" + +

The flow controller type IfcProtectiveDeviceType defines commonly shared information for occurrences of protective devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a protective device specification (i.e. the specific product information, that is common to all occurrences of that product type). Protective Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcProtectiveDeviceType are represented by instances of IfcProtectiveDevice.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcProtectiveDeviceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcProtectiveDeviceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcProtectiveDevice for standard port definitions.

+ +
" +2925;IfcElectricDistributionBoardType;" + +

The flow controller type IfcElectricDistributionBoardType defines commonly shared information for occurrences of distribution boards. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a distribution board specification (i.e. the specific product information, that is common to all occurrences of that product type). Distribution Board types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricDistributionBoardType are represented by instances of IfcElectricDistributionBoard.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcElectricDistributionBoardType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricDistributionBoardType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricDistributionBoard for standard port definitions.

+ +
" +2935;IfcCableCarrierFittingType;" + +

The flow fitting type IfcCableCarrierFittingType defines commonly shared information for occurrences of cable carrier fittings. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cable carrier fitting specification (i.e. the specific product information, that is common to all occurrences of that product type). Cable Carrier Fitting types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCableCarrierFittingType are represented by instances of IfcCableCarrierFitting.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowFittingType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCableCarrierFittingType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCableCarrierFittingType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCableCarrierFitting for standard port definitions.

+ +
" +2945;IfcJunctionBoxType;" + +

The flow fitting type IfcJunctionBoxType defines commonly shared information for occurrences of junction boxs. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a junction box specification (i.e. the specific product information, that is common to all occurrences of that product type). Junction Box types may be exchanged without being already assigned to occurrences. + Occurrences of IfcJunctionBoxType are represented by instances of IfcJunctionBox.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowFittingType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcJunctionBoxType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcJunctionBoxType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcJunctionBox for standard port definitions.

+ +
" +2953;IfcCableFittingType;" + +

The flow fitting type IfcCableFittingType defines commonly shared information for occurrences of cable fittings. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cable fitting specification (i.e. the specific product information, that is common to all occurrences of that product type). Cable Fitting types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCableFittingType are represented by instances of IfcCableFitting.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowFittingType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCableFittingType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Conductor': Material from which the conductors are constructed, such as Aluminium or Copper.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCableFittingType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCableFitting for standard port definitions.

+ +
" +2964;IfcElectricFlowStorageDeviceType;" + +

The flow storage device type IfcElectricFlowStorageDeviceType defines commonly shared information for occurrences of electric flow storage devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a electric flow storage device specification (i.e. the specific product information, that is common to all occurrences of that product type). Electric Flow Storage Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricFlowStorageDeviceType are represented by instances of IfcElectricFlowStorageDevice.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowStorageDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcElectricFlowStorageDeviceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricFlowStorageDeviceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricFlowStorageDevice for standard port definitions.

+ +
" +2975;IfcCableSegmentType;" + +

The flow segment type IfcCableSegmentType defines commonly shared information for occurrences of cable segments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cable segment specification (i.e. the specific product information, that is common to all occurrences of that product type). Cable Segment types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCableSegmentType are represented by instances of IfcCableSegment.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowSegmentType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcCableSegmentType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Conductor': The material from which the conductor is constructed such as Aluminium or Copper.
  • +
  • 'Insulation': The material from which the insulation is constructed such as PVC, PEX, EPR, etc.
  • +
  • 'Screen': The material from which the screen that covers the sheath is constructed (mantel) such as Aluminium, Copper, Steel , Lead.
  • +
  • 'Sheath': The outer sheathing of the cable which may be color-coded.
  • +
+ +

Composition Use Definition

+

The IfcCableSegmentType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCableSegmentType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

+ +

Port Use Definition

+

The distribution ports relating to the IfcCableSegmentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCableSegment for standard port definitions.

+ +
" +2985;IfcCableCarrierSegmentType;" + +

The flow segment type IfcCableCarrierSegmentType defines commonly shared information for occurrences of cable carrier segments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cable carrier segment specification (i.e. the specific product information, that is common to all occurrences of that product type). Cable Carrier Segment types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCableCarrierSegmentType are represented by instances of IfcCableCarrierSegment.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowSegmentType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcCableCarrierSegmentType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Body': Material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCableCarrierSegmentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCableCarrierSegment for standard port definitions.

+ +
" +2995;IfcProtectiveDeviceTrippingUnitType;" + +

The distribution control element type IfcProtectiveDeviceTrippingUnitType defines commonly shared information for occurrences of protective device tripping units. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a protective device tripping unit specification (i.e. the specific product information, that is common to all occurrences of that product type). Protective Device Tripping Unit types may be exchanged without being already assigned to occurrences. + Occurrences of IfcProtectiveDeviceTrippingUnitType are represented by instances of IfcProtectiveDeviceTrippingUnit.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcDistributionControlElementType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcProtectiveDeviceTrippingUnitType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcProtectiveDeviceTrippingUnitType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcProtectiveDeviceTrippingUnit for standard port definitions.

+ +
" +3005;IfcCableSegment;"

A cable segment is a flow segment used to carry electrical power, data, or telecommunications signals.

+

A cable segment is used to typically join two sections of an electrical network or a network of components carrying the electrical service.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCableSegment defines the occurrence of any cable segment; common information about cable segment types is handled by IfcCableSegmentType. +The IfcCableSegmentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCableSegmentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCableSegmentType has ports or aggregated elements, such objects are reflected at the IfcCableSegment occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCableSegmentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCableSegmentType.HasPropertySets. +If both are given, then the properties directly defined at IfcCableSegment override the properties defined at IfcCableSegmentType. +Refer to the documentation at the supertype IfcFlowSegment and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCableSegment is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCableSegmentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Conductor: Material from which the conductors are constructed, such as Aluminium or Copper.
  • +
  • Insulation: The material from which the insulation is constructed such as PVC, PEX, or EPR.
  • +
  • Screen: The material from which the screen that covers the sheath is constructed (mantel) such as Aluminium, Copper, Steel, or Lead.
  • +
  • Sheath: The outer sheathing of the cable which may be color-coded.
  • +
+ +

Composition Use Definition

+

The IfcCableSegment may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCableSegment and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • CABLESEGMENT +
      +
    • May contain IfcCableSegment components having PredefinedType=CORESEGMENT. Cable segments may be aggregated into cable cores.
    • +
    +
  • +
  • CORESEGMENT +
      +
    • May contain IfcCableSegment components having PredefinedType=CONDUCTORSEGMENT. Cable cores may be aggregated into cable conductors.
    • +
    +
  • +
+ +

Connection Use Definition

+

The IfcCableSegment may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcCableSegment are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cable segment occurrence is defined by IfcCableSegmentType, then the port occurrences must reflect those defined at the IfcCableSegmentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCableSegment PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3009;IfcCableCarrierSegment;"

A cable carrier segment is a flow segment that is specifically used to carry and support cabling.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCableCarrierSegment defines the occurrence of any cable carrier segment; common information about cable carrier segment types is handled by IfcCableCarrierSegmentType. +The IfcCableCarrierSegmentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCableCarrierSegmentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCableCarrierSegmentType has ports or aggregated elements, such objects are reflected at the IfcCableCarrierSegment occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCableCarrierSegmentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCableCarrierSegmentType.HasPropertySets. +If both are given, then the properties directly defined at IfcCableCarrierSegment override the properties defined at IfcCableCarrierSegmentType. +Refer to the documentation at the supertype IfcFlowSegment and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCableCarrierSegment is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCableCarrierSegmentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCableCarrierSegment are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cable carrier segment occurrence is defined by IfcCableCarrierSegmentType, then the port occurrences must reflect those defined at the IfcCableCarrierSegmentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCableCarrierSegment PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3013;IfcCableCarrierFitting;"

A cable carrier fitting is a fitting that is placed at junction or transition in a cable carrier system.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCableCarrierFitting defines the occurrence of any cable carrier fitting; common information about cable carrier fitting types is handled by IfcCableCarrierFittingType. +The IfcCableCarrierFittingType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCableCarrierFittingType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCableCarrierFittingType has ports or aggregated elements, such objects are reflected at the IfcCableCarrierFitting occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCableCarrierFittingType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCableCarrierFittingType.HasPropertySets. +If both are given, then the properties directly defined at IfcCableCarrierFitting override the properties defined at IfcCableCarrierFittingType. +Refer to the documentation at the supertype IfcFlowFitting and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCableCarrierFitting is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCableCarrierFittingType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCableCarrierFitting are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cable carrier fitting occurrence is defined by IfcCableCarrierFittingType, then the port occurrences must reflect those defined at the IfcCableCarrierFittingType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCableCarrierFitting PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3017;IfcCableFitting;"

A cable fitting is a fitting that is placed at a junction, transition or termination in a cable system.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCableFitting defines the occurrence of any cable fitting; common information about cable fitting types is handled by IfcCableFittingType. +The IfcCableFittingType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCableFittingType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCableFittingType has ports or aggregated elements, such objects are reflected at the IfcCableFitting occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCableFittingType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCableFittingType.HasPropertySets. +If both are given, then the properties directly defined at IfcCableFitting override the properties defined at IfcCableFittingType. +Refer to the documentation at the supertype IfcFlowFitting and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCableFitting is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCableFittingType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
  • Conductor: Material from which the conductors are constructed, such as Aluminium or Copper.
  • +
+ +

Connection Use Definition

+

The IfcCableFitting may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcCableFitting are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cable fitting occurrence is defined by IfcCableFittingType, then the port occurrences must reflect those defined at the IfcCableFittingType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCableFitting PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3021;IfcJunctionBox;"

A junction box is an enclosure within which cables are connected.

+

Cables may be members of an electrical circuit (for electrical power systems) or be information carriers (in a telecommunications system). A junction box is typically intended to conceal a cable junction from sight, eliminate tampering or provide a safe place for electrical connection.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcJunctionBox defines the occurrence of any junction box; common information about junction box types is handled by IfcJunctionBoxType. +The IfcJunctionBoxType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcJunctionBoxType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcJunctionBoxType has ports or aggregated elements, such objects are reflected at the IfcJunctionBox occurrence using the IfcRelDefinesByObject relationship.

+

Figure 200 illustrates junction box type use.

+

Figure 200 — Junction box type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcJunctionBoxType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcJunctionBoxType.HasPropertySets. +If both are given, then the properties directly defined at IfcJunctionBox override the properties defined at IfcJunctionBoxType. +Refer to the documentation at the supertype IfcFlowFitting and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcJunctionBox is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcJunctionBoxType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Connection Use Definition

+

The IfcJunctionBox may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcJunctionBox are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the junction box occurrence is defined by IfcJunctionBoxType, then the port occurrences must reflect those defined at the IfcJunctionBoxType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcJunctionBox PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • DATA +
      +
    • Line#1 (DATA, SINK): A data line, typically a cable connecting from a network router communications device.
    • +
    • Line#2 (DATA, SINK): A data line, typically a cable connecting from a network router communications device.
    • +
    • Gang#1 (DATA, SOURCE): A slot to house a data outlet containing one or more jacks, ordered from left-to-right.
    • +
    • Gang#2 (DATA, SOURCE): A slot to house a data outlet containing one or more jacks, ordered from left-to-right.
    • +
    +
  • +
  • POWER +
      +
    • Line (ELECTRICAL, SINK): The electrical supply line, typically a cable connecting from another junction box or from a protective device within a distribution board.
    • +
    • Load (ELECTRICAL, SOURCE): The next load in the circuit, typically a cable connecting to another junction box.
    • +
    • Gang#1 (ELECTRICAL, SOURCE): A slot to house a switch or outlet, ordered from left-to-right.
    • +
    • Gang#2 (ELECTRICAL, SOURCE): A slot to house a switch or outlet, ordered from left-to-right.
    • +
    • Gang#3 (ELECTRICAL, SOURCE): A slot to house a switch or outlet, ordered from left-to-right.
    • +
    • Gang#4 (ELECTRICAL, SOURCE): A slot to house a switch or outlet, ordered from left-to-right.
    • +
    +
  • +
+

Figure 201 illustrates junction box port use.

+

Figure 201 — Junction box port use

+ + " +3025;IfcElectricFlowStorageDevice;"

An electric flow storage device is a device in which electrical energy is stored and from which energy may be progressively released.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricFlowStorageDevice defines the occurrence of any electric flow storage device; common information about electric flow storage device types is handled by IfcElectricFlowStorageDeviceType. +The IfcElectricFlowStorageDeviceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricFlowStorageDeviceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricFlowStorageDeviceType has ports or aggregated elements, such objects are reflected at the IfcElectricFlowStorageDevice occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricFlowStorageDeviceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricFlowStorageDeviceType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricFlowStorageDevice override the properties defined at IfcElectricFlowStorageDeviceType. +Refer to the documentation at the supertype IfcFlowStorageDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricFlowStorageDevice is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricFlowStorageDeviceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricFlowStorageDevice are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric flow storage device occurrence is defined by IfcElectricFlowStorageDeviceType, then the port occurrences must reflect those defined at the IfcElectricFlowStorageDeviceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricFlowStorageDevice PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • Line (ELECTRICAL, SINK): Incoming power used to charge the flow storage device.
  • +
  • Load (ELECTRICAL, SOURCE): Outgoing power backed by the flow storage device.
  • +
+ " +3029;IfcOutlet;"

An outlet is a device installed at a point to receive one or more inserted plugs for electrical power or communications.

+

Power outlets are commonly connected within a junction box; data outlets may be directly connected to a wall. For power outlets sharing the same circuit within a junction box, the ports should indicate the logical wiring relationship to the enclosing junction box, even though they may be physically connected to a cable going to another outlet, switch, or fixture.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcOutlet defines the occurrence of any outlet; common information about outlet types is handled by IfcOutletType. +The IfcOutletType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcOutletType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcOutletType has ports or aggregated elements, such objects are reflected at the IfcOutlet occurrence using the IfcRelDefinesByObject relationship.

+

Figure 206 illustrates outlet type use.

+

Figure 206 — Outlet type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcOutletType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcOutletType.HasPropertySets. +If both are given, then the properties directly defined at IfcOutlet override the properties defined at IfcOutletType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcOutlet is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcOutletType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
  • Conductor: Material from which the conductors are constructed.
  • +
  • Surface: Material from which the outer plate is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcOutlet are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the outlet occurrence is defined by IfcOutletType, then the port occurrences must reflect those defined at the IfcOutletType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcOutlet PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • DATAOUTLET +
      +
    • Line#1 (DATA, SINK): A data line, connecting to a cable commonly originating from a port on a router.
    • +
    • Line#2 (DATA, SINK): A data line, connecting to a cable commonly originating from a port on a router.
    • +
    • Jack#1 (DATA, SOURCE): Jacks in order of layout, going to the right and then down, which may accept a cable.
    • +
    • Jack#2 (DATA, SOURCE): Jacks in order of layout, going to the right and then down, which may accept a cable.
    • +
    +
  • +
  • POWEROUTLET +
      +
    • Line (ELECTRICAL, SINK): The source of power, which may refer to a port on a junction box.
    • +
    • Jack#1 (ELECTRICAL, SOURCE): Upper jack, accepting a plug from an appliance or fixture.
    • +
    • Jack#2 (ELECTRICAL, SOURCE): Lower jack, accepting a plug from an appliance or fixture.
    • +
    +
  • +
  • TELEPHONEOUTLET +
      +
    • Line#1 (DATA, SINK): A telephone line, connecting to a cable originating from a telecommunications distribution board.
    • +
    • Line#2 (DATA, SINK): A telephone line, connecting to a cable originating from a telecommunications distribution board.
    • +
    • Jack#1 (DATA, SOURCE): Jacks in order of layout, going to the right and then down, which may accept a cable.
    • +
    • Jack#2 (DATA, SOURCE): Jacks in order of layout, going to the right and then down, which may accept a cable.
    • +
    +
  • +
+

Figure 207 illustrates outlet port use.

+

Figure 207 — Outlet port use

+ + " +3033;IfcLightFixture;"

A light fixture is a container that is designed for the purpose of housing one or more lamps and optionally devices that control, restrict or vary their emission.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcLightFixture defines the occurrence of any light fixture; common information about light fixture types is handled by IfcLightFixtureType. +The IfcLightFixtureType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcLightFixtureType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcLightFixtureType has ports or aggregated elements, such objects are reflected at the IfcLightFixture occurrence using the IfcRelDefinesByObject relationship.

+

Figure 204 illustrates light fixture type use.

+

Figure 204 — Light fixture type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcLightFixtureType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcLightFixtureType.HasPropertySets. +If both are given, then the properties directly defined at IfcLightFixture override the properties defined at IfcLightFixtureType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcLightFixture is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcLightFixtureType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Connection Use Definition

+

The IfcLightFixture may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcLightFixture are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the light fixture occurrence is defined by IfcLightFixtureType, then the port occurrences must reflect those defined at the IfcLightFixtureType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcLightFixture PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • Line (ELECTRICAL, SINK): The power supply line, typically a cable connected to a switch.
  • +
  • Socket#1 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#2 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#3 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#4 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#5 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#6 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#7 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
  • Socket#8 (LIGHTING, SOURCE): A lamp socket within the light fixture.
  • +
+

Figure 205 illustrates light fixture port use.

+

Figure 205 — Light fixture port use

+ + " +3037;IfcLamp;"

A lamp is an artificial light source such as a light bulb or tube.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcLamp defines the occurrence of any lamp; common information about lamp types is handled by IfcLampType. +The IfcLampType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcLampType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcLampType has ports or aggregated elements, such objects are reflected at the IfcLamp occurrence using the IfcRelDefinesByObject relationship.

+

Figure 202 illustrates lamp type use.

+

Figure 202 — Lamp type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcLampType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcLampType.HasPropertySets. +If both are given, then the properties directly defined at IfcLamp override the properties defined at IfcLampType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcLamp is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcLampType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Bulb: Material from which the bulb is constructed such as glass.
  • +
  • Conductor: Material from which the conductor is constructed.
  • +
  • Filament: Material from which the filament is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcLamp are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the lamp occurrence is defined by IfcLampType, then the port occurrences must reflect those defined at the IfcLampType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcLamp PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • Socket (LIGHTING, SINK): The socket providing electricity.
  • +
+

Figure 203 illustrates lamp port use.

+

Figure 203 — Lamp port use

+ + " +3041;IfcElectricAppliance;"

A communications appliance transmits and receives electronic or digital information as data or sound.

+

Communication appliances may be fixed in place or may be able to be moved from one space to another. Communication appliances require an electrical supply that may be supplied either by an electrical circuit or provided from a local battery source.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricAppliance defines the occurrence of any electric appliance; common information about electric appliance types is handled by IfcElectricApplianceType. +The IfcElectricApplianceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricApplianceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricApplianceType has ports or aggregated elements, such objects are reflected at the IfcElectricAppliance occurrence using the IfcRelDefinesByObject relationship.

+

Figure 196 illustrates electric appliance type use.

+

Figure 196 — Electric appliance type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricApplianceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricApplianceType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricAppliance override the properties defined at IfcElectricApplianceType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricAppliance is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricApplianceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricAppliance are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric appliance occurrence is defined by IfcElectricApplianceType, then the port occurrences must reflect those defined at the IfcElectricApplianceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricAppliance PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 197 illustrates electric appliance port use.

+

Figure 197 — Electric appliance port use

+ + " +3045;IfcAudioVisualAppliance;"

An audio-visual appliance is a device that displays, captures, transmits, or receives audio or video.

+

Audio-visual appliances may be fixed in place or may be able to be moved from one space to another. They may require an electrical supply that may be supplied either by an electrical circuit or provided from a local battery source. Audio-visual appliances may be connected to data circuits including specialist circuits for audio visual purposes only.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcAudioVisualAppliance defines the occurrence of any audio visual appliance; common information about audio visual appliance types is handled by IfcAudioVisualApplianceType. +The IfcAudioVisualApplianceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcAudioVisualApplianceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcAudioVisualApplianceType has ports or aggregated elements, such objects are reflected at the IfcAudioVisualAppliance occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcAudioVisualApplianceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcAudioVisualApplianceType.HasPropertySets. +If both are given, then the properties directly defined at IfcAudioVisualAppliance override the properties defined at IfcAudioVisualApplianceType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcAudioVisualAppliance is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcAudioVisualApplianceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcAudioVisualAppliance may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcAudioVisualAppliance and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • May contain IfcAudioVisualAppliance components.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAudioVisualAppliance are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the audio visual appliance occurrence is defined by IfcAudioVisualApplianceType, then the port occurrences must reflect those defined at the IfcAudioVisualApplianceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcAudioVisualAppliance PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3049;IfcCommunicationsAppliance;"

A communications appliance transmits and receives electronic or digital information as data or sound.

+

Communication appliances may be fixed in place or may be able to be moved from one space to another. Communication appliances require an electrical supply that may be supplied either by an electrical circuit or provided from a local battery source.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCommunicationsAppliance defines the occurrence of any communications appliance; common information about communications appliance types is handled by IfcCommunicationsApplianceType. +The IfcCommunicationsApplianceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCommunicationsApplianceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCommunicationsApplianceType has ports or aggregated elements, such objects are reflected at the IfcCommunicationsAppliance occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCommunicationsApplianceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCommunicationsApplianceType.HasPropertySets. +If both are given, then the properties directly defined at IfcCommunicationsAppliance override the properties defined at IfcCommunicationsApplianceType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCommunicationsAppliance is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCommunicationsApplianceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcCommunicationsAppliance may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCommunicationsAppliance and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • COMPUTER +
      +
    • May contain IfcAudioVisualAppliance components. Computers may be aggregated into audio-visual components such as displays, cameras, speakers, or microphones.
    • +
    +
  • +
+ +

Connection Use Definition

+

The IfcCommunicationsAppliance may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcCommunicationsAppliance are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the communications appliance occurrence is defined by IfcCommunicationsApplianceType, then the port occurrences must reflect those defined at the IfcCommunicationsApplianceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCommunicationsAppliance PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • ANTENNA +
      +
    • Power (ELECTRICAL, SINK): Receives electrical power.
    • +
    • Radio (SIGNAL, SINK): Electromagnetic waves.
    • +
    • Signal (SIGNAL, SOURCE): The modulated analog signal in a circuit, such as a cable connected to a modem.
    • +
    +
  • +
  • COMPUTER +
      +
    • Power (ELECTRICAL, SINK): Receives electrical power.
    • +
    • Network (DATA, SINK): A network connection, may be wired or wireless (implicit antenna), such as a cable connected from a data outlet jack or from a router communications appliance. While communication is bidirectional, the router-end is considered to be the source.
    • +
    • Device (CONTROL, SOURCE): A device connection such as USB or serial, which may connect to equipment such as a building automation controller.
    • +
    • Display (AUDIOVISUAL, SOURCE): Audio/video output, such as a cable connected to a display, which may be aggregated into separate channels.
    • +
    +
  • +
  • FAX + +
  • +
  • MODEM +
      +
    • Power (ELECTRICAL, SINK): Receives electrical power.
    • +
    • Signal (SIGNAL, SINK): Modulated analog signal, typically a cable connecting from a communications junction box or an antenna.
    • +
    • Internet (DATA, SOURCE): Internet data network.
    • +
    • Television (TV, SOURCE): Television modulated signal.
    • +
    • Telephone (TELEPHONE, SOURCE): Telephone communications.
    • +
    +
  • +
  • PRINTER +
      +
    • Power (ELECTRICAL, SINK): Receives electrical power.
    • +
    • Network (DATA, SINK): A network connection, may be wired or wireless (implicit antenna), such as a cable connected from a data outlet jack or from a router communications appliance. While communication is bidirectional, the router-end is considered to be the source.
    • +
    +
  • +
  • REPEATER + +
  • +
  • ROUTER +
      +
    • Power (ELECTRICAL, SINK): Receives electrical power.
    • +
    • Uplink (DATA, SINK): Uplink from another network, such as a cable connected to another router or the Internet.
    • +
    • Link#1 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#2 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#3 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#4 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#5 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#6 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#7 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    • Link#8 (DATA, SOURCE): A network link to a routed device such as a cable connecting to a computer.
    • +
    +
  • +
+ " +3053;IfcSwitchingDevice;"

A switch is used in a cable distribution system (electrical circuit) to control or modulate the flow of electricity.

+

Switches include those used for electrical power, communications, audio-visual, or other distribution system types as determined by the available ports.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcSwitchingDevice defines the occurrence of any switching device; common information about switching device types is handled by IfcSwitchingDeviceType. +The IfcSwitchingDeviceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcSwitchingDeviceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcSwitchingDeviceType has ports or aggregated elements, such objects are reflected at the IfcSwitchingDevice occurrence using the IfcRelDefinesByObject relationship.

+

Figure 208 illustrates switching device type use.

+

Figure 208 — Switching device type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcSwitchingDeviceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcSwitchingDeviceType.HasPropertySets. +If both are given, then the properties directly defined at IfcSwitchingDevice override the properties defined at IfcSwitchingDeviceType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcSwitchingDevice is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSwitchingDeviceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
  • Conductor: Material from which the conductors are constructed.
  • +
  • Surface: Material from which the switch surface is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSwitchingDevice are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the switching device occurrence is defined by IfcSwitchingDeviceType, then the port occurrences must reflect those defined at the IfcSwitchingDeviceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcSwitchingDevice PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 209 illustrates switching device port use.

+

Figure 209 — Switching device port use

+ + " +3057;IfcProtectiveDevice;"

A protective device breaks an electrical circuit when a stated electric current that passes through it is exceeded.

+

A protective device provides protection against electrical current only (not as a general protective device). It may be used to represent the complete set of elements including both the tripping unit and the breaking unit that provide the protection. This may be particularly useful at earlier stages of design where the approach to breaking the electrical supply may be determined but the method of tripping may not. Alternatively, this entity may be used to specifically represent the breaking unit alone (in which case the tripping unit will also be specifically identified). This entity is specific to dedicated protective devices and excludes electrical outlets that may have circuit protection.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcProtectiveDevice defines the occurrence of any protective device; common information about protective device types is handled by IfcProtectiveDeviceType. +The IfcProtectiveDeviceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcProtectiveDeviceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcProtectiveDeviceType has ports or aggregated elements, such objects are reflected at the IfcProtectiveDevice occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcProtectiveDeviceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcProtectiveDeviceType.HasPropertySets. +If both are given, then the properties directly defined at IfcProtectiveDevice override the properties defined at IfcProtectiveDeviceType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcProtectiveDevice is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcProtectiveDeviceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcProtectiveDevice are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the protective device occurrence is defined by IfcProtectiveDeviceType, then the port occurrences must reflect those defined at the IfcProtectiveDeviceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcProtectiveDevice PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • CIRCUITBREAKER +
      +
    • Line (ELECTRICAL, SINK): The supply line, typically connected from a slot in a distribution board.
    • +
    • Load (ELECTRICAL, SOURCE): The load protected by this device, typically a cable connected to a device or the first junction box of a circuit.
    • +
    +
  • +
+ " +3061;IfcElectricDistributionBoard;"

A distribution board is a flow controller in which instances of electrical devices are brought together at a single place for a particular purpose.

+

A distribution provides a housing for connected electrical distribution elements so that they can be viewed, operated or acted upon from a single place. Each connected item may have its own geometric representation and location.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricDistributionBoard defines the occurrence of any electric distribution board; common information about electric distribution board types is handled by IfcElectricDistributionBoardType. +The IfcElectricDistributionBoardType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricDistributionBoardType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricDistributionBoardType has ports or aggregated elements, such objects are reflected at the IfcElectricDistributionBoard occurrence using the IfcRelDefinesByObject relationship.

+

Figure 198 illustrates electric distribution board type use.

+

Figure 198 — Electric distribution board type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricDistributionBoardType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricDistributionBoardType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricDistributionBoard override the properties defined at IfcElectricDistributionBoardType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricDistributionBoard is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricDistributionBoardType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricDistributionBoard are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric distribution board occurrence is defined by IfcElectricDistributionBoardType, then the port occurrences must reflect those defined at the IfcElectricDistributionBoardType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricDistributionBoard PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • CONSUMERUNIT +
      +
    • Line (ELECTRICAL, SINK): Incoming power, such as a cable connecting from the electrical utility or another distribution board.
    • +
    • Ground (EARTHING, SOURCE): Grounding connection, such as a cable connecting to a cable fitting connected to a cold water pipe segment coming from the ground.
    • +
    • Circuit#1 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#2 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#3 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#4 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#5 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#6 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#7 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    • Circuit#8 (ELECTRICAL, SOURCE): A downstream circuit, typically a circuit breaker protective device.
    • +
    +
  • +
+

Figure 199 illustrates electric distribution board port use.

+

Figure 199 — Electric distribution board port use

+ + " +3065;IfcElectricTimeControl;"

An electric time control is a device that applies control to the provision or flow of electrical energy over time.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricTimeControl defines the occurrence of any electric time control; common information about electric time control types is handled by IfcElectricTimeControlType. +The IfcElectricTimeControlType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricTimeControlType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricTimeControlType has ports or aggregated elements, such objects are reflected at the IfcElectricTimeControl occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricTimeControlType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricTimeControlType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricTimeControl override the properties defined at IfcElectricTimeControlType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricTimeControl is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricTimeControlType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricTimeControl are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric time control occurrence is defined by IfcElectricTimeControlType, then the port occurrences must reflect those defined at the IfcElectricTimeControlType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricTimeControl PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3069;IfcTransformer;"

A transformer is an inductive stationary device that transfers electrical energy from one circuit to another.

+

IfcTransformer is used to transform electric power; conversion of electric signals for other purposes is handled at other entities: IfcController converts arbitrary signals, IfcAudioVisualAppliance converts signals for audio or video streams, and IfcCommunicationsAppliance converts signals for data or other communications usage.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcTransformer defines the occurrence of any transformer; common information about transformer types is handled by IfcTransformerType. +The IfcTransformerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcTransformerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcTransformerType has ports or aggregated elements, such objects are reflected at the IfcTransformer occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcTransformerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcTransformerType.HasPropertySets. +If both are given, then the properties directly defined at IfcTransformer override the properties defined at IfcTransformerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcTransformer is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcTransformerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTransformer are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the transformer occurrence is defined by IfcTransformerType, then the port occurrences must reflect those defined at the IfcTransformerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcTransformer PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3081;IfcElectricGenerator;"

An electric generator is an engine that is a machine for converting mechanical energy into electrical energy.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricGenerator defines the occurrence of any electric generator; common information about electric generator types is handled by IfcElectricGeneratorType. +The IfcElectricGeneratorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricGeneratorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricGeneratorType has ports or aggregated elements, such objects are reflected at the IfcElectricGenerator occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricGeneratorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricGeneratorType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricGenerator override the properties defined at IfcElectricGeneratorType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricGenerator is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricGeneratorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcElectricGenerator may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcElectricGenerator and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • ENGINEGENERATOR +
      +
    • May contain IfcEngine components. Engine-Generator sets may optionally include an engine to indicate specific detail.
    • +
    +
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricGenerator are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric generator occurrence is defined by IfcElectricGeneratorType, then the port occurrences must reflect those defined at the IfcElectricGeneratorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricGenerator PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3091;IfcElectricMotor;"

An electric motor is an engine that is a machine for converting electrical energy into mechanical energy.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcElectricMotor defines the occurrence of any electric motor; common information about electric motor types is handled by IfcElectricMotorType. +The IfcElectricMotorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcElectricMotorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcElectricMotorType has ports or aggregated elements, such objects are reflected at the IfcElectricMotor occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcElectricMotorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcElectricMotorType.HasPropertySets. +If both are given, then the properties directly defined at IfcElectricMotor override the properties defined at IfcElectricMotorType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcElectricMotor is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcElectricMotorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricMotor are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the electric motor occurrence is defined by IfcElectricMotorType, then the port occurrences must reflect those defined at the IfcElectricMotorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcElectricMotor PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3103;IfcMotorConnection;"

A motor connection provides the means for connecting a motor as the driving device to the driven device.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcMotorConnection defines the occurrence of any motor connection; common information about motor connection types is handled by IfcMotorConnectionType. +The IfcMotorConnectionType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcMotorConnectionType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcMotorConnectionType has ports or aggregated elements, such objects are reflected at the IfcMotorConnection occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcMotorConnectionType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcMotorConnectionType.HasPropertySets. +If both are given, then the properties directly defined at IfcMotorConnection override the properties defined at IfcMotorConnectionType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcMotorConnection is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcMotorConnectionType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcMotorConnection are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the motor connection occurrence is defined by IfcMotorConnectionType, then the port occurrences must reflect those defined at the IfcMotorConnectionType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcMotorConnection PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3113;IfcSolarDevice;"

A solar device converts solar radiation into other energy such as electric current or thermal energy.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcSolarDevice defines the occurrence of any solar device; common information about solar device types is handled by IfcSolarDeviceType. +The IfcSolarDeviceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcSolarDeviceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcSolarDeviceType has ports or aggregated elements, such objects are reflected at the IfcSolarDevice occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcSolarDeviceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcSolarDeviceType.HasPropertySets. +If both are given, then the properties directly defined at IfcSolarDevice override the properties defined at IfcSolarDeviceType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcSolarDevice is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSolarDeviceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Casing: Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSolarDevice are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the solar device occurrence is defined by IfcSolarDeviceType, then the port occurrences must reflect those defined at the IfcSolarDeviceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcSolarDevice PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3122;IfcProtectiveDeviceTrippingUnit;"Entity Definition + +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcProtectiveDeviceTrippingUnit defines the occurrence of any protective device tripping unit; common information about protective device tripping unit types is handled by IfcProtectiveDeviceTrippingUnitType. +The IfcProtectiveDeviceTrippingUnitType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcProtectiveDeviceTrippingUnitType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcProtectiveDeviceTrippingUnitType has ports or aggregated elements, such objects are reflected at the IfcProtectiveDeviceTrippingUnit occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcProtectiveDeviceTrippingUnitType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcProtectiveDeviceTrippingUnitType.HasPropertySets. +If both are given, then the properties directly defined at IfcProtectiveDeviceTrippingUnit override the properties defined at IfcProtectiveDeviceTrippingUnitType. +Refer to the documentation at the supertype IfcDistributionControlElement and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + " +3126;IfcElectricGeneratorType;" + +

The energy conversion device type IfcElectricGeneratorType defines commonly shared information for occurrences of electric generators. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a electric generator specification (i.e. the specific product information, that is common to all occurrences of that product type). Electric Generator types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricGeneratorType are represented by instances of IfcElectricGenerator.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcElectricGeneratorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Composition Use Definition

+

The IfcElectricGeneratorType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcElectricGeneratorType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

    +
  • ENGINEGENERATOR: May contain IfcEngine components. Engine-Generator sets may optionally include an engine to indicate specific detail.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricGeneratorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricGenerator for standard port definitions.

+ +
" +3129;IfcTransformerType;" + +

The energy conversion device type IfcTransformerType defines commonly shared information for occurrences of transformers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a transformer specification (i.e. the specific product information, that is common to all occurrences of that product type). Transformer types may be exchanged without being already assigned to occurrences. + Occurrences of IfcTransformerType are represented by instances of IfcTransformer.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcTransformerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTransformerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcTransformer for standard port definitions.

+ +
" +3132;IfcElectricMotorType;" + +

The energy conversion device type IfcElectricMotorType defines commonly shared information for occurrences of electric motors. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a electric motor specification (i.e. the specific product information, that is common to all occurrences of that product type). Electric Motor types may be exchanged without being already assigned to occurrences. + Occurrences of IfcElectricMotorType are represented by instances of IfcElectricMotor.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcElectricMotorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcElectricMotorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcElectricMotor for standard port definitions.

+ +
" +3135;IfcSolarDeviceType;" + +

The energy conversion device type IfcSolarDeviceType defines commonly shared information for occurrences of solar devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a solar device specification (i.e. the specific product information, that is common to all occurrences of that product type). Solar Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSolarDeviceType are represented by instances of IfcSolarDevice.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcSolarDeviceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSolarDeviceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcSolarDevice for standard port definitions.

+ +
" +3139;IfcAirToAirHeatRecoveryType;" + +

The energy conversion device type IfcAirToAirHeatRecoveryType defines commonly shared information for occurrences of air-to-air heat recovery devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a air-to-air heat recovery device specification (i.e. the specific product information, that is common to all occurrences of that product type). Air-To-Air Heat Recovery Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcAirToAirHeatRecoveryType are represented by instances of IfcAirToAirHeatRecovery.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcAirToAirHeatRecoveryType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Media': The primary media material used for heat transfer.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirToAirHeatRecoveryType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcAirToAirHeatRecovery for standard port definitions.

+ +
" +3154;IfcBoilerType;" + +

The energy conversion device type IfcBoilerType defines commonly shared information for occurrences of boilers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a boiler specification (i.e. the specific product information, that is common to all occurrences of that product type). Boiler types may be exchanged without being already assigned to occurrences. + Occurrences of IfcBoilerType are represented by instances of IfcBoiler.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcBoilerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcBoilerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcBoiler for standard port definitions.

+ +
" +3162;IfcBurnerType;" + +

The energy conversion device type IfcBurnerType defines commonly shared information for occurrences of burners. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a burner specification (i.e. the specific product information, that is common to all occurrences of that product type). Burner types may be exchanged without being already assigned to occurrences. + Occurrences of IfcBurnerType are represented by instances of IfcBurner.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcBurnerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Fuel': Material designed to be burned.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcBurnerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcBurner for standard port definitions.

+ +
" +3168;IfcChillerType;" + +

The energy conversion device type IfcChillerType defines commonly shared information for occurrences of chillers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a chiller specification (i.e. the specific product information, that is common to all occurrences of that product type). Chiller types may be exchanged without being already assigned to occurrences. + Occurrences of IfcChillerType are represented by instances of IfcChiller.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcChillerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Refrigerant': Refrigerant material.
  • +
+ +

Composition Use Definition

+

The IfcChillerType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcChillerType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcDistributionElement components. Chillers may aggregate distribution flow elements forming a refrigeration cycle (compressor, condenser, valve, evaporator), as well as control elements.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcChillerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcChiller for standard port definitions.

+ +
" +3177;IfcCoilType;" + +

The energy conversion device type IfcCoilType defines commonly shared information for occurrences of coils. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a coil specification (i.e. the specific product information, that is common to all occurrences of that product type). Coil types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCoilType are represented by instances of IfcCoil.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCoilType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCoilType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCoil for standard port definitions.

+ +
" +3190;IfcCondenserType;" + +

The energy conversion device type IfcCondenserType defines commonly shared information for occurrences of condensers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a condenser specification (i.e. the specific product information, that is common to all occurrences of that product type). Condenser types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCondenserType are represented by instances of IfcCondenser.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCondenserType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Refrigerant': Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCondenserType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCondenser for standard port definitions.

+ +
" +3203;IfcCooledBeamType;" + +

The energy conversion device type IfcCooledBeamType defines commonly shared information for occurrences of cooled beams. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cooled beam specification (i.e. the specific product information, that is common to all occurrences of that product type). Cooled Beam types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCooledBeamType are represented by instances of IfcCooledBeam.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcCooledBeamType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCooledBeamType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCooledBeam for standard port definitions.

+ +
" +3211;IfcCoolingTowerType;" + +

The energy conversion device type IfcCoolingTowerType defines commonly shared information for occurrences of cooling towers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a cooling tower specification (i.e. the specific product information, that is common to all occurrences of that product type). Cooling Tower types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCoolingTowerType are represented by instances of IfcCoolingTower.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCoolingTowerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Fill': Fill material.
  • +
+ +

Composition Use Definition

+

The IfcCoolingTowerType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCoolingTowerType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

+ +

Port Use Definition

+

The distribution ports relating to the IfcCoolingTowerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCoolingTower for standard port definitions.

+ +
" +3220;IfcEvaporativeCoolerType;" + +

The energy conversion device type IfcEvaporativeCoolerType defines commonly shared information for occurrences of evaporative coolers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a evaporative cooler specification (i.e. the specific product information, that is common to all occurrences of that product type). Evaporative Cooler types may be exchanged without being already assigned to occurrences. + Occurrences of IfcEvaporativeCoolerType are represented by instances of IfcEvaporativeCooler.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcEvaporativeCoolerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Media': Heat exchanger media material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEvaporativeCoolerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcEvaporativeCooler for standard port definitions.

+ +
" +3235;IfcEvaporatorType;" + +

The energy conversion device type IfcEvaporatorType defines commonly shared information for occurrences of evaporators. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a evaporator specification (i.e. the specific product information, that is common to all occurrences of that product type). Evaporator types may be exchanged without being already assigned to occurrences. + Occurrences of IfcEvaporatorType are represented by instances of IfcEvaporator.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcEvaporatorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Refrigerant': Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEvaporatorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcEvaporator for standard port definitions.

+ +
" +3247;IfcHeatExchangerType;" + +

The energy conversion device type IfcHeatExchangerType defines commonly shared information for occurrences of heat exchangers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a heat exchanger specification (i.e. the specific product information, that is common to all occurrences of that product type). Heat Exchanger types may be exchanged without being already assigned to occurrences. + Occurrences of IfcHeatExchangerType are represented by instances of IfcHeatExchanger.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcHeatExchangerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Shell': Material used to construct the shell of the heat exchanger.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcHeatExchangerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcHeatExchanger for standard port definitions.

+ +
" +3255;IfcHumidifierType;" + +

The energy conversion device type IfcHumidifierType defines commonly shared information for occurrences of humidifiers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a humidifier specification (i.e. the specific product information, that is common to all occurrences of that product type). Humidifier types may be exchanged without being already assigned to occurrences. + Occurrences of IfcHumidifierType are represented by instances of IfcHumidifier.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcHumidifierType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcHumidifierType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcHumidifier for standard port definitions.

+ +
" +3274;IfcTubeBundleType;" + +

The energy conversion device type IfcTubeBundleType defines commonly shared information for occurrences of tube bundles. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a tube bundle specification (i.e. the specific product information, that is common to all occurrences of that product type). Tube Bundle types may be exchanged without being already assigned to occurrences. + Occurrences of IfcTubeBundleType are represented by instances of IfcTubeBundle.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcTubeBundleType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': Material used for construction of the tubes.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTubeBundleType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcTubeBundle for standard port definitions.

+ +
" +3281;IfcUnitaryEquipmentType;" + +

The energy conversion device type IfcUnitaryEquipmentType defines commonly shared information for occurrences of unitary equipments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a unitary equipment specification (i.e. the specific product information, that is common to all occurrences of that product type). Unitary Equipment types may be exchanged without being already assigned to occurrences. + Occurrences of IfcUnitaryEquipmentType are represented by instances of IfcUnitaryEquipment.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcUnitaryEquipmentType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute.

+

Composition Use Definition

+

The IfcUnitaryEquipmentType may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcUnitaryEquipmentType and RelatedObjects contains one or more components. Components are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Aggregation use is defined for the following predefined types: +

    +
  • (All Types): May contain IfcDistributionElement components. Unitary equipment (air handlers in particular) may elaborate contained elements such as dampers, fans, coils, sensors, actuators, and controllers. Such breakdown provides access to component information and tracking of performance history for embedded elements.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcUnitaryEquipmentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcUnitaryEquipment for standard port definitions.

+ +
" +3292;IfcEngineType;" + +

The energy conversion device type IfcEngineType defines commonly shared information for occurrences of engines. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a engine specification (i.e. the specific product information, that is common to all occurrences of that product type). Engine types may be exchanged without being already assigned to occurrences. + Occurrences of IfcEngineType are represented by instances of IfcEngine.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcEngineType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEngineType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcEngine for standard port definitions.

+ +
" +3300;IfcFanType;" + +

The flow moving device type IfcFanType defines commonly shared information for occurrences of fans. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a fan specification (i.e. the specific product information, that is common to all occurrences of that product type). Fan types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFanType are represented by instances of IfcFan.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowMovingDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcFanType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Housing': The material used to construct the fan housing.
  • +
  • 'Wheel': The material used to construct the fan wheel.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFanType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcFan for standard port definitions.

+ +
" +3313;IfcCompressorType;" + +

The flow moving device type IfcCompressorType defines commonly shared information for occurrences of compressors. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a compressor specification (i.e. the specific product information, that is common to all occurrences of that product type). Compressor types may be exchanged without being already assigned to occurrences. + Occurrences of IfcCompressorType are represented by instances of IfcCompressor.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowMovingDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcCompressorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
  • 'Refrigerant': Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCompressorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcCompressor for standard port definitions.

+ +
" +3334;IfcPumpType;" + +

The flow moving device type IfcPumpType defines commonly shared information for occurrences of pumps. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a pump specification (i.e. the specific product information, that is common to all occurrences of that product type). Pump types may be exchanged without being already assigned to occurrences. + Occurrences of IfcPumpType are represented by instances of IfcPump.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowMovingDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcPumpType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
  • 'Impeller': Material from which the impeller of the pump is constructed. In the case of a positive displacement pump, the piston acts as the impeller.
  • +
  • 'ImpellerSeal': Material from which the impeller shaft seal of the pump is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPumpType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcPump for standard port definitions.

+ +
" +3347;IfcDamperType;" + +

The flow controller type IfcDamperType defines commonly shared information for occurrences of dampers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a damper specification (i.e. the specific product information, that is common to all occurrences of that product type). Damper types may be exchanged without being already assigned to occurrences. + Occurrences of IfcDamperType are represented by instances of IfcDamper.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcDamperType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Blade': The material from which the damper blades are constructed.
  • +
  • 'Frame': The material from which the damper frame is constructed.
  • +
  • 'Seal': The material from which the damper seals are constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDamperType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcDamper for standard port definitions.

+ +
" +3364;IfcAirTerminalBoxType;" + +

The flow controller type IfcAirTerminalBoxType defines commonly shared information for occurrences of air boxes. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a air box specification (i.e. the specific product information, that is common to all occurrences of that product type). Air Box types may be exchanged without being already assigned to occurrences. + Occurrences of IfcAirTerminalBoxType are represented by instances of IfcAirTerminalBox.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcAirTerminalBoxType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirTerminalBoxType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcAirTerminalBox for standard port definitions.

+ +
" +3373;IfcValveType;" + +

The flow controller type IfcValveType defines commonly shared information for occurrences of valves. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a valve specification (i.e. the specific product information, that is common to all occurrences of that product type). Valve types may be exchanged without being already assigned to occurrences. + Occurrences of IfcValveType are represented by instances of IfcValve.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcValveType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
  • 'Operation': Material from which the operating mechanism (gate, globe, plug, needle, clack etc.) of the valve is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcValveType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcValve for standard port definitions.

+ +
" +3400;IfcFlowMeterType;" + +

The flow controller type IfcFlowMeterType defines commonly shared information for occurrences of flow meters. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a flow meter specification (i.e. the specific product information, that is common to all occurrences of that product type). Flow Meter types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFlowMeterType are represented by instances of IfcFlowMeter.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowControllerType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFlowMeterType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Casing': Material from which the casing is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFlowMeterType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcFlowMeter for standard port definitions.

+ +
" +3410;IfcDuctFittingType;" + +

The flow fitting type IfcDuctFittingType defines commonly shared information for occurrences of duct fittings. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a duct fitting specification (i.e. the specific product information, that is common to all occurrences of that product type). Duct Fitting types may be exchanged without being already assigned to occurrences. + Occurrences of IfcDuctFittingType are represented by instances of IfcDuctFitting.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowFittingType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcDuctFittingType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Body': Material from which the duct fitting is constructed.
  • +
  • 'Coating': The outer coating, if applicable.
  • +
  • 'Insulation': The insulating wrapping, if applicable.
  • +
  • 'Lining': The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctFittingType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcDuctFitting for standard port definitions.

+ +
" +3423;IfcPipeFittingType;" + +

The flow fitting type IfcPipeFittingType defines commonly shared information for occurrences of pipe fittings. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a pipe fitting specification (i.e. the specific product information, that is common to all occurrences of that product type). Pipe Fitting types may be exchanged without being already assigned to occurrences. + Occurrences of IfcPipeFittingType are represented by instances of IfcPipeFitting.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowFittingType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcPipeFittingType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Body': Material from which the pipe fitting is constructed.
  • +
  • 'Coating': The outer coating, if applicable.
  • +
  • 'Insulation': The insulating wrapping, if applicable.
  • +
  • 'Lining': The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPipeFittingType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcPipeFitting for standard port definitions.

+ +
" +3436;IfcTankType;" + +

The flow storage device type IfcTankType defines commonly shared information for occurrences of tanks. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a tank specification (i.e. the specific product information, that is common to all occurrences of that product type). Tank types may be exchanged without being already assigned to occurrences. + Occurrences of IfcTankType are represented by instances of IfcTank.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowStorageDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcTankType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTankType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcTank for standard port definitions.

+ +
" +3449;IfcDuctSilencerType;" + +

The flow treatment device type IfcDuctSilencerType defines commonly shared information for occurrences of duct silencers. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a duct silencer specification (i.e. the specific product information, that is common to all occurrences of that product type). Duct Silencer types may be exchanged without being already assigned to occurrences. + Occurrences of IfcDuctSilencerType are represented by instances of IfcDuctSilencer.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTreatmentDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcDuctSilencerType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctSilencerType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcDuctSilencer for standard port definitions.

+ +
" +3458;IfcFilterType;" + +

The flow treatment device type IfcFilterType defines commonly shared information for occurrences of filters. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a filter specification (i.e. the specific product information, that is common to all occurrences of that product type). Filter types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFilterType are represented by instances of IfcFilter.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTreatmentDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFilterType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Media': The material that is used for filtering particulates from the fluid.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFilterType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcFilter for standard port definitions.

+ +
" +3470;IfcPipeSegmentType;" + +

The flow segment type IfcPipeSegmentType defines commonly shared information for occurrences of pipe segments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a pipe segment specification (i.e. the specific product information, that is common to all occurrences of that product type). Pipe Segment types may be exchanged without being already assigned to occurrences. + Occurrences of IfcPipeSegmentType are represented by instances of IfcPipeSegment.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowSegmentType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcPipeSegmentType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Body': Material from which the pipe segment is constructed.
  • +
  • 'Coating': The outer coating, if applicable.
  • +
  • 'Insulation': The insulating wrapping, if applicable.
  • +
  • 'Lining': The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPipeSegmentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcPipeSegment for standard port definitions.

+ +
" +3481;IfcDuctSegmentType;" + +

The flow segment type IfcDuctSegmentType defines commonly shared information for occurrences of duct segments. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a duct segment specification (i.e. the specific product information, that is common to all occurrences of that product type). Duct Segment types may be exchanged without being already assigned to occurrences. + Occurrences of IfcDuctSegmentType are represented by instances of IfcDuctSegment.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowSegmentType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcDuctSegmentType is defined by IfcMaterialProfileSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used:

+
    +
  • 'Body': Material from which the duct segment is constructed.
  • +
  • 'Coating': The outer coating, if applicable.
  • +
  • 'Insulation': The insulating wrapping, if applicable.
  • +
  • 'Lining': The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctSegmentType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcDuctSegment for standard port definitions.

+ +
" +3489;IfcPipeFitting;"

A pipe fitting is a junction or transition in a piping flow distribution system or used to connect pipe segments, resulting changes in flow characteristics to the fluid such as direction or flow rate.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcPipeFitting defines the occurrence of any pipe fitting; common information about pipe fitting types is handled by IfcPipeFittingType. +The IfcPipeFittingType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcPipeFittingType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcPipeFittingType has ports or aggregated elements, such objects are reflected at the IfcPipeFitting occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcPipeFittingType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcPipeFittingType.HasPropertySets. +If both are given, then the properties directly defined at IfcPipeFitting override the properties defined at IfcPipeFittingType. +Refer to the documentation at the supertype IfcFlowFitting and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcPipeFitting is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcPipeFittingType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: Material from which the pipe fitting is constructed.
  • +
  • Coating: The outer coating, if applicable.
  • +
  • Insulation: The insulating wrapping, if applicable.
  • +
  • Lining: The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPipeFitting are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the pipe fitting occurrence is defined by IfcPipeFittingType, then the port occurrences must reflect those defined at the IfcPipeFittingType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcPipeFitting PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 227 illustrates pipe fitting port use.

+

Figure 227 — Pipe fitting port use

+ + " +3493;IfcDuctFitting;"

A duct fitting is a junction or transition in a ducted flow distribution system or used to connect duct segments, resulting changes in flow characteristics to the fluid such as direction and flow rate.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcDuctFitting defines the occurrence of any duct fitting; common information about duct fitting types is handled by IfcDuctFittingType. +The IfcDuctFittingType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcDuctFittingType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcDuctFittingType has ports or aggregated elements, such objects are reflected at the IfcDuctFitting occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcDuctFittingType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcDuctFittingType.HasPropertySets. +If both are given, then the properties directly defined at IfcDuctFitting override the properties defined at IfcDuctFittingType. +Refer to the documentation at the supertype IfcFlowFitting and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcDuctFitting is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDuctFittingType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: Material from which the duct fitting is constructed.
  • +
  • Coating: The outer coating, if applicable.
  • +
  • Insulation: The insulating wrapping, if applicable.
  • +
  • Lining: The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctFitting are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the duct fitting occurrence is defined by IfcDuctFittingType, then the port occurrences must reflect those defined at the IfcDuctFittingType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcDuctFitting PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 221 illustrates duct fitting port use.

+

Figure 221 — Duct fitting port use

+ + " +3497;IfcPipeSegment;"

A pipe segment is used to typically join two sections of a piping network.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcPipeSegment defines the occurrence of any pipe segment; common information about pipe segment types is handled by IfcPipeSegmentType. +The IfcPipeSegmentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcPipeSegmentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcPipeSegmentType has ports or aggregated elements, such objects are reflected at the IfcPipeSegment occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcPipeSegmentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcPipeSegmentType.HasPropertySets. +If both are given, then the properties directly defined at IfcPipeSegment override the properties defined at IfcPipeSegmentType. +Refer to the documentation at the supertype IfcFlowSegment and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcPipeSegment is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcPipeSegmentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: Material from which the duct fitting is constructed.
  • +
  • Coating: The outer coating, if applicable.
  • +
  • Insulation: The insulating wrapping, if applicable.
  • +
  • Lining: The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPipeSegment are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the pipe segment occurrence is defined by IfcPipeSegmentType, then the port occurrences must reflect those defined at the IfcPipeSegmentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcPipeSegment PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 228 illustrates pipe segment port use.

+

Figure 228 — Pipe segment port use

+ + " +3501;IfcDuctSegment;"

A duct segment is used to typically join two sections of duct network.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcDuctSegment defines the occurrence of any duct segment; common information about duct segment types is handled by IfcDuctSegmentType. +The IfcDuctSegmentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcDuctSegmentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcDuctSegmentType has ports or aggregated elements, such objects are reflected at the IfcDuctSegment occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcDuctSegmentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcDuctSegmentType.HasPropertySets. +If both are given, then the properties directly defined at IfcDuctSegment override the properties defined at IfcDuctSegmentType. +Refer to the documentation at the supertype IfcFlowSegment and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcDuctSegment is defined by IfcMaterialProfileSetUsage or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDuctSegmentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialProfileSet.MaterialProfiles[n].Name shall be used: +

    +
  • Body: Material from which the duct fitting is constructed.
  • +
  • Coating: The outer coating, if applicable.
  • +
  • Insulation: The insulating wrapping, if applicable.
  • +
  • Lining: The inner lining, if applicable.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctSegment are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the duct segment occurrence is defined by IfcDuctSegmentType, then the port occurrences must reflect those defined at the IfcDuctSegmentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcDuctSegment PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 222 illustrates duct segment port use.

+

Figure 222 — Duct segment port use

+ + " +3505;IfcFilter;"

A filter is an apparatus used to remove particulate or gaseous matter from fluids and gases.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcFilter defines the occurrence of any filter; common information about filter types is handled by IfcFilterType. +The IfcFilterType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcFilterType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcFilterType has ports or aggregated elements, such objects are reflected at the IfcFilter occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcFilterType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcFilterType.HasPropertySets. +If both are given, then the properties directly defined at IfcFilter override the properties defined at IfcFilterType. +Refer to the documentation at the supertype IfcFlowTreatmentDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcFilter is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFilterType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Frame: The material used to construct the filter housing.
  • +
  • Media: The material that is used for filtering particulates.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFilter are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the filter occurrence is defined by IfcFilterType, then the port occurrences must reflect those defined at the IfcFilterType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcFilter PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 225 illustrates filter port use.

+

Figure 225 — Filter port use

+ + " +3509;IfcDuctSilencer;"

A duct silencer is a device that is typically installed inside a duct distribution system for the purpose of reducing the noise levels from air movement, fan noise, etc. in the adjacent space or downstream of the duct silencer device.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcDuctSilencer defines the occurrence of any duct silencer; common information about duct silencer types is handled by IfcDuctSilencerType. +The IfcDuctSilencerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcDuctSilencerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcDuctSilencerType has ports or aggregated elements, such objects are reflected at the IfcDuctSilencer occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcDuctSilencerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcDuctSilencerType.HasPropertySets. +If both are given, then the properties directly defined at IfcDuctSilencer override the properties defined at IfcDuctSilencerType. +Refer to the documentation at the supertype IfcFlowTreatmentDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcDuctSilencer is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDuctSilencerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcDuctSilencer are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the duct silencer occurrence is defined by IfcDuctSilencerType, then the port occurrences must reflect those defined at the IfcDuctSilencerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcDuctSilencer PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3513;IfcCompressor;"

A compressor is a device that compresses a fluid typically used in a refrigeration circuit.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCompressor defines the occurrence of any compressor; common information about compressor types is handled by IfcCompressorType. +The IfcCompressorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCompressorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCompressorType has ports or aggregated elements, such objects are reflected at the IfcCompressor occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCompressorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCompressorType.HasPropertySets. +If both are given, then the properties directly defined at IfcCompressor override the properties defined at IfcCompressorType. +Refer to the documentation at the supertype IfcFlowMovingDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCompressor is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCompressorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Refrigerant: Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCompressor are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the compressor occurrence is defined by IfcCompressorType, then the port occurrences must reflect those defined at the IfcCompressorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCompressor PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • RefrigerantIn (REFRIGERATION, SINK): Uncompressed vapor refrigerant entering the compressor.
  • +
  • RefrigerantOut (REFRIGERATION, SOURCE): Compressed vapor refrigerant leaving the compressor.
  • +
+

Figure 217 illustrates compressor port use.

+

Figure 217 — Compressor port use

+ + " +3517;IfcFan;"

A fan is a device which imparts mechanical work on a gas. A typical usage of a fan is to induce airflow in a building services air distribution system.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcFan defines the occurrence of any fan; common information about fan types is handled by IfcFanType. +The IfcFanType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcFanType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcFanType has ports or aggregated elements, such objects are reflected at the IfcFan occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcFanType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcFanType.HasPropertySets. +If both are given, then the properties directly defined at IfcFan override the properties defined at IfcFanType. +Refer to the documentation at the supertype IfcFlowMovingDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcFan is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFanType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Frame: The material used to construct the fan housing.
  • +
  • Wheel: The material used to construct the fan wheel.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFan are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the fan occurrence is defined by IfcFanType, then the port occurrences must reflect those defined at the IfcFanType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcFan PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 224 illustrates fan port use.

+

Figure 224 — Fan port use

+ + " +3521;IfcPump;"

A pump is a device which imparts mechanical work on fluids or slurries to move them through a channel or pipeline. A typical use of a pump is to circulate chilled water or heating hot water in a building services distribution system.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcPump defines the occurrence of any pump; common information about pump types is handled by IfcPumpType. +The IfcPumpType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcPumpType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcPumpType has ports or aggregated elements, such objects are reflected at the IfcPump occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcPumpType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcPumpType.HasPropertySets. +If both are given, then the properties directly defined at IfcPump override the properties defined at IfcPumpType. +Refer to the documentation at the supertype IfcFlowMovingDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcPump is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcPumpType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Impeller: Material from which the impeller of the pump is constructed. In the case of a positive displacement pump, the piston acts as the impeller.
  • +
  • Seal: Material from which the impeller shaft seal of the pump is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcPump are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the pump occurrence is defined by IfcPumpType, then the port occurrences must reflect those defined at the IfcPumpType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcPump PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 229 illustrates pump port use.

+

Figure 229 — Pump port use

+ + " +3525;IfcAirTerminal;"

An air terminal is a terminating or origination point for the transfer of air between distribution system(s) and one or more spaces. It can also be used for the transfer of air between adjacent spaces.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcAirTerminal defines the occurrence of any air terminal; common information about air terminal types is handled by IfcAirTerminalType. +The IfcAirTerminalType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcAirTerminalType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcAirTerminalType has ports or aggregated elements, such objects are reflected at the IfcAirTerminal occurrence using the IfcRelDefinesByObject relationship.

+

Figure 210 illustrates air terminal type use.

+

Figure 210 — Air terminal type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcAirTerminalType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcAirTerminalType.HasPropertySets. +If both are given, then the properties directly defined at IfcAirTerminal override the properties defined at IfcAirTerminalType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcAirTerminal is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcAirTerminalType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirTerminal are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the air terminal occurrence is defined by IfcAirTerminalType, then the port occurrences must reflect those defined at the IfcAirTerminalType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcAirTerminal PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 211 illustrates air terminal port use.

+

Figure 211 — Air terminal port use

+ + " +3536;IfcSpaceHeater;"

Space heaters utilize a combination of radiation and/or natural convection using a heating source such as electricity, steam or hot water to heat a limited space or area. Examples of space heaters include radiators, convectors, baseboard and finned-tube heaters.

+

IfcUnitaryEquipment should be used for packaged units supporting a combination of heating, cooling, and/or dehumidification; IfcCoil should be used for coil-based floor heating.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcSpaceHeater defines the occurrence of any space heater; common information about space heater types is handled by IfcSpaceHeaterType. +The IfcSpaceHeaterType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcSpaceHeaterType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcSpaceHeaterType has ports or aggregated elements, such objects are reflected at the IfcSpaceHeater occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcSpaceHeaterType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcSpaceHeaterType.HasPropertySets. +If both are given, then the properties directly defined at IfcSpaceHeater override the properties defined at IfcSpaceHeaterType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcSpaceHeater is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSpaceHeaterType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSpaceHeater are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the space heater occurrence is defined by IfcSpaceHeaterType, then the port occurrences must reflect those defined at the IfcSpaceHeaterType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcSpaceHeater PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 230 illustrates space heater port use.

+

Figure 230 — Space heater port use

+ + " +3545;IfcMedicalDevice;"

A medical device is attached to a medical piping system and operates upon medical gases to perform a specific function. Medical gases include medical air, medical vacuum, oxygen, carbon dioxide, nitrogen, and nitrous oxide.

+

Outlets for medical gasses should use IfcValve with PredefinedType equal to GASTAP, containing an IfcDistributionPort with FlowDirection=SINK and PredefinedType equal to COMPRESSEDAIR, VACUUM, or CHEMICAL, and having property sets on the port further indicating the gas type and pressure. Tanks for medical gasses should use IfcTank with PredefinedType equal to PRESSUREVESSEL, containing an IfcDistributionPort with FlowDirection=SOURCE and PredefinedType=CHEMICAL, and having property sets on the port further indicating the gas type and pressure range.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcMedicalDevice defines the occurrence of any medical device; common information about medical device types is handled by IfcMedicalDeviceType. +The IfcMedicalDeviceType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcMedicalDeviceType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcMedicalDeviceType has ports or aggregated elements, such objects are reflected at the IfcMedicalDevice occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcMedicalDeviceType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcMedicalDeviceType.HasPropertySets. +If both are given, then the properties directly defined at IfcMedicalDevice override the properties defined at IfcMedicalDeviceType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcMedicalDevice is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcMedicalDeviceType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcMedicalDevice are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the medical device occurrence is defined by IfcMedicalDeviceType, then the port occurrences must reflect those defined at the IfcMedicalDeviceType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcMedicalDevice PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3557;IfcAirTerminalBox;"

An air terminal box typically participates in an HVAC duct distribution system and is used to control or modulate the amount of air delivered to its downstream ductwork. An air terminal box type is often referred to as an ""air flow regulator"".

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcAirTerminalBox defines the occurrence of any air terminal box; common information about air terminal box types is handled by IfcAirTerminalBoxType. +The IfcAirTerminalBoxType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcAirTerminalBoxType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcAirTerminalBoxType has ports or aggregated elements, such objects are reflected at the IfcAirTerminalBox occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcAirTerminalBoxType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcAirTerminalBoxType.HasPropertySets. +If both are given, then the properties directly defined at IfcAirTerminalBox override the properties defined at IfcAirTerminalBoxType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcAirTerminalBox is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcAirTerminalBoxType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirTerminalBox are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the air terminal box occurrence is defined by IfcAirTerminalBoxType, then the port occurrences must reflect those defined at the IfcAirTerminalBoxType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcAirTerminalBox PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3561;IfcDamper;"

A damper typically participates in an HVAC duct distribution system and is used to control or modulate the flow of air.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcDamper defines the occurrence of any damper; common information about damper types is handled by IfcDamperType. +The IfcDamperType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcDamperType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcDamperType has ports or aggregated elements, such objects are reflected at the IfcDamper occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcDamperType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcDamperType.HasPropertySets. +If both are given, then the properties directly defined at IfcDamper override the properties defined at IfcDamperType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcDamper is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcDamperType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Blade: The material from which the damper blades are constructed.
  • +
  • Frame: The material from which the damper frame is constructed.
  • +
  • Seal: The material from which the damper seals are constructed.
  • +
+ +

Connection Use Definition

+

The IfcDamper may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcDamper are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the damper occurrence is defined by IfcDamperType, then the port occurrences must reflect those defined at the IfcDamperType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcDamper PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 220 illustrates damper port use.

+

Figure 220 — Damper port use

+ + " +3565;IfcFlowMeter;"

A flow meter is a device that is used to measure the flow rate in a system.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcFlowMeter defines the occurrence of any flow meter; common information about flow meter types is handled by IfcFlowMeterType. +The IfcFlowMeterType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcFlowMeterType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcFlowMeterType has ports or aggregated elements, such objects are reflected at the IfcFlowMeter occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcFlowMeterType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcFlowMeterType.HasPropertySets. +If both are given, then the properties directly defined at IfcFlowMeter override the properties defined at IfcFlowMeterType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcFlowMeter is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFlowMeterType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFlowMeter are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the flow meter occurrence is defined by IfcFlowMeterType, then the port occurrences must reflect those defined at the IfcFlowMeterType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcFlowMeter PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 226 illustrates flow meter port use.

+

Figure 226 — Flow meter port use

+ + " +3569;IfcValve;"

A valve is used in a building services piping distribution system to control or modulate the flow of the fluid.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcValve defines the occurrence of any valve; common information about valve types is handled by IfcValveType. +The IfcValveType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcValveType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcValveType has ports or aggregated elements, such objects are reflected at the IfcValve occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcValveType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcValveType.HasPropertySets. +If both are given, then the properties directly defined at IfcValve override the properties defined at IfcValveType. +Refer to the documentation at the supertype IfcFlowController and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcValve is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcValveType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Operation: Material from which the operating mechanism (such as gate, globe, plug, needle, or clack) of the valve is constructed.
  • +
+ +

Connection Use Definition

+

The IfcValve may be connected to other objects as follows using the indicated relationship:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcValve are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the valve occurrence is defined by IfcValveType, then the port occurrences must reflect those defined at the IfcValveType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcValve PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 233 illustrates valve port use.

+

Figure 233 — Valve port use

+ + " +3573;IfcTank;"

A tank is a vessel or container in which a fluid or gas is stored for later use.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcTank defines the occurrence of any tank; common information about tank types is handled by IfcTankType. +The IfcTankType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcTankType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcTankType has ports or aggregated elements, such objects are reflected at the IfcTank occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcTankType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcTankType.HasPropertySets. +If both are given, then the properties directly defined at IfcTank override the properties defined at IfcTankType. +Refer to the documentation at the supertype IfcFlowStorageDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcTank is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcTankType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTank are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the tank occurrence is defined by IfcTankType, then the port occurrences must reflect those defined at the IfcTankType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcTank PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3577;IfcAirToAirHeatRecovery;"

An air-to-air heat recovery device employs a counter-flow heat exchanger between inbound and outbound air flow. It is typically used to transfer heat from warmer air in one chamber to cooler air in the second chamber (i.e., typically used to recover heat from the conditioned air being exhausted and the outside air being supplied to a building), resulting in energy savings from reduced heating (or cooling) requirements.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcAirToAirHeatRecovery defines the occurrence of any air to air heat recovery; common information about air to air heat recovery types is handled by IfcAirToAirHeatRecoveryType. +The IfcAirToAirHeatRecoveryType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcAirToAirHeatRecoveryType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcAirToAirHeatRecoveryType has ports or aggregated elements, such objects are reflected at the IfcAirToAirHeatRecovery occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcAirToAirHeatRecoveryType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcAirToAirHeatRecoveryType.HasPropertySets. +If both are given, then the properties directly defined at IfcAirToAirHeatRecovery override the properties defined at IfcAirToAirHeatRecoveryType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcAirToAirHeatRecovery is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcAirToAirHeatRecoveryType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Media: The primary media material used for heat transfer.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirToAirHeatRecovery are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the air to air heat recovery occurrence is defined by IfcAirToAirHeatRecoveryType, then the port occurrences must reflect those defined at the IfcAirToAirHeatRecoveryType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcAirToAirHeatRecovery PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3581;IfcBoiler;"

A boiler is a closed, pressure-rated vessel in which water or other fluid is heated using an energy source such as natural gas, heating oil, or electricity. The fluid in the vessel is then circulated out of the boiler for use in various processes or heating applications.

+

IfcBoiler is a vessel solely used for heating of water or other fluids. Storage vessels, such as for drinking water storage are considered as tanks and use the IfcTank entity.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcBoiler defines the occurrence of any boiler; common information about boiler types is handled by IfcBoilerType. +The IfcBoilerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcBoilerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcBoilerType has ports or aggregated elements, such objects are reflected at the IfcBoiler occurrence using the IfcRelDefinesByObject relationship.

+

Figure 212 illustrates boiler type use.

+

Figure 212 — Boiler type use

+ + +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcBoilerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcBoilerType.HasPropertySets. +If both are given, then the properties directly defined at IfcBoiler override the properties defined at IfcBoilerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcBoiler is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcBoilerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcBoiler are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the boiler occurrence is defined by IfcBoilerType, then the port occurrences must reflect those defined at the IfcBoilerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcBoiler PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 213 illustrates boiler port use.

+

Figure 213 — Boiler port use

+ + " +3585;IfcBurner;"

A burner is a device that converts fuel into heat through combustion. It includes gas, oil, and wood burners.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcBurner defines the occurrence of any burner; common information about burner types is handled by IfcBurnerType. +The IfcBurnerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcBurnerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcBurnerType has ports or aggregated elements, such objects are reflected at the IfcBurner occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcBurnerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcBurnerType.HasPropertySets. +If both are given, then the properties directly defined at IfcBurner override the properties defined at IfcBurnerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcBurner is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcBurnerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Fuel: Material designed to be burned.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcBurner are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the burner occurrence is defined by IfcBurnerType, then the port occurrences must reflect those defined at the IfcBurnerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcBurner PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+
    +
  • Gas (GAS, SINK): Gas inlet for burner.
  • +
+ " +3589;IfcChiller;"

A chiller is a device used to remove heat from a liquid via a vapor-compression or absorption refrigeration cycle to cool a fluid, typically water or a mixture of water and glycol. The chilled fluid is then used to cool and dehumidify air in a building.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcChiller defines the occurrence of any chiller; common information about chiller types is handled by IfcChillerType. +The IfcChillerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcChillerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcChillerType has ports or aggregated elements, such objects are reflected at the IfcChiller occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcChillerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcChillerType.HasPropertySets. +If both are given, then the properties directly defined at IfcChiller override the properties defined at IfcChillerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcChiller is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcChillerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Refrigerant: Refrigerant material.
  • +
+ +

Composition Use Definition

+

The IfcChiller may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcChiller and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • May contain IfcDistributionElement components. Chillers may aggregate distribution flow elements forming a refrigeration cycle (compressor, condenser, valve, evaporator), as well as control elements.
  • +
+

Figure 214 illustrates chiller composition use.

+

Figure 214 — Chiller composition use

+ + +

Port Use Definition

+

The distribution ports relating to the IfcChiller are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the chiller occurrence is defined by IfcChillerType, then the port occurrences must reflect those defined at the IfcChillerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcChiller PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 215 illustrates chiller port use.

+

Figure 215 — Chiller port use

+ + " +3593;IfcCoil;"

A coil is a device used to provide heat transfer between non-mixing media. A common example is a cooling coil, which utilizes a finned coil in which circulates chilled water, antifreeze, or refrigerant that is used to remove heat from air moving across the surface of the coil. A coil may be used either for heating or cooling purposes by placing a series of tubes (the coil) carrying a heating or cooling fluid into an airstream. The coil may be constructed from tubes bundled in a serpentine form or from finned tubes that give a extended heat transfer surface.

+

Coils may also be used for non-airflow cases such as embedded in a floor slab.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCoil defines the occurrence of any coil; common information about coil types is handled by IfcCoilType. +The IfcCoilType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCoilType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCoilType has ports or aggregated elements, such objects are reflected at the IfcCoil occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCoilType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCoilType.HasPropertySets. +If both are given, then the properties directly defined at IfcCoil override the properties defined at IfcCoilType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCoil is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCoilType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCoil are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the coil occurrence is defined by IfcCoilType, then the port occurrences must reflect those defined at the IfcCoilType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCoil PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 216 illustrates coil port use.

+

Figure 216 — Coil port use

+ + " +3597;IfcCondenser;"

A condenser is a device that is used to dissipate heat, typically by condensing a substance such as a refrigerant from its gaseous to its liquid state.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCondenser defines the occurrence of any condenser; common information about condenser types is handled by IfcCondenserType. +The IfcCondenserType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCondenserType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCondenserType has ports or aggregated elements, such objects are reflected at the IfcCondenser occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCondenserType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCondenserType.HasPropertySets. +If both are given, then the properties directly defined at IfcCondenser override the properties defined at IfcCondenserType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCondenser is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCondenserType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Refrigerant: Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCondenser are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the condenser occurrence is defined by IfcCondenserType, then the port occurrences must reflect those defined at the IfcCondenserType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCondenser PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 218 illustrates condenser port use.

+

Figure 218 — Condenser port use

+ + " +3601;IfcCooledBeam;"

A cooled beam (or chilled beam) is a device typically used to cool air by circulating a fluid such as chilled water through exposed finned tubes above a space. Typically mounted overhead near or within a ceiling, the cooled beam uses convection to cool the space below it by acting as a heat sink for the naturally rising warm air of the space. Once cooled, the air naturally drops back to the floor where the cycle begins again.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCooledBeam defines the occurrence of any cooled beam; common information about cooled beam types is handled by IfcCooledBeamType. +The IfcCooledBeamType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCooledBeamType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCooledBeamType has ports or aggregated elements, such objects are reflected at the IfcCooledBeam occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCooledBeamType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCooledBeamType.HasPropertySets. +If both are given, then the properties directly defined at IfcCooledBeam override the properties defined at IfcCooledBeamType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCooledBeam is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCooledBeamType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcCooledBeam are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cooled beam occurrence is defined by IfcCooledBeamType, then the port occurrences must reflect those defined at the IfcCooledBeamType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCooledBeam PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3605;IfcCoolingTower;"

A cooling tower is a device which rejects heat to ambient air by circulating a fluid such as water through it to reduce its temperature by partial evaporation.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcCoolingTower defines the occurrence of any cooling tower; common information about cooling tower types is handled by IfcCoolingTowerType. +The IfcCoolingTowerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcCoolingTowerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcCoolingTowerType has ports or aggregated elements, such objects are reflected at the IfcCoolingTower occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcCoolingTowerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcCoolingTowerType.HasPropertySets. +If both are given, then the properties directly defined at IfcCoolingTower override the properties defined at IfcCoolingTowerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcCoolingTower is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcCoolingTowerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Fill: Fill material.
  • +
+ +

Composition Use Definition

+

The IfcCoolingTower may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcCoolingTower and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+ + +

Port Use Definition

+

The distribution ports relating to the IfcCoolingTower are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the cooling tower occurrence is defined by IfcCoolingTowerType, then the port occurrences must reflect those defined at the IfcCoolingTowerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcCoolingTower PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 219 illustrates cooling tower port use.

+

Figure 219 — Cooling tower port use

+ + " +3609;IfcEvaporativeCooler;"

An evaporative cooler is a device that cools air by saturating it with water vapor.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcEvaporativeCooler defines the occurrence of any evaporative cooler; common information about evaporative cooler types is handled by IfcEvaporativeCoolerType. +The IfcEvaporativeCoolerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcEvaporativeCoolerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcEvaporativeCoolerType has ports or aggregated elements, such objects are reflected at the IfcEvaporativeCooler occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcEvaporativeCoolerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcEvaporativeCoolerType.HasPropertySets. +If both are given, then the properties directly defined at IfcEvaporativeCooler override the properties defined at IfcEvaporativeCoolerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcEvaporativeCooler is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcEvaporativeCoolerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Media: Heat exchanger media material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEvaporativeCooler are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the evaporative cooler occurrence is defined by IfcEvaporativeCoolerType, then the port occurrences must reflect those defined at the IfcEvaporativeCoolerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcEvaporativeCooler PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3613;IfcEvaporator;"

An evaporator is a device in which a liquid refrigerent is vaporized and absorbs heat from the surrounding fluid.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcEvaporator defines the occurrence of any evaporator; common information about evaporator types is handled by IfcEvaporatorType. +The IfcEvaporatorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcEvaporatorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcEvaporatorType has ports or aggregated elements, such objects are reflected at the IfcEvaporator occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcEvaporatorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcEvaporatorType.HasPropertySets. +If both are given, then the properties directly defined at IfcEvaporator override the properties defined at IfcEvaporatorType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcEvaporator is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcEvaporatorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Refrigerant: Refrigerant material.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEvaporator are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the evaporator occurrence is defined by IfcEvaporatorType, then the port occurrences must reflect those defined at the IfcEvaporatorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcEvaporator PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 223 illustrates evaporator port use.

+

Figure 223 — Evaporator port use

+ + " +3617;IfcHeatExchanger;"

A heat exchanger is a device used to provide heat transfer between non-mixing media such as plate and shell and tube heat exchangers.

+

IfcHeatExchanger is commonly used on water-side distribution systems to recover energy from a liquid to another liquid (typically water-based), whereas IfcAirToAirHeatRecovery is commonly used on air-side distribution systems to recover energy from a gas to a gas (usually air).

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcHeatExchanger defines the occurrence of any heat exchanger; common information about heat exchanger types is handled by IfcHeatExchangerType. +The IfcHeatExchangerType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcHeatExchangerType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcHeatExchangerType has ports or aggregated elements, such objects are reflected at the IfcHeatExchanger occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcHeatExchangerType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcHeatExchangerType.HasPropertySets. +If both are given, then the properties directly defined at IfcHeatExchanger override the properties defined at IfcHeatExchangerType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcHeatExchanger is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcHeatExchangerType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcHeatExchanger are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the heat exchanger occurrence is defined by IfcHeatExchangerType, then the port occurrences must reflect those defined at the IfcHeatExchangerType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcHeatExchanger PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3621;IfcHumidifier;"

A humidifier is a device that adds moisture into the air.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcHumidifier defines the occurrence of any humidifier; common information about humidifier types is handled by IfcHumidifierType. +The IfcHumidifierType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcHumidifierType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcHumidifierType has ports or aggregated elements, such objects are reflected at the IfcHumidifier occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcHumidifierType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcHumidifierType.HasPropertySets. +If both are given, then the properties directly defined at IfcHumidifier override the properties defined at IfcHumidifierType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcHumidifier is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcHumidifierType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcHumidifier are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the humidifier occurrence is defined by IfcHumidifierType, then the port occurrences must reflect those defined at the IfcHumidifierType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcHumidifier PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3625;IfcTubeBundle;"

A tube bundle is a device consisting of tubes and bundles of tubes used for heat transfer and contained typically within other energy conversion devices, such as a chiller or coil.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcTubeBundle defines the occurrence of any tube bundle; common information about tube bundle types is handled by IfcTubeBundleType. +The IfcTubeBundleType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcTubeBundleType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcTubeBundleType has ports or aggregated elements, such objects are reflected at the IfcTubeBundle occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcTubeBundleType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcTubeBundleType.HasPropertySets. +If both are given, then the properties directly defined at IfcTubeBundle override the properties defined at IfcTubeBundleType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcTubeBundle is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcTubeBundleType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcTubeBundle are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the tube bundle occurrence is defined by IfcTubeBundleType, then the port occurrences must reflect those defined at the IfcTubeBundleType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcTubeBundle PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3629;IfcUnitaryEquipment;"

Unitary equipment typically combine a number of components into a single product, such as air handlers, pre-packaged rooftop air-conditioning units, and split systems.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcUnitaryEquipment defines the occurrence of any unitary equipment; common information about unitary equipment types is handled by IfcUnitaryEquipmentType. +The IfcUnitaryEquipmentType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcUnitaryEquipmentType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcUnitaryEquipmentType has ports or aggregated elements, such objects are reflected at the IfcUnitaryEquipment occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcUnitaryEquipmentType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcUnitaryEquipmentType.HasPropertySets. +If both are given, then the properties directly defined at IfcUnitaryEquipment override the properties defined at IfcUnitaryEquipmentType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcUnitaryEquipment is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcUnitaryEquipmentType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Composition Use Definition

+

The IfcUnitaryEquipment may be aggregated into components using IfcRelAggregates where RelatingObject refers to the enclosing IfcUnitaryEquipment and RelatedObjects contains one or more components. Aggregation use is defined for the following predefined types:

+
    +
  • May contain IfcDistributionElement components. Unitary equipment (air handlers in particular) may elaborate contained elements such as dampers, fans, coils, sensors, actuators, and controllers. Such breakdown provides access to component information and tracking of performance history for embedded elements.
  • +
+

Figure 231 illustrates unitary equipment composition use.

+

Figure 231 — Unitary equipment composition use

+ + +

Port Use Definition

+

The distribution ports relating to the IfcUnitaryEquipment are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the unitary equipment occurrence is defined by IfcUnitaryEquipmentType, then the port occurrences must reflect those defined at the IfcUnitaryEquipmentType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcUnitaryEquipment PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ +

Figure 232 illustrates unitary equipment port use.

+

Figure 232 — Unitary equipment port use

+ + " +3633;IfcEngine;"

An engine is a device that converts fuel into mechanical energy through combustion.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcEngine defines the occurrence of any engine; common information about engine types is handled by IfcEngineType. +The IfcEngineType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcEngineType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcEngineType has ports or aggregated elements, such objects are reflected at the IfcEngine occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcEngineType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcEngineType.HasPropertySets. +If both are given, then the properties directly defined at IfcEngine override the properties defined at IfcEngineType. +Refer to the documentation at the supertype IfcEnergyConversionDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcEngine is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcEngineType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcEngine are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the engine occurrence is defined by IfcEngineType, then the port occurrences must reflect those defined at the IfcEngineType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcEngine PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3637;IfcAirTerminalType;" + +

The flow terminal type IfcAirTerminalType defines commonly shared information for occurrences of air terminals. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a air terminal specification (i.e. the specific product information, that is common to all occurrences of that product type). Air Terminal types may be exchanged without being already assigned to occurrences. + Occurrences of IfcAirTerminalType are represented by instances of IfcAirTerminal.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcAirTerminalType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcAirTerminalType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcAirTerminal for standard port definitions.

+ +
" +3640;IfcSpaceHeaterType;" + +

The energy conversion device type IfcSpaceHeaterType defines commonly shared information for occurrences of space heaters. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a space heater specification (i.e. the specific product information, that is common to all occurrences of that product type). Space Heater types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSpaceHeaterType are represented by instances of IfcSpaceHeater.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcEnergyConversionDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSpaceHeaterType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSpaceHeaterType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcSpaceHeater for standard port definitions.

+ +
" +3643;IfcMedicalDeviceType;" + +

The flow terminal type IfcMedicalDeviceType defines commonly shared information for occurrences of medical devices. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a medical device specification (i.e. the specific product information, that is common to all occurrences of that product type). Medical Device types may be exchanged without being already assigned to occurrences. + Occurrences of IfcMedicalDeviceType are represented by instances of IfcMedicalDevice.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcMedicalDeviceType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcMedicalDeviceType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcMedicalDevice for standard port definitions.

+ +
" +3646;IfcVibrationIsolator;"

A vibration isolator is a device used to minimize the effects of vibration transmissibility in a building.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcVibrationIsolator defines the occurrence of any vibration isolator; common information about vibration isolator types is handled by IfcVibrationIsolatorType. +The IfcVibrationIsolatorType (if present) may establish the common type name, usage (predefined type), properties, materials, composition, assignments, and representations. +The IfcVibrationIsolatorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcVibrationIsolatorType has aggregated elements, such objects are reflected at the IfcVibrationIsolator occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcVibrationIsolatorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcVibrationIsolatorType.HasPropertySets. +If both are given, then the properties directly defined at IfcVibrationIsolator override the properties defined at IfcVibrationIsolatorType. +Refer to the documentation at the supertype IfcElementComponent and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcVibrationIsolator is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcVibrationIsolatorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Damping: Material from which the damping element of the vibration isolator is constructed.
  • +
+ " +3655;IfcVibrationIsolatorType;" + +

The element component type IfcVibrationIsolatorType defines commonly shared information for occurrences of vibration isolators. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • applicable assignment of process types
  • +
+

It is used to define a vibration isolator specification (i.e. the specific product information, that is common to all occurrences of that product type). Vibration Isolator types may be exchanged without being already assigned to occurrences. + Occurrences of IfcVibrationIsolatorType are represented by instances of IfcVibrationIsolator.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcElementComponentType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcVibrationIsolatorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Damping': Material from which the damping element of the vibration isolator is constructed.
  • +
+ +
" +3659;IfcWasteTerminalType;" + +

The flow terminal type IfcWasteTerminalType defines commonly shared information for occurrences of waste terminals. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a waste terminal specification (i.e. the specific product information, that is common to all occurrences of that product type). Waste Terminal types may be exchanged without being already assigned to occurrences. + Occurrences of IfcWasteTerminalType are represented by instances of IfcWasteTerminal.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcWasteTerminalType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
  • 'Cover': Material from which the cover or grating is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcWasteTerminalType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcWasteTerminal for standard port definitions.

+ +
" +3672;IfcStackTerminalType;" + +

The flow terminal type IfcStackTerminalType defines commonly shared information for occurrences of stack terminals. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a stack terminal specification (i.e. the specific product information, that is common to all occurrences of that product type). Stack Terminal types may be exchanged without being already assigned to occurrences. + Occurrences of IfcStackTerminalType are represented by instances of IfcStackTerminal.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Material Use Definition

+

The material of the IfcStackTerminalType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcStackTerminalType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcStackTerminal for standard port definitions.

+ +
" +3681;IfcSanitaryTerminalType;" + +

The flow terminal type IfcSanitaryTerminalType defines commonly shared information for occurrences of sanitary terminals. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a sanitary terminal specification (i.e. the specific product information, that is common to all occurrences of that product type). Sanitary Terminal types may be exchanged without being already assigned to occurrences. + Occurrences of IfcSanitaryTerminalType are represented by instances of IfcSanitaryTerminal.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcSanitaryTerminalType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSanitaryTerminalType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcSanitaryTerminal for standard port definitions.

+ +
" +3697;IfcFireSuppressionTerminalType;" + +

The flow terminal type IfcFireSuppressionTerminalType defines commonly shared information for occurrences of fire suppression terminals. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a fire suppression terminal specification (i.e. the specific product information, that is common to all occurrences of that product type). Fire Suppression Terminal types may be exchanged without being already assigned to occurrences. + Occurrences of IfcFireSuppressionTerminalType are represented by instances of IfcFireSuppressionTerminal.

+ +
HISTORY: New entity in IFC2x2
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTerminalType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcFireSuppressionTerminalType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
  • 'Deflector': The material used to construct the deflector plate.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFireSuppressionTerminalType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcFireSuppressionTerminal for standard port definitions.

+ +
" +3708;IfcFireSuppressionTerminal;"

A fire suppression terminal has the purpose of delivering a fluid (gas or liquid) that will suppress a fire.

+

A fire suppression terminal provides for all forms of sprinkler, spreader and other form of terminal that is connected to a pipework system and intended to act in the role of suppressing a fire.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcFireSuppressionTerminal defines the occurrence of any fire suppression terminal; common information about fire suppression terminal types is handled by IfcFireSuppressionTerminalType. +The IfcFireSuppressionTerminalType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcFireSuppressionTerminalType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcFireSuppressionTerminalType has ports or aggregated elements, such objects are reflected at the IfcFireSuppressionTerminal occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcFireSuppressionTerminalType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcFireSuppressionTerminalType.HasPropertySets. +If both are given, then the properties directly defined at IfcFireSuppressionTerminal override the properties defined at IfcFireSuppressionTerminalType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcFireSuppressionTerminal is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcFireSuppressionTerminalType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Deflector: The material used to construct the deflector plate.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcFireSuppressionTerminal are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the fire suppression terminal occurrence is defined by IfcFireSuppressionTerminalType, then the port occurrences must reflect those defined at the IfcFireSuppressionTerminalType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcFireSuppressionTerminal PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3712;IfcSanitaryTerminal;"

A sanitary terminal is a fixed appliance or terminal usually supplied with water and used for drinking, cleaning or foul water disposal or that is an item of equipment directly used with such an appliance or terminal.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcSanitaryTerminal defines the occurrence of any sanitary terminal; common information about sanitary terminal types is handled by IfcSanitaryTerminalType. +The IfcSanitaryTerminalType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcSanitaryTerminalType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcSanitaryTerminalType has ports or aggregated elements, such objects are reflected at the IfcSanitaryTerminal occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcSanitaryTerminalType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcSanitaryTerminalType.HasPropertySets. +If both are given, then the properties directly defined at IfcSanitaryTerminal override the properties defined at IfcSanitaryTerminalType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcSanitaryTerminal is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcSanitaryTerminalType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcSanitaryTerminal are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the sanitary terminal occurrence is defined by IfcSanitaryTerminalType, then the port occurrences must reflect those defined at the IfcSanitaryTerminalType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcSanitaryTerminal PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3716;IfcStackTerminal;"

A stack terminal is placed at the top of a ventilating stack (such as to prevent ingress by birds or rainwater) or rainwater pipe (to act as a collector or hopper for discharge from guttering).

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcStackTerminal defines the occurrence of any stack terminal; common information about stack terminal types is handled by IfcStackTerminalType. +The IfcStackTerminalType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcStackTerminalType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcStackTerminalType has ports or aggregated elements, such objects are reflected at the IfcStackTerminal occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcStackTerminalType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcStackTerminalType.HasPropertySets. +If both are given, then the properties directly defined at IfcStackTerminal override the properties defined at IfcStackTerminalType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcStackTerminal is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcStackTerminalType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcStackTerminal are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the stack terminal occurrence is defined by IfcStackTerminalType, then the port occurrences must reflect those defined at the IfcStackTerminalType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcStackTerminal PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3720;IfcWasteTerminal;"

A waste terminal has the purpose of collecting or intercepting waste from one or more sanitary terminals or other fluid waste generating equipment and discharging it into a single waste/drainage system.

+

A waste terminal provides for all forms of trap and waste point that collects discharge from a sanitary terminal and discharges it into a waste/drainage subsystem or that collects waste from several terminals and passes it into a single waste/drainage subsystem. This includes the P and S traps from soil sanitary terminals, sinks, and basins as well as floor wastes and gully traps that provide collection points.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcWasteTerminal defines the occurrence of any waste terminal; common information about waste terminal types is handled by IfcWasteTerminalType. +The IfcWasteTerminalType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcWasteTerminalType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcWasteTerminalType has ports or aggregated elements, such objects are reflected at the IfcWasteTerminal occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcWasteTerminalType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcWasteTerminalType.HasPropertySets. +If both are given, then the properties directly defined at IfcWasteTerminal override the properties defined at IfcWasteTerminalType. +Refer to the documentation at the supertype IfcFlowTerminal and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcWasteTerminal is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcWasteTerminalType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Cover: Material from which the cover or grating is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcWasteTerminal are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the waste terminal occurrence is defined by IfcWasteTerminalType, then the port occurrences must reflect those defined at the IfcWasteTerminalType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcWasteTerminal PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3724;IfcInterceptorType;" + +

The flow treatment device type IfcInterceptorType defines commonly shared information for occurrences of interceptors. The set of shared information may include:

+
    +
  • common properties with shared property sets
  • +
  • common representations of shape
  • +
  • common materials
  • +
  • common composition of elements
  • +
  • common ports
  • +
  • applicable assignment of process types
  • +
+

It is used to define a interceptor specification (i.e. the specific product information, that is common to all occurrences of that product type). Interceptor types may be exchanged without being already assigned to occurrences. + Occurrences of IfcInterceptorType are represented by instances of IfcInterceptor.

+ +
HISTORY: New entity in IFC2x4
+ +

Property Set Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the HasPropertySets attribute. Refer to the documentation at the supertype IfcFlowTreatmentDeviceType and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+

The following property set definitions are applicable to this entity according to the PredefinedType attribute:

+ +

Material Use Definition

+

The material of the IfcInterceptorType is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used:

+
    +
  • 'Body': The primary material from which the object is constructed.
  • +
  • 'Cover': Material from which the cover or grating is constructed.
  • +
  • 'Strainer': Material from which the strainer is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcInterceptorType type are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. Ports are reflected at occurrences of this type using the IfcRelDefinesByObject relationship. Refer to the documentation at IfcInterceptor for standard port definitions.

+ +
" +3734;IfcInterceptor;"

An interceptor is a device designed and installed in order to separate and retain deleterious, hazardous or undesirable matter while permitting normal sewage or liquids to discharge into a collection system by gravity.

+ +
HISTORY  New entity in IFC2x4
+ +

Type Use Definition

+

IfcInterceptor defines the occurrence of any interceptor; common information about interceptor types is handled by IfcInterceptorType. +The IfcInterceptorType (if present) may establish the common type name, usage (predefined type), properties, materials, ports, composition, assignments, and representations. +The IfcInterceptorType is attached using the IfcRelDefinesByType objectified relationship and is accessible by the IsTypedBy inverse attribute. +If the IfcInterceptorType has ports or aggregated elements, such objects are reflected at the IfcInterceptor occurrence using the IfcRelDefinesByObject relationship.

+ +

Property Use Definition

+

The property sets relating to this entity are defined by IfcPropertySet and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute. +Property sets may also be specified at the IfcInterceptorType, defining the common property data for all occurrences of the same type. +They are then accessible by the IsTypedBy inverse attribute pointing to IfcInterceptorType.HasPropertySets. +If both are given, then the properties directly defined at IfcInterceptor override the properties defined at IfcInterceptorType. +Refer to the documentation at the supertype IfcFlowTreatmentDevice and ancestors for inherited property set definitions.

+

The following property set definitions are applicable to this entity:

+ +

Quantity Use Definition

+

The quantities relating to this entity are defined by IfcElementQuantity and attached by the IfcRelDefinesByProperties relationship. +They are accessible by the IsDefinedBy inverse attribute.

+

The following base quantities are defined and shall be exchanged with the IfcElementQuantity.Name = 'BaseQuantities'. +Other quantities, being subjected to local standard of measurement, may be defined with another string value assigned to Name. +In this case a valid value for MethodOfMeasurement shall be provided.

+ + +

Material Use Definition

+

The material of the IfcInterceptor is defined by IfcMaterialConstituentSet or as a fallback by IfcMaterial, and attached by the RelatingMaterial attribute on the IfcRelAssociatesMaterial relationship. It is accessible by the HasAssociations inverse attribute. Material information can also be given at the IfcInterceptorType, defining the common attribute data for all occurrences of the same type. The following keywords for IfcMaterialConstituentSet.MaterialConstituents[n].Name shall be used: +

    +
  • Body: The primary material from which the object is constructed.
  • +
  • Cover: Material from which the cover or grating is constructed.
  • +
  • Strainer: Material from which the strainer is constructed.
  • +
+ +

Port Use Definition

+

The distribution ports relating to the IfcInterceptor are defined by IfcDistributionPort and attached by the IfcRelConnectsPortToElement relationship. + If the interceptor occurrence is defined by IfcInterceptorType, then the port occurrences must reflect those defined at the IfcInterceptorType using the IfcRelDefinesByObject relationship. + Ports are specific to the IfcInterceptor PredefinedType as follows indicated by the IfcDistributionPort Name, PredefinedType, and FlowDirection:

+ + " +3742;IfcClassification;" +

An IfcClassification is used for the arrangement of objects into a class or category according to a common purpose or their possession of common +characteristics. A classification in the sense of IfcClassification is taxonomy, or taxonomic scheme, arranged in a hierarchical structure. A category of objects relates to other categories in a generalization-specialization relationship. Therefore the classification items in an +classification are organized in a tree structure.

+ +
+HISTORY New class in IFC Release 1.5. Modified in IFC 2x. +
+
+IFC 2x4 CHANGE Attribute Edition made optional. Attributes: PublicationLocation, Description and ReferenceTokens added. Inverse attribute HasClassificationReferences added. +
+ +

Classification use definitions

+

IfcClassification identifies the classification system or source from which a classification notation is derived. Each classification reference or classification item, belonging to a single classification system, shall reference a single instance of IfcClassification. Therefore, each particular classification system or source used should have only one IfcClassification instance. However, because multiple classification is allowed, there may be many IfcClassification objects used, each identifying a different classification system or source.

+ +

A classification system declared may be either formally published (such as Omniclass, Uniclass, Masterformat, or DIN) or it may be a locally defined method of classifiying information. There are two methods to define a classification system within an IFC dataset:

+
    +
  1. Including the classification system structure within the dataset: Here a hierarchical tree of IfcClassificationItem's is included that defines the classification system including the relationship between the classification items. An IfcClassificationNotation is used to classify an object.
  2. +
  3. Referencing the classification system by a classification key or id: Here the IfcClassificationReference is used to assign a classification id or key to each classified object.
  4. +
+ +
" +3752;IfcExternalInformation;" + +

An IfcExternalInformation is the identification of an information source that is not explicitly represented in the current model or in the project database (as an implementation of the current model). The IfcExternalInformation identifies the external source (classification, document, or library), but not the particular items such as a dictionary entry, a classification notation, or a document reference within the external source

+ +

The IfcExternalInformation is an abstract supertype of +all external information entities.

+ +
+HISTORY New entity in IFC2x4. +
+ +
" +3756;IfcLibraryInformation;" + +

An IfcLibraryInformation describes a library where a library is a structured store of information, normally organized in a manner which allows information lookup through an index or reference value. IfcLibraryInformation provides the library Name and optional Version, VersionDate and Publisher attributes. A Location may be added for electronic access to the library.

+ +
+NOTE  The complete definition of the information in an external library is out of scope in this IFC release. +
+
+HISTORY  New +Entity in IFC2x. +
+
+IFC2x4 CHANGE  Location attribute added, HasLibraryReferences inverse attribute added (previous LibraryReference changed to inverse). +
+ +
" +3765;IfcLibraryReference;" + +

An IfcLibraryReference is a reference into a library of information by Location (provided as a URI). It also provides an optional inherited Identification key to allow more specific references to library sections or tables. The inherited Name attribute allows for a human interpretable identification of the library item. Also, general information on the library from which the reference is taken, is given by the ReferencedLibrary relation which identifies the relevant occurrence of IfcLibraryInformation.

+ +

The ifcLibraryReference additionally provides the capability to handle multilingual library entries. The Language attribute then holds the language tag for the language used by the strings kept in the Name and the Description attribute.

+ +
+HISTORY  New Entity in IFC2.0. +
+
+IFC2x4 CHANGE  Description and Language attribute added; ReferencedLibrary attribute added (reversing previous ReferenceIntoLibrary inverse relationship). +
+ +
" +3770;IfcExternalReference;" + +

An IfcExternalReference is the identification of information that is not explicitly represented in the current model or in the project database (as an implementation of the current model). Such information may be contained in classifications, documents or libraries. The IfcExternalReference identifies a particular item, such as a +dictionary entry, a classification notation, or a document reference within the external source.

+ +

Only the Location (as a URL) is given to describe the place where the information can be found. Also an optional +Identification as a key to allow more specific references (as to sections or tables) is provided. The Identification defines a system interpretable method to identify the relevant part of information at the source. In addition a human interpretable Name can be assigned to identify the information subject, such as a classification code.

+ +

IfcExternalReference is an abstract supertype of all external reference entities.

+ +
+HISTORY New entity in IFC2x. +
+ +
" +3779;IfcClassificationReference;" +

An IfcClassificationReference is a reference into a classification system or source (see IfcClassification) for a specific classification key (or notation).

+ +

The inherited attributes have the following meaning:

+
    +
  • Identification: holds the key provided for a specific references to classification items (or tables).
  • +
  • Name: allows for a human interpretable designation of a classification notation.
  • +
  • Location: optionally holds a direct URI link into the classification system (or source) to hyperlink the classification key.
  • +
+ +

The IfcClassificationReference can either be assigned directly to the IfcClassification, such as if no classification hierarchy has to be included, or it references the parent classification notation, if the fully classification hierarchy is included in the data set. The attribute ReferencedSource then holds the following information (choice by IfcClassificationReferenceSelect):

+
    +
  • being of type IfcClassification: direct reference to the classification system (with meta information provided), used for highest level of classification notations, or if the classification notation hierarchy is not relevant,
  • +
  • being of type IfcClassificationReference: reference to the parent classification notation within the classification hierarchy.
  • +
+ +
+HISTORY New entity in IFC 2x. +
+
+IFC2x4 CHANGE The attribute Description and inverse attribute HasReferences are added. The attribute Identification has been renamed from ItemReference. +
+ +

Use definitions

+

The IfcClassificationReference can be used to only assign classification keys to objects, or to hold a fully classification hierarchy. The first is refered to as ""lightweight classification"", and the second as ""full classification""

+ +

The IfcClassificationReference can be used as a form of 'lightweight' classification through the 'Identification' attribute inherited from the abstract IfcExternalReference class. In this case, the 'Identification' could take (for instance) the Uniclass notation ""L6814"" which, if the classification was well understood by all parties and was known to be taken from a particular classification source, would be sufficient. The Name attribute could be the title ""Tanking"". This would remove the need for the overhead of the more complete classification structure of the model.

+ +
" +3787;IfcDocumentReference;" + + +

An IfcDocumentReference is a reference +to the location of a document. The reference is given by a system +interpretable Location attribute (a URL string) where the document can be found, and an optional inherited + internal reference Identification, which refers to a system + interpretable position within the document. The optional inherited +Name attribute is meant to have meaning for human readers. Optional +document metadata can also be captured through reference to +IfcDocumentInformation.

+ + + +
+HISTORY: New Entity in IFC Release 2.0. + Modified in IFC 2x. +
+ + + + + +
" +3792;IfcDocumentInformation;" + +

IfcDocumentInformation captures ""metadata"" of an external document. The actual content of the document is not defined in IFC; instead, it can be found following the reference given to IfcDocumentReference.

+ +
+HISTORY: New entity in IFC 2x. +
+ +
" +3814;IfcDocumentElectronicFormat;" + +

IfcDocumentElectronicFormat captures the type of document being referenced as an external source, and for which metadata is specified by IfcDocumentInformation.

+ +
+HISTORY: New entity in IFC 2x +
+ +
" +3832;IfcDocumentInformationRelationship;" +

An IfcDocumentInformationRelationship is a relationship class that enables a document to have the ability to reference other documents.

+ +
+HISTORY  New entity in Release IFC2x. +
+
+IFC2x4 CHANGE  Subtyped from IfcResourceLevelRelationship, order of attributes changed. +
+ +

Use definitions

+

This class can be used to describe relationships in which one document may reference one or more other sub documents or where a document is used as a replacement for another document (but where both the original and the replacing document need to be retained).

+ +
" +3836;IfcResourceLevelRelationship;" + +

IfcResourceLevelRelationship is an abstract base class for relationships between resource-level entities.

+ +
+HISTORY New Entity in IFC 2x4 +
+ +
" +3849;IfcExternalReferenceRelationship;" + +

IfcExternalReferenceRelationship is a relationship entity that enables objects from the +IfcResourceObjectSelect to have the ability to be tagged by external references.

+ +
+NOTE This relationship is used to assign classification, library or document information to entities that +do not inherit from IfcRoot. It has a similar functionality as the subtypes of IfcRelAssociates. +
+ +
+HISTORY New Entity in IFC 2x4 +
+ +
" +3877;IfcConstraint;" +

An IfcConstraint is used to define a constraint or limiting value or boundary condition that may be applied to an object or to the value of a property.

+ +
+HISTORY: New Entity in IFC Release 2.0 +
+ +

Use Definition

+

IfcConstraint may be associated with any subtype of IfcRoot (unless restricted in specific subtypes) through the IfcRelAssociatesConstraint relationship in the IfcControlExtension schema, or may be associated with IfcProperty by IfcPropertyConstraintRelationship.

+ +

A constraint may aggregate other constraints through the IfcConstraintAggregationRelationship through which a logical association between constraints may be applied, or constraints may have other defined relationship to other constraints via IfcConstraintRelationship.

+ +

A constraint must have a name applied through the IfcConstraint.Name attribute and optionally, a description through IfcConstraint.Description. The grade of the constraint (hard, soft, advisory) must be specified through IfcConstraint.ConstraintGrade or IfcConstraint.UserDefinedGrade whilst the source, creating actor and time at which the constraint is created may be optionally asserted through IfcConstraint.ConstraintSource, IfcConstraint.CreatingActor and IfcConstraint.CreationTime.

+ +

A constraint may also have additional external information (such as classification or document information) associated to it by IfcExternalReferenceRelationship, accessible through inverse attribute IfcConstraint.HasExternalReferences

+ +
" +3893;IfcObjective;" + +

An IfcObjective captures qualitative information for an objective-based constraint.

+ +
+HISTORY: New Entity in IFC Release 2.0 +
+ +

Use definition

+ +

IfcObjective is a subtype of IfcConstraint and may be associated with any subtype of IfcRoot through the IfcRelAssociatesConstraint relationship in the IfcControlExtension schema, or may be associated with IfcProperty by IfcPropertyConstraintRelationship.

+ +

The aim of IfcObjective is to specify the purpose for which the constraint is applied and to capture the values of the constraint. These may be both the benchmark values that are intended to indicate the constraint extent and the resulting values in use that enable performance comparisons to be applied.

+ +
" +3899;IfcMetric;" + +

An IfcMetric is used to capture quantitative resultant metrics that can be applied to objectives.

+ +
+HISTORY: New Entity in IFC Release 2.0 +
+ +

Use Definition

+

IfcMetric is a subtype of IfcConstraint and may be associated with any subtype of IfcRoot through the IfcRelAssociatesConstraint relationship in the IfcControlExtension schema, or may be associated with IfcProperty by IfcPropertyConstraintRelationship.

+ +

The aim of IfcMetric is to capture the quantitative aspects of a constraint.

+ +

For instance, when undertaking a move (instantiated through the IfcTask class), a constraint is instantiated as the class IfcMetric and may be named as a 'Move Start Constraint' or 'Move End Constraint' and described using one of a possible range of move constraints as shown in the table below.

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Constraint Description Benchmark Grade
ASSOONASPOSSIBLEAction should commence at the earliest possible opportunity.GREATERTHANOREQUALTOSOFT
MUSTSTARTONAction must start at a prescribed date/time.EQUALTOHARD
MUSTSTARTBEFOREAction must start before a prescribed date/time.LESSTHANOREQUALTOHARD
MUSTSTARTAFTERAction must not start before a prescribed date/time.GREATERTHANOREQUALTOHARD
MAYSTARTAFTERAction may start at any time following a prescribed date/time.GREATERTHANOREQUALTOSOFT
MUSTFINISHONAction must be complete at or by a prescribed date/time.EQUALTOHARD
MUSTFINISHBEFOREAction must be complete before a prescribed date/time.LESSTHANOREQUALTOHARD
+ +

This constraint (instantiated as IfcMetric) uses a Date/Time value in IfcMetric.DataValue through IfcMetricValueSelect. An appropriate benchmark is applied according to the requirement of the constraint (as indicated) by IfcMetric.Benchmark. The grade of the constraint (hard, soft, advisory) must be specified through IfcConstraint.ConstraintGrade whilst the time at which the constraint is created may be optionally asserted through IfcConstraint.CreationTime.

+ +
" +3937;IfcResourceConstraintRelationship;" + +

An IfcResourceConstraintRelationship is a relationship +entity that enables a constraint to be related to one or more +resource level objects.

+ +
+HISTORY  New Entity in Release IFC2x2. +
+
+IFC2x4 CHANGE  Renamed from IfcPropertyConstraintRelationship and extended to apply to all resource level entities. Subtyped from IfcResourceLevelRelationship. +
+ +

Use definition

+ +

An IfcResourceConstraintRelationship allows for the +specification of a constraint to be applied to many entity types. +An important case is to apply constraints to properties. The +constraints applied therefore enable a property to carry values +identifying requirements as well as those identifying the +fulfilment of those requirements.

+ +

Figure 238 shows how a constraint may be applied to a property within a property set. For simplicity, only the mandatory attributes are shown as asserted. It shows how a property 'ThingWeight' which has a nominal value of 19.5 kg has two constraints that are logically aggregated by an AND connection. One of the constraints has a benchmark of 'GREATERTHANOREQUALTO' whilst the second has a benchmark of 'LESSTHANOREQUALTO'. This means that the constraint must lie between these two bounding values. The relating constraint is instantiated as an objective named as 'Weight Constraint' and qualified as a SPECIFICATION constraint. The two related constraints are both specified as metrics since they can have specific values.

+ + + + +

Figure 238 — Resource constraint relationship

+ +
" +3940;IfcConstraintRelationship;" +

An IfcConstraintRelationship is an objectified relationship that enables instances of IfcConstraint and its +subtypes to be associated to each other. Logical aggregation of instances of IfcConstraint and its subtypes is handled by the subtype IfcConstraintAggregationRelationship.

+ +
+EXAMPLE: Certain constraints related to an IfcWall may be derived from a constraint related to an +IfcSpace. +
+
+HISTORY  New entity in Release IFC2x2 (Addendum 1). +
+
+IFC2x4 CHANGE  Subtyped from IfcResourceLevelRelationship. +
+ +
" +3945;IfcConstraintAggregationRelationship;" + +

An IfcConstraintAggregationRelationship is an objectified relationship that enables instances of IfcConstraint subtypes to be aggregated together logically.

+ +
+HISTORY  New Entity in IFC Release 2.0. Modified in IFC2x2. +
+
+IFC2x4 CHANGE  Subtyped from IfcConstraintRelationship +
+ +

Use definition

+

IfcConstraintAggregationRelationship allows the aggregation link between subtypes of constraint to be logically defined (AND, OR, XOR, NOTAND, NOTOR). In this way, whereby an object or property can have multiple constraints assigned, and the logical linkage between them can be specified. Thus linked constraints might show as for example (> X AND < Y) which is useful for an allowed range, or bounded value, for example, (A OR B OR C) which is valuable for an enumerated property where a selection is constrained to be (at least) one of A, B or C.

+

Figure 237 illustrates constraint aggregation.

+ + + + +

Figure 237 — Constraint aggregation

+ +
" +3954;IfcCostValue;" + +

IfcCostValue is an amount of money or a value that affects an amount of money.

+ +
+HISTORY: New Entity in IFC Release 1.0 +
+ +

Use definitions

+

Each instance of IfcCostValue may also have a CostType. There are many possible types of cost value that may be identified. While there is a broad understanding of the meaning of names that may be assigned to different types of costs, there is no general standard for naming cost types nor are there any broadly defined classifications. To allow for any type of cost value, the IfcLabel datatype is assigned.

+ +

The following defines some cost types that might be applied:

+
    +
  • Annual rate of return
  • +
  • Bonus
  • +
  • Bulk purchase rebate
  • +
  • Contract
  • +
  • Consultancy
  • +
  • Delivery
  • +
  • Estimated cost
  • +
  • Hire
  • +
  • Installation
  • +
  • Interest rate
  • +
  • Labor
  • +
  • Lease
  • +
  • List price
  • +
  • Maintenance
  • +
  • Material
  • +
  • Overhead
  • +
  • Postage and packing
  • +
  • Profit
  • +
  • Purchase
  • +
  • Rental
  • +
  • Repair
  • +
  • Replacement
  • +
  • Sale
  • +
  • Small quantity surcharge
  • +
  • Spares
  • +
  • Storage
  • +
  • Sub-Contract
  • +
  • Trade discount
  • +
  • Transportation
  • +
  • Waste allowance
  • +
  • Whole life
  • +
+ +

In the absence of any well-defined standard, it is recommended that local agreements should be made to define allowable and understandable cost value types within a project or region.

+ +
" +3957;IfcAppliedValue;" + +

IfcAppliedValue is an abstract supertype that specifies the common attributes for cost values.

+ +
+HISTORY: New Entity in IFC2x2. Modifed in IFC2x4 to use IfcDate for date values. +
+ +

Use definitions

+

The extent of the IfcAppliedValue is determined by the AppliedValue attribute which may be defined either as an IfcMeasureWithUnit or as an IfcMonetaryMeasure or as an IfcRatioMeasure via the IfcAppliedValueSelect type.

+ +

Optionally, an IfcAppliedValue may have an applicable date. This is intended to fix the date on which the value became relevant for use. It may be the date on which the value was set in the model or it may be a prior or future date when the value becomes operable.

+ +

Similarly, an IfcAppliedValue may have a 'fixed until' date. This is intended to fix the date on which the value ceases to be relevant for use.

+ +

An instance of IfcAppliedValue may have a unit basis asserted. This is defined as an IfcMeasureWithUnit that determines the extent of the unit value for application purposes. It is assumed that when this attribute is asserted, then the value given to IfcAppliedValue is that for unit quantity. This is not enforced within the IFC schema and thus needs to be controlled within an application.

+ +

Applied values may be referenced from a document (such as a price list). The relationship between one or more occurrences of IfcAppliedValue (or its subtypes) is achieved through the use of the IfcExternalReferenceRelationship in which the document provides the IfcExternalReferenceRelationship.RelatingExtReference and the value occurrences are the IfcExternalReferenceRelationship.RelatedResourceObjects.

+ +
" +3973;IfcCurrencyRelationship;" + +

IfcCurrencyRelationship defines the rate of exchange +that applies between two designated currencies at a particular time +and as published by a particular source.

+ +
+HISTORY  New Entity in IFC2x2. +
+
+IFC2x4 CHANGE  Subtyped from IfcResourceLevelRelationship, attribute order changed. +
+ +

Use definitions

+

An IfcCurrencyRelationship is used where there may be a need to reference an IfcCostValue in one currency to an IfcCostValue in another currency. It takes account of fact that currency exchange rates may vary by requiring the recording the date and time of the currency exchange rate used and the source that publishes the rate. There may be many sources and there are different strategies for currency conversion (spot rate, forward buying of currency at a fixed rate).

+

The source for the currency exchange is defined as an instance of IfcLibraryInformation that includes a name and a URL.

+ +
" +3979;IfcAppliedValueRelationship;" + +

An IfcAppliedValueRelationship is a relationship class that enables cost values to be aggregated together as components of another cost value.

+ +
+HISTORY  New Entity in Release IFC2.0. +
+
+IFC2x4 CHANGE  Subtyped from IfcResourceLevelRelationship, attribute order changed. +
+ +

Use definitions

+

Dependency relationships can exist between applied values on the basis that one particular value may be determined by operations on one or more other values. This is captured through the IfcAppliedValueRelationship entity. In this relationship, one instance of IfcAppliedValue acts as the principal (IfcAppliedValueRelationship.ComponentOf) whose value may be +determined from the instances of IfcAppliedValue that are defined as its components +(IfcAppliedValueRelationship.Components)

+

An IfcAppliedValueRelationship has an ArithmeticOperator attribute that specifies the form of arithmetical operation implied by the relationship.

+

A practical consideration when using the applied value relationship is that when the arithmetic operator is ADD, then the +type of the IfcAppliedValue.AppliedValue attribute will be IfcMeasureWithUnit or IfcMonetaryMeasure while if the arithmetic operator is MULTIPLY, then the type of the IfcAppliedValue.AppliedValue attribute for one instance of +IfcAppliedValue will be IfcMeasureWithUnit or IfcMonetaryMeasure while for other instances it will be +IfcRatioMeasure.

+

If the arithmetic operator is SUBTRACT or DIVIDE then there can only be two occurrences of IfcAppliedValue that can contribute and the order in which they occur is significant. The value of (A - B) will usually differ from the value of (B - A) whilst (X / Y) is the reciprocal of (Y / X).

+ +

Figure 239 illustrates one level aggregation of applied values. A relationship exists between applied value A and applied values B, C and D such that the value of A is determined by the addition of B, C and D such that: A = B + C + D

+ + + + +

Figure 239 — Applied value relationship single level

+ +

Figure 240 illustrates two level aggregation of applied values. It is possible to develop more complex applied value specifications by creating hierarchies of applied value relationships. In the diagram, the development of a applied value is shown whereby, because B = E * F and D = G * H * J, then: A = ((E * F) + C + (G * H * J)).

+ + + + +

Figure 240 — Applied value relationship multiple level

+ +
" +3989;IfcResourceCost;" + +

IfcResourceCost defines cost information for resources.

+ +
+HISTORY: New Entity in IFC 2x4. +
+ +
" +4005;IfcTimeSeries;" + +

A time series is a set of a time-stamped data entries. It allows a natural association of data collected over intervals of time. Time series can be regular or irregular. In regular time series data arrive predictably at predefined intervals. In irregular time series some or all time stamps do not follow a repetitive pattern and unpredictable bursts of data may arrive at unspecified points in time.

+ +

The modeling of buildings and their performance involves data that are generated and recorded over a period of time. Such data cover a large spectrum, from weather data to schedules of all kinds to status measurements to reporting to everything else that has a time related aspect. Their correct placement in time is essential for their proper understanding and use, and the IfcTimeSeries subtypes provide the appropriate data structures to accommodate these types of data.

+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4017;IfcRegularTimeSeries;" + +

In a regular time series, the data arrives predictably at predefined intervals. In a regular time series there is no need to store multiple time stamps and the algorithms for analyzing the time series are therefore significantly simpler. Using the start time provided in the supertype, the time step is used to identify the frequency of the occurrences of the list of values.

+ +
+EXAMPLE: A smoke detector samples the concentration of particulates in a space at a fixed rate (for example, every six seconds); a control system measures the outside air temperature every hour. +
+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4020;IfcTimeSeriesValue;" + +

A time series value is a list of values that comprise the time series. At least one value must be supplied. Applications are expected to normalize values by applying the following three rules:

+
    +
  • All time (universal, local, daylight savings, and solar) is normalized against the ISO 8601 standard GMT/UTC (Universal Coordinated Time).
  • +
  • Any rollover is handled by the application providing the data. Rollover occurs, for example, when the measurement device resets itself while measuring and the recording data do not include the data measured before the reset.
  • +
  • The normalized data refer to the preceding time unit. The time series example shown in Figure 241 below contains four time points: Time ""a"" indicates the beginning of the time series and the associated datum has no relevance. Data at time points ""b,"" ""c"" and ""d"" are associated with values 1, 2 and 3, respectively.
  • +
+ + + + +

Figure 241 — Time series value

+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +4022;IfcIrregularTimeSeries;" + +

In an irregular time series, unpredictable bursts of data arrive at unspecified points in time, or most time stamps cannot be characterized by a repeating pattern.

+ +
+EXAMPLE: A circulating pump cycles on and off at unpredictable times as dictated by the demands on the piping system; the amount of light in a classroom varies depending on when the lights are manually switched on and off and and how many lamps are controlled by each switch. +
+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4024;IfcIrregularTimeSeriesValue;" + +

The IfcIrregularTimeSeriesValue describes a value (or set of values) at a particular time point.

+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4041;IfcTaskTime;" + +

IfcTaskTime captures the time-related information about a task including the different types (actual or scheduled) of starting and ending times.

+ +
+HISTORY: New entity in IFC2x4, adapted from IfcScheduleTimeControl. Differently to IfcScheduleTimeControl it is also possible to differentiate duration time measures between the two possible types; (1) work time and (2) elapsed time. +
+ +

Use definitions

+

All given values should be provided by the application; the IFC schema does not deal with dependencies between task time values. There is also no consistency check through where rules that guarantee a meaningful population of time values. Thus, an application is responsible to provide reasonable values and, if an application receives task times, has to make consistency checks by their own.

+ +

IfcTaskTime furthermore provides a generic mechanism to differentiate between user given time values and time values derived from user given time values and other constraints such as work calendars and assigned resources.

+ +
" +4060;IfcSchedulingTime;" + +

IfcSchedulingTime is the abstract supertype of entities that capture time-related information of processes.

+ +
+HISTORY: New entity in IFC2x4. +
+ +
" +4069;IfcLagTime;" + +

IfcLagTime describes the time parameters that may exist within a sequence relationship between two processes.

+ +
+HISTORY: New entity in IFC Release 2x4. +
+ +

Use Definitions

+

+ An IfcLagTime provides information about the + time lag that exists between the predecessor and successor + process in a sequence. The assertion of the time lag is + optional for a sequence but for work schedules that + specifically deal with processes occurring at particular + times, it should be asserted. +

+

+ A lag time has a duration type. This allows the + identification of whether elapsed time or work time is + being measured (where work time is the estimate of the time + required to complete the process and elapsed time being the + amount of time actually allocated to the process) +

+

+ The form of measurement of the duration can be captured. + Allowed values for this are MEASURED, PREDICTED or + SIMULATED. The selection of this value depends on the use + of the schedule. A NOTDEFINED value is also allowed. +

+

+ The value of the time lag may be selected as being either a + percentage ratio or an actual time measure. If selected as + a ratio, the percentage should apply to the duration of the + predecessor process (relating process) such that e.g. a + value of 0.5 (50%) would indicate that the successor task + should start when the predecessor task is 50% complete (if + a START-START sequence type is used) or should wait for 50% + of the duration of the predecessor process to have elapsed + after the finish of the predecessor process in case of a + FINISH-START sequence type. +

+

+ The time unit for the task duration may also be set and + this may be set to any allowed unit of time measure. +

+ +
" +4079;IfcResourceTime;" +

IfcResourceTime captures the time-related information about a construction resource.

+
HISTORY: New entity in IFC2x4.
+
" +4095;IfcEventTime;" +

+ IfcEventTime captures the time-related information about an event + including the different types of event dates (i.e. actual, + scheduled, early, and late). +

+
HISTORY: New entity in IFC2x4.
+

Use definitions

+

+ All given values should be provided by the application, + i.e. the IFC schema does not deal with dependencies between + process time values. At this stage there is also no + consistency check through where rules that guarantee a + meaningful population of date values. Thus, an application + is responsible to provide reasonable values and, if an + application receives event dates, has to make consistency + checks by their own. +

+

+ IfcEventTime furthermore provides a generic + mechanism to differentiate between user given time values + and time values derived from user given time values and + other constraints such as work calendars and assigned + resources (derived from the process graph). The data origin flag + is provided as a single attribute applying to all date time related attributes + of IfcEventTime. +

+
" +4100;IfcWorkTime;" + +

IfcWorkTime defines time periods that are used by IfcWorkCalendar for either describing working times or non-working exception times. Besides start and finish dates, a set of time periods can be given by various types of recurrence patterns.

+ +
+HISTORY: New entity in IFC2x4. +
+ +

Use definitions

+

A work time should have a meaningful name that describes the time periods (for example, working week, holiday name). Non-recurring time periods should have a start date (IfcWorkTime.Start) and a finish date (IfcWorkTime.Finish). In that case it is assumed that the time period begins at 0:00 on the start date and ends at 24:00 on the finish date.

+ +

The start and finish date is optional if a recurrence pattern is given (IfcWorkTime.RecurrencePattern). They then restrict never-ending recurrence patterns.

+ +
+ " +4104;IfcRecurrencePattern;" + +

IfcRecurrencePattern defines repetitive time periods on the basis of regular recurrences such as each Monday in a week, or every third Tuesday in a month. The population of the remaining attributes such as DayComponent, Position, and Interval depend on the specified recurrence type.

+ +
+HISTORY: New entity in IFC2x4. +
+ +

Use definitions

+

IfcRecurrencePattern supports various recurrence patterns that are differentiated by a type definition (IfcRecurrencePattern.RecurrenceType), which is required to provide the meaning of the given values. It can be further constrained by applicable times through specified IfcTimePeriod instances, thus enabling time periods such as between 7:00 and 12:00 and between 13:00 and 17:00 for each of the applicable days, weeks or months.

+ +
" +4128;IfcTimePeriod;" + +

IfcTimePeriod defines a time period given by a start and end time. Both time definitions consider the time zone and allow for the daylight savings offset.

+ +
+HISTORY: New entity in IFC R2x4. +
+ +

Use definitions

+

A time period is defined by a start and an end time, which is defined by IfcTime. The given time period should be within reasonable values (for example, the start time must be before the end time). It is furthermore expected that both time definitions use the same time zone and, if given, the same daylight saving offset.

+ +
" +4131;IfcTaskTimeRecurring;" + +

IfcTaskTimeRecurring is a recurring instance of IfcTaskTime for handling regularly scheduled or repetitive tasks.

+ +
HISTORY: New entity in IFC2x4.
+ +
" +4134;IfcConnectionGeometry;" + +

IfcConnectionGeometry is used to describe the geometric and topological constraints that facilitate the physical connection of two objects. It is envisioned as a control that applies to the element connection relationships.

+ +
+NOTE  The element connection relationship normally provides for a logical connection information, by referencing the relating and related elements. If in addition an IfcConnectionGeometry is provided, physical connection information is given by specifying exactly where at the relating and related element the element connection occurs. +Using the eccentricity subtypes, the connection can also be described when there is a physical distance (or eccentricity) between the connection elements. +
+ +

The IfcConnectionGeometry allows for the provision of connection constraints between geometric and topological elements, the following connection geometry/topology types are in scope:

+
    +
  • point | vertex point,
  • +
  • curve | edge curve,
  • +
  • surface | face surface,
  • +
+ +
+HISTORY  New entity in IFC Release 1.5. +
+ +
+IFC2x Edition 3 CHANGE  The definition of the subtypes has been enhanced by allowing either geometric representation items (point | curve | surface) or topological representation items with associated geometry (vertex point | edge curve | face  surface). +
+ +
" +4139;IfcConnectionPointGeometry;" +

IfcConnectionPointGeometry +is used to describe the geometric constraints that facilitate the +physical connection of two objects at a point (here IfcCartesianPoint) or at an vertex with point +coordinates associated. It is envisioned as a control that applies to the element connection relationships.

+ +
+EXAMPLE  The connection relationship between two path based elements (like a column and a beam) has a geometric constraint which describes the connection points by a PointOnRelatingElement for the column and a PointOnRelatedElement for the beam. The exact usage of the IfcConnectionPointGeometry is further defined in the geometry use sections of the elements that use it.
+
+NOTE  If the point connection has an offset (if the two points or vertex points at the relating and related element do not physically match), the subtype IfcConnectionPointEccentricity shall be used. +
+ +
+HISTORY  New entity in IFC Release 1.5, has been renamed from IfcPointConnectionGeometry in IFC Release 2x. +
+
+IFC2x Edition 3 CHANGE  The provision of topology with associated geometry, IfcVertexPoint, is +enabled by using the IfcPointOrVertexPoint. +
+ +

Geometry use definitions

+

The IfcPoint (or the IfcVertexPoint with an associated IfcPoint) at the PointOnRelatingElement attribute defines the point where the basic geometry items of the connected elements connect. The point coordinates are provided within the local coordinate system of the RelatingElement, as specified at the IfcRelConnectsSubtype that utilizes the IfcConnectionPointGeometry. Optionally, the same point coordinates can also be provided within the local coordinate system of the RelatedElement by using the PointOnRelatedElement attribute. If both point coordinates are not identical within a common parent coordinate system (ultimately within the world coordinate system), the subtype IfcConnectionPointEccentricity shall be used.

+ +
" +4143;IfcConnectionPointEccentricity;" + +

IfcConnectionPointEccentricity is used to describe the geometric constraints that facilitate the physical connection of two objects at a point or vertex point with associated point coordinates. There is a physical distance, or eccentricity, etween the connection points of both object. The eccentricity can be either given by:

+
    +
  • providing the PointOnRelatingElement and the PointOnRelatedElement, where bothÿpoint coordinates are not identical within a common parent coordinate system (latestly within the world coordinate system),
  • +
  • providing the PointOnRelatingElement and the three distance measures, EccentricityInX, EccentricityInY, and EccentricityInZ (or only EccentricityInX, and EccentricityInY if the +underlying coordinate system is two-dimensional), or
  • +
  • providing both.
  • +
+ +
+NOTEÿ If both, PointOnRelatedElement, and EccentricityInX, EccentricityInY, (EccentricityInZ) are provided, the values should be consistent. In case of any non-consistency, the calculated distance between PointOnRelatingElement and PointOnRelatedElement takes precedence. +
+ +

The explicit values for EccentricityInX, EccentricityInY, and EccentricityInZ are always +measured in the following direction and coordinate system (defining when the value is positive or negative):

+
    +
  • from the PointOnRelatedElement to PointOnRelatingElement within the coordinate system of the RelatingElement.
  • +
  • in addition: when used to specify connections in structural analysis models, the IfcStructuralMember is to be used as the RelatingElement of the relationship object utilizing IfcConnectionPointEccentricity, and the IfcStructuralConnection is the RelatedElement.
  • +
+ +
+HISTORYÿ New entity in IFC 2x Edition 3. +
+ +

Geometry use definitions

+

The IfcPoint (or the IfcVertexPoint with an associated IfcPoint) at the PointOnRelatingElement attribute defines the point where the basic geometry items of the connected elements connects. The point coordinates are provided within the local coordinate system of the RelatingElement, as specified at the IfcRelConnects subtype that utilizes the IfcConnectionPointGeometry. Optionally, the same point coordinates can also be provided within the local coordinate system of the RelatedElement by using the PointOnRelatedElement attribute, otherwise the distance to the point at the RelatedElement has to be given by the three eccentricity values.

+ +
" +4150;IfcConnectionCurveGeometry;" + +

IfcConnectionCurveGeometry is used to describe the geometric constraints that facilitate the physical connection of two objects at a curve or at an edge with curve geometry associated. It is envisioned as a control that applies to the element connection relationships.

+ +
+EXAMPLE  The connection relationship between two walls has a geometric constraint which describes the end caps (or cut-off of the wall ends) by a CurveOnRelatingElement for the first wall and a CurveOnRelatedElement for the second wall. The exact usage of the IfcConnectionCurveGeometry is further defined in the geometry use sections of the elements that use it. +
+ +

The available geometry for the connection constraint may be further restricted to only allow straight segments by applying IfcPolyline +only. Such an usage constraint is provided at the object definition of the IfcElement subtype, utilizing the element connection by referring to the subtype of IfcRelConnects with the associated IfcConnectionCurveGeometry.

+ +
+HISTORY  New entity in IFC Release 1.5, has been renamed from IfcLineConnectionGeometry in IFC Release 2x. +
+
+IFC2x Edition 3 CHANGE  The provision of topology with associated geometry, IfcEdgeCurve, is enabled by using the IfcCurveOrEdgeCurve. +
+ +

Geometry use definitions

+

The IfcCurve (or the IfcEdgeCurve with an associated IfcCurve) at the CurveOnRelatingElement attribute defines the curve where the basic geometry items of the connected elements connects. The curve geometry and coordinates are provided within the local coordinate system of the RelatingElement, as specified at the IfcRelConnects Subtype that utilizes the IfcConnectionCurveGeometry. Optionally, the same curve geometry and coordinates can also be provided within the local coordinate system of the RelatedElement by using the CurveOnRelatedElement attribute.

+ +
" +4156;IfcConnectionSurfaceGeometry;" + +

IfcConnectionSurfaceGeometry is used to describe the geometric constraints that facilitate the physical connection of two objects at a surface or at a face with surface geometry associated. It is envisioned as a control that applies to the element connection relationships.

+ +
+HISTORY  New entity in IFC Release 2x. +
+
+IFC2x Edition 3 CHANGE  The provision of topology with associated geometry, IfcFaceSurface, is enabled by using the IfcSurfaceOrFaceSurface. +
+ +

Geometry use definitions

+

The IfcSurface (or the IfcFaceSurface with an associated IfcSurface) at the SurfaceOnRelatingElement attribute defines the surface where the basic geometry items of the connected elements connects. The surface geometry and coordinates are provided within the local coordinate system of the RelatingElement, as specified at the IfcRelConnectsSubtype that utilizes the IfcConnectionSurfaceGeometry. Optionally, the same surface geometry and coordinates can also be provided within the local coordinate system of the RelatedElement by using the SurfaceOnRelatedElement attribute.

+ +
" +4163;IfcConnectionVolumeGeometry;" + +

IfcConnectionVolumeGeometry is used to describe the geometric constraints that facilitate the physical connection (or overlap) of two objects at a volume defined by a solid or closed shell. It is envisioned as a control that applies to the element connection or interference relationships.

+ +
+HISTORYÿ New entity in IFC2x4. +
+ +

Geometry use definitions

+

The IfcSolidModel (or the IfcClosedShell) at the VolumeOnRelatingElement attribute defines the volume where the basic geometry items of the interfering elements overlap. The volume geometry and coordinates are provided within the local coordinate system of the RelatingElement, as specified at the subtypes of the relationship IfcRelConnects that utilizes the IfcConnectionSurfaceGeometry. Optionally, the sameÿvolume geometry and coordinates can also be provided within the local coordinate system of the RelatedElement by using the VolumeOnRelatedElement attribute.

+ +
" +4169;IfcGridAxis;" + +

An individual axis, IfcGridAxis, is defined in the context of a design grid. The axis definition is based on a curve of dimensionality 2. The grid axis is positioned within the XY plane of the position coordinate system defined by the IfcDesignGrid.

+ +
+HISTORY  New entity in IFC Release 1.0 +
+ +

Geometry use definitions

+

The standard geometric representation of IfcGridAxis is +defined using a 2D curve entity. Grid axes are normally defined +by an offset to another axis. The IfcOffsetCurve2D +supports this concept.

+

Each grid axis has a sense given by the parameterization of +the curve. The attribute SameSense is an indicator of +whether or not the sense of the grid axis agrees with, or +opposes, that of the underlying curve.

+

As shown in Figure 242, the grid axis is defined as a 2D curve within +the xy plane of the position coordinate system. Any curve can be +used to define a grid axis, most common is the use of IfcLine for +linear grids and IfcCircle for radial grids.

+

Most grids are defined by a pair of axis +lists, each defined by a base grid axis and axes given by an +offset to the base axis. The use of IfcOffsetCurve2D as +underlying AxisCurve supports this concept.

+ + + + +

Figure 242 — Grid axis

+ +
" +4179;IfcVirtualGridIntersection;" + +

IfcVirtualGridIntersection defines the derived location of the intersection between two grid axes. Offset values may be given to set an offset distance to the grid axis for the calculation of the virtual grid intersection.

+ +

The two intersecting axes (IntersectingAxes) define the intersection point, which exact location (in terms of the Cartesian point representing the intersection) has to be calculated from the geometric representation of the two participating curves.

+ +
+NOTE The IfcGrid local placement, that can be provided relative to the local placement of another spatial structure element, has to be taken into account for calculating the absolute placement of the IfcVirtualGridIntersection. Where rules and informal rules ensure, that the IntersectingAxes belong to the same IfcGrid +
+ +

Offset values may be given (OffsetDistances). If given, the position within the list of OffsetDistances +corresponds with the position within the list of IntersectingAxes. Therefore:

+
    +
  • OffsetDistances[1] sets the offset to IntersectingAxes[1],
  • +
  • OffsetDistances[2] sets the offset to IntersectingAxes[2], and
  • +
  • OffsetDistances[3] sets the offset to the virtual intersection in direction of the orientation of the cross product +of IntersectingAxes[1] and the orthogonal complement of the IntersectingAxes[1] (which is the positive or negative +direction of the z axis of the design grid position).
  • +
+ +
+HISTORY  New entity in IFC Release 1.5. The entity name was changed from IfcConstraintRelIntersection in IFC Release 2x. +
+ +

Informal Propositions:

+
    +
  1. Both, IntersectingAxes[1] and +IntersectingAxes[2] shall be two IfcGridAxis +defined by the same IfcGrid.
  2. +
  3. IntersectingAxes[1] and IntersectingAxes[2] +shall not be part of the same row of grid axes, i.e. both shall +not be within the same set of IfcGrid.UAxes or +IfcGrid.VAxes of the corresponding IfcGrid.
  4. +
+

Geometry use definitions:

+

The following figures explain the usage of the OffsetDistances and IntersectingAxes attributes.

+ +

Figure 246 illustrates two offset distances given where the virtual intersection is defined in the xy plane of the grid axis placement.

+ + + + +

Figure 246 — Virtual grid intersection with two offsets

+ +

Figure 247 illustrates three offset distances given where the virtual intersection is defined by an offset (in direction of the +z-axis of the design grid placement) to the virtual intersection in the xy plane of the grid axis placement.

+ + + +

Figure 247 — Virtual grid intersection with three offsets

+ +

The distance of the offset curve (OffsetDistances[n]) +is measured from the basis curve. The distance may be positive, +negative or zero. A positive value of distance defines an offset +in the direction which is normal to the curve in the sense of an +anti-clockwise rotation through 90 degrees from the tangent +vector T at the given point. (This is in the direction of +orthogonal complement(T).) This can be reverted by the +SameSense attribute at IfcGridAxis which may switch +the sense of the AxisCurve.

+

Illustration

+ +

Figure 248 illustrates an example of a negative offset where the figure shows the side of the offset.

+
    +
  • IntersectingAxes[1].AxisCurve is an +IfcTrimmedCurve with an IfcCircle as +BasisCurve and SenseAgreement = TRUE.
  • +
  • IntersectingAxes[1].SameSense = TRUE.
  • +
  • OffsetDistances[1] is a negative length measure
  • +
+ + + + +

Figure 248 — Virtual grid intersection negative offset

+ +
" +4182;IfcGridPlacement;" + +

IfcGridPlacement provides a specialization of IfcObjectPlacement in which +the placement and axis direction of the object coordinate system is defined by a reference to the design grid as defined in IfcGrid.

+

The location of the object coordinate system is given by the attribute PlacementLocation. It is defined as an +IfcVirtualGridIntersection, that is, an intersection between two grid axes with optional offsets.

+

The axis direction of the x-axis of the object coordinate +system is given either:

+
    +
  • PlacementRefDirection = NIL: by the tangent of the first grid axis (PlacementLocation.IntersectingAxes[1]) at the virtual intersection (maybe using the offset curve, if PlacementLocation.OffsetDistances is given);
  • +
  • PlacementRefDirection = IfcDirection: by the explicitly provided direction information;
  • +
  • PlacementRefDirection = IfcVirtualGridIntersection: by the tangent between the virtual grid intersection of PlacementLocation and the virtual grid intersection of PlacementRefDirection. Offsets as potentially provided in the IfcVirtualGridIntersection's of PlacementLocation and PlacementRefDirection have to be taken into account.
  • +
+

The direction of the y-axis of the IfcGridPlacement is the orthogonal complement to the x-axis. The plane defined by the x and y axis shall be co-planar to the xy plane of the local placement of the IfcGrid.ÿ

+

The direction of the z-axis is the orientation of the cross product of the x-axis and the y-axis, i.e. the z-axis of the IfcGridPlacement shall be co-linear to the z-axis of the local placement of the IfcGrid.

+ +
+NOTE The IfcGrid local placement, that can be provided relative to the local placement of another spatial structure element, has to be taken into account for calculating the absolute placement of the virtual grid intersection. +
+
+NOTE The PlacementLocation.OffsetDistances[3] and the PlacementRefDirection.OffsetDistances[3] shall either not be assigned or should have the same z offset value. +
+
+HISTORY ÿNew entity in IFC Release 1.5. The entity name was changed from IfcConstrainedPlacement in IFC Release 2x. +
+
+IFC2x4 CHANGE Attribute data type of PlacementRefDirection has been changed to IfcGridPlacementDirectionSelect. +
+ +

Geometry use definitions

+

The following examples show the usage of placement location and direction for an IfcGridPlacement.

+ + +

Figure 243 illustrates the case where PlacementRefDirection is not given - the object coordinate system is defined by:

+
    +
  • its location: given by the virtual grid intersection of PlacementLocation
  • +
  • its x-axis direction: given by the tangent of the first intersecting axis in the offset location of the virtual grid intersection
  • +
+ + + + +

Figure 243 — Grid placement

+ +

Figure 244 illustrates the case where PlacementRefDirection is given as an IfcDirection- the object coordinate system is defined by: +

    +
  • its location: given by the virtual grid intersection of PlacementLocation
  • +
  • its x-axis direction: given by the DirectionRatios of the IfcDirection, only the ratios for x and y are taken into account,
  • +
+ + + + +

Figure 244 — Grid placement with direction

+ +

Figure 245 illustrates the case where PlacementRefDirection is given as an IfcVirtualGridIntersection- the object coordinate system is defined by: +

    +
  • its location: given by the virtual grid intersection of PlacementLocation
  • +
  • its x-axis direction: given by the tangent of the line between the virtual grid intersection of the PlacementLocation and the virtual grid intersection of the PlacementRefDirection.
  • +
+ + + + +

Figure 245 — Grid placement with intersection

+ +
" +4185;IfcObjectPlacement;" +

IfcObjectPlacement is an abstract supertype for the special types defining the object coordinate system. The +IfcObjectPlacement has to be provided for each product that has a shape representation.

+

The object placement can be given:

+
    +
  • absolute: by an axis2 placement, relative to the world coordinate system,
  • +
  • relative: by an axis2 placement, relative to the object placement of another product,
  • +
  • by grid reference: by the virtual intersection and reference direction given by two axes of a design grid.
  • +
+

In any case the object placement has to unambiguously define the object coordinate system as either two-dimensional axis placement (IfcAxis2Placement2D) or three-dimensional axis placement (IfcAxis2Placement3D). The axis placement may have to be calculated.

+ +
+HISTORY New entity in IFC Release 2x. +
+ +
" +4190;IfcLocalPlacement;" + +

IfcLocalPlacement defines the relative placement of a product in relation to the +placement of another product or the absolute placement of a product within the geometric representation context of the project.

+

IfcLocalPlacement allows that an IfcProduct can be placed by this IfcLocalPlacement (through +the attributeObjectPlacement) within the local coordinate system of the object placement of another IfcProduct, +which is referenced by the PlacementRelTo. Rules to prevent cyclic relative placements have to be introduced on the +application level.

+

If the PlacementRelTo is not given, then +the IfcProduct is placed absolutely within the +world coordinate system.

+ +
+HISTORY: New entity in IFC Release 1.0. +
+ +

Geometry use definitions

+

The following conventions shall apply as default relative positions if the relative placement is used. The conventions are given for all five direct subtypes of IfcProduct, the IfcSpatialStructureElement, IfcElement, IfcAnnotation, IfcGrid, IfcPort. More detailed placement information is given at the level of subtypes of those five types mentioned.

+
    +
  • For the subtypes of IfcSpatialStructureElement the following conventions apply +
      +
    • IfcSite shall be placed absolutely within the world coordinate system established by the geometric +representation context of the IfcProject
    • +
    • IfcBuilding shall be placed relative to the local placement of IfcSite
    • +
    • IfcBuildingStorey shall be placed relative to the local placement of IfcBuilding
    • +
    +
  • +
  • For IfcGrid and IfcAnnotation the convention applies that it shall be placed relative +
      +
    • to the local placement of its container (IfcSite, IfcBuilding, IfcBuildingStorey) +
        +
      • it should be the same container element that is referenced by the IfcRelContainedInSpatialStructure +containment relationship,
      • +
      +
    • +
    +
  • +
  • For IfcPort the convention applies that it shall be placed relative +
      +
    • to the local placement of the element it belongs to (IfcElement) +
        +
      • it should be the same element that is referenced by the IfcRelConnectsPortToElement connection +relationship,
      • +
      +
    • +
    +
  • +
  • For IfcElement the convention applies that it shall be placed relative: +
      +
    • to the local placement of its container (IfcSite, IfcBuilding, IfcBuildingStorey) +
        +
      • it should be the same container element that is referenced by the IfcRelContainedInSpatialStructure +containment relationship,
      • +
      +
    • +
    • to the local placement of the IfcElement to which it is tied by an element composition relationship +
        +
      • for features that are located relative to the main component (such as openings), as expressed by IfcRelVoidsElement and IfcRelProjectsElement,
      • +
      • for elements that fill an opening (such as doors or windows), as expressed byIfcRelFillsElement,
      • +
      • for coverings that cover the element, as expressed byIfcRelCoversBldgElements,
      • +
      • for sub components that are aggregated to the main component, as expressed by IIfcRelAggregates and IfcRelNests)
      • +
      +
    • +
    +
  • +
+

If the PlacementRelTo relationship is not given, then it defaults to an absolute placement within the world +coordinate system established by the referenced geometric representation context within the project.

+ +
" +4199;IfcMaterial;" + +

IfcMaterial is a homogeneous or inhomogeneous +substance that can be used to form elements (physical products or +their components).

+

IfcMaterial is the basic entity for material +designation and definition; this includes identification by name +and classification (via reference to an external classification), +as well as association of material properties (isotropic or +anisotropic) defined by (subtypes of) +IfcMaterialProperties. An instance of IfcMaterial +may be associated to an element or element type using the +IfcRelAssociatesMaterial relationship. The assignment +might either be direct as a single material information, or +via

+
    +
  • a material layer set
  • +
  • a material profile set
  • +
  • a material constituent set
  • +
+

An IfcMaterial may also have presentation information +associated. Such presentation information is provided by +IfcMaterialDefinitionRepresentation, associating line +styles, hatching definitions or surface coloring/rendering +information to a material.

+ +
+HISTORYÿNew entity in IFC2x4 +
+ +
+IFC2x4 CHANGEÿ The attributes Description and Category have been added. +
+ +
" +4206;IfcMaterialDefinition;" +

IfcMaterialDefinition is a general supertype for all +material related information items in IFC that have common +material related properties that may include association of +material with some shape parameters or assignments to identified +parts of a component.

+

There are three ways of assigning materials to a single component or +multiple components; they are characterized as:

+
    +
  • by layer - assigning a material to a layer with constant +thickness
  • +
  • by profile - assigning a material to a profile with a +constant of varying shape along an extrusion
  • +
  • by constituents - assigning a material to an identified part +of a component shape; the identification is by a keyword rather than +by a shape parameter
  • +
+

Each instantiable subtype of IfcMaterialDefinition may +have material properties assigned, or have an external +classification of its definition. It can be assigned to either a +subtype of IfcElement, or a subtype of +IfcElementType by using the objectified relationship +IfcRelAssociatesMaterial.

+ +
+HISTORYÿ New entity in IFC2x4 +
+ +
" +4217;IfcMaterialLayer;" + +

IfcMaterialLayer is a single and identifiable part of an element which is constructed of a number of layers (one or more). Each IfcMaterialLayer has a constant thickness and is located relative to the referencing IfcMaterialLayerSet along the MlsBase.

+ +
+

EXAMPLE  A cavity wall with brick masonry used with +an air gap in between would be modeled using three +IfcMaterialLayer's: [1] Brick, [2] Air gap, [3] Brick. The +inner layer ""Brick"" would have a Name = ""Brick"", an +individual LayerThickness, and potentially a +Category indicating it as ""load bearing"", and a +Priority that controls how this material layer interacts +with other material layers in wall connections.

+
+ +

The IfcMaterialLayer may have a material layer name, +that might be different to the IfcMaterial name +referenced.

+ +
+

EXAMPLE  The IfcMaterialLayer name of an +insulation layer can be ""Insulation"", whereas the +IfcMaterial name is ""polystyrene insulating +boards"".

+
+ +
+HISTORY  New entity in IFC 1.5 +
+ +
+IFC2x4 CHANGE  The attributes Name, Description, Category, Priority have been added at the end of attribute list. Data type of LayerThickness relaxed to IfcNonNegativeLengthMeasure. +
+ +
" +4227;IfcMaterialLayerWithOffsets;" +

IfcMaterialLayerWithOffsets is a specialization of IfcMaterialLayer enabling definition +of offset values along edges (within the material layer set usage in parent layer set).

+ +

It defines the assignment of two offset values for a material +layer in its intended use within a material layer set. Offsets are +applied to the edges of layered elements (that is, in directions +perpendicular to the layer set direction). Offsets shall not be +used in layer set direction, that is, for modelling gaps (or overlaps) +between layers; gaps shall be modeled as layers with appropriate +material assignment for the void.

+ +
EXAMPLE   At the top of a standard wall, +with shape representation SweptSolid, offset of a given layer can +be specified in the direction of the extrusion (positive Z axis), +applied at the start or end (extruded from bottom to top), and with +a positive (extending above extrusion) or negative (ending below +extrusion).
+
+Take a standard wall with the outer material layer for the +external isolation extending above extrusion by 100mm, but starting +at the same base height. In this case the following values are +set: +
    +
  • OffsetDirection = .AXIS3.
  • +
  • OffsetValues[1] = 0.0
  • +
  • OffsetValues[2] = 100.0 (default unit assumed to +be mm)
  • +
+
+ +
+HISTORY  New Entity in IFC2x4. +
+ +

Informal propositions

+
    +
  1. The OffestDirection shall not be identical to the +LayerSetDirection of the corresponding +IfcMaterialLayerSetUsage
  2. +
  3. The attribute ReferenceExtent shall be asserted at the +corresponding IfcMaterialLayerSetUsage
  4. +
+ +

Attribute use definition

+

The OffsetValues and OffsetDirection correspond to the definitions ReferenceExtent and LayerSetDirection at the IfcMaterialLayerSetUsage.

+

Figure 289 shows an example of applying the OffsetValues to the material layers of a standard wall.

+ + + + +

Figure 289 — Material layer with offsets

+ +
" +4234;IfcMaterialLayerSet;" + +

IfcMaterialLayerSet is a designation by which materials of an element constructed of a number of material layers is known and through which the relative positioning of individual layers can be expressed.

+ +

The Material Layer Set Base (MlsBase) describes the axis along +which the material layers are positioned. The MlsBase is positioned +along the reference axis or reference plane of the element +supporting the IfcMaterialLayerSetUsage concept with a +potential offset (see here). The positive Material Layer Set +Direction (MlsDirection) describes the direction by which the +individual material layers, with their material layer thicknesses +are stacked. IfcMaterialLayer's are stacked with no gap, +gaps within a material layer set are expresses as layers by +themselves.

+ +
+

EXAMPLE A cavity brick wall would be modeled as +IfcMaterialLayerSet consisting of three +IfcMaterialLayer's: brick, air cavity and brick. The air +gap is identified, using the IsVentilated flag at +IfcMaterialLayer.

+
+ +
+HISTORY  New entity in IFC 1.0 +
+ +
+IFC2x4 CHANGE  Subtyped from IfcMaterialDefinition, the attribute Description +has been added at the end of attribute list. +
+ +

Attribute use definition

+

As shown in Figure 285, each IfcMaterialLayerSet implicitly defines a material +layer set base line (MlsBase), to which the start of the first +IfcMaterialLayer is aligned. The total thickness of a +layer set is calculated from the individual layer thicknesses, the +first layer starting from the MlsBase and following layers being +placed on top of the previous (no gaps or overlaps).

+ + + + +

Figure 285 — Material layer set

+ +
" +4239;IfcMaterialProfileSet;" + +

IfcMaterialProfileSet is a designation by which individual material(s) of a prismatic element (for example, beam or column) constructed of a single or multiple material profiles is known. If only a single material profile is used (the most typical case) then no CompositeProfile is asserted.

+ +
NOTE ÿ In case of multiple MaterialProfiles, the relative positioning of individual profiles in IfcMaterialProfileSet are defined using the concept of IfcCompositeProfileDef in IfcProfileResource schema; otherwise, only one MaterialProfile is given and defined by an individual IfcProfileDef (subtype).
+ +
+HISTORYÿNew Entity in IFC2x4. +
+ +
" +4244;IfcMaterialProfile;" + +

IfcMaterialProfile is a single and identifiable part of an element which is constructed of a number of profiles (one or more).

+ +
NOTE ÿ In case of multiple MaterialProfiles, the relative positioning of individual profiles in IfcMaterialProfileSet are defined using the concept of IfcCompositeProfileDef in IfcProfileResource schema; otherwise, only one MaterialProfile is given and defined by an individual IfcProfileDef (subtype).
+ +
+HISTORYÿNew Entity in IFC2x4 +
+ +
" +4253;IfcMaterialProfileWithOffsets;" + +

IfcMaterialProfileWithOffsets is a specialization of IfcMaterialProfile enabling definition offset values for profile start or end in its use in parent material profile set usage.

+ +

Relative positions of IfcMaterialProfileWithOffsets in the longitudinal direction of an element can be defined giving offsets at the start and end. This shall not be used for relative positions of individual profiles in the plane of profile definition, which is given in composite profile definition itself. Also, care should be taken especially when used with IfcMaterialProfileSetUsageTapering for correct start and end offset assignement.

+ +
+HISTORYÿ New Entity in IFC2x4. +
+ +
" +4255;IfcMaterialConstituentSet;" + +

IfcMaterialConstituentSet is a collection of individual material constituents, each assigning a material to a part of an element. The parts are only identified by a keyword (as opposed to an IfcMaterialLayerSet or IfcMaterialProfileSet where each part has an individual shape parameter (layer thickness or layer profile).

+ +
EXAMPLE The different materials of a window +construction shall be provided for the window lining and the +window glazing. An IfcMaterialConstituentSet is assigned +to the window with two IfcMaterialConstituent's, one with +the Name = 'Lining', one with the Name = +'Glazing'.
+NOTE See the ""Material Use Definition"" at the individual +element to which an IfcMaterialConstituentSet may apply +for a required or recommended definition of such +keywords.
+ +
+HISTORYÿNew Entity in IFC2x4. +
+ +
" +4259;IfcMaterialConstituent;" + +

IfcMaterialConstituent is a single and identifiable part of an element which is constructed of a number of part (one or more) each having an individual material. The association of the material constituent to the part is provided by a keyword as value of the Name attribute.

+ +
NOTE See the ""Material Use Definition"" at the individual element to which an IfcMaterialConstituentSet may apply for a required or recommended definition of such keywords as value for IfcMaterialConstituent.Name.
+ +
+HISTORYÿNew Entity in IFC2x4 +
+ +
" +4266;IfcMaterialRelationship;" +

IfcMaterialRelationship defines a relationship between part and whole in material definitions (as in composite materials). The parts, expressed by the set of RelatedMaterials, are material constituents of which a single material aggregate is composed.

+ +
+HISTORYÿNew Entity in IFC2x4 +
+ +
" +4270;IfcMaterialProperties;" +

IfcMaterialProperties is defined as an abstract +supertype for entities that apply material properties to material +definitions. A set of material properties that are assigned to an +individual material definiton may be identified by a Name +and a Description.

+ +
+

NOTE  The set of material properties can be assigned +to an individual IfcMaterial, a set or composite of +materials (IfcMaterialConstituent, +IfcMaterialConstituentSet), or set or individual material +layer (IfcMaterialLayer, IfcMaterialLayerSet), or +a set or individual material profile (IfcMaterialProfile, +IfcMaterialProfileSet)

+
+ +

The applicable set of material properties is defined at the +subtype IfcExtendedMaterialProperties. It includes +material properties defined in this IFC specification and those +defined as user-defined extended material properties.

+ +
+HISTORY  New Entity in IFC 2x. +
+ +
+IFC2x4 CHANGE  The subtypes that represented a fixed list of statically defined material properties, IfcMechanicalMaterialProperties, IfcThermalMaterialProperties, IfcHygroscopicMaterialProperties, IfcGeneralMaterialProperties, IfcOpticalMaterialProperties, IfcWaterProperties, IfcFuelProperties, IfcProductsOfCombustionProperties have been deleted, use the generic IfcExtendedMaterialProperties instead. +
+ +
" +4275;IfcExtendedMaterialProperties;" + +

The IfcExtendedMaterialProperties assign a set of +defined material properties to associated material definitions. +This provides a mechanism to assign any material properties to +material. Those material properties that are defined as part of the +IFC specification are provided within the use definitions +below.

+
NOTE The usage of this entity has changed in +IFC2x4, it is now used to express all material +properties.
+

The IfcProperty (instantiable subtypes) is used to +express the individual material properties.

+ +
+HISTORY  New entity in Release IFC2x. +
+ +
+IFC2x4 CHANGE  The attributes Name and Description are promoted to supertype, +attribute ExtendedProperties has been renamed to Properties. +
+ +

Extended property use definitions

+

The following sets of material property definitions are part of +this IFC release:

+ +
" +4277;IfcMaterialClassificationRelationship;" + +

IfcMaterialClassificationRelationship is a relationship assigning classifications to materials.

+ +
+HISTORYÿ New entity in IFC2x. +
+ +
+IFC2x4 CHANGEÿ The entity IfcMaterialClassificationRelationship is deprecated since IFC2x4 and shall no longer be used. Use IfcExternalReferenceRelationship instead. +
+ +
" +4280;IfcMaterialLayerSetUsage;" +

IfcMaterialLayerSetUsage determines the usage of +IfcMaterialLayerSet in terms of its location and +orientation relative to the associated element geometry. The +location of material layer set shall be compatible with the +building element geometry (that is, material layers shall fit inside +the element geometry). The rules to ensure the compatibility +depend on the type of the building element.

+ +
EXAMPLE ÿFor a cavity brick wall with shape +representation SweptSolid, the +IfcMaterialLayerSet.TotalThickness shall be equal to the +wall thickness. Also the OffsetFromReferenceLine shall +match the exact positions between the two shape representations +of IfcWallStandardCase, i.e. the +IfcShapeRepresentation's with +RepresentationIdentifier=""Axis"" and +RepresentationIdentifier=""Body"".
+
+NOTE ÿRefer to the implementation guide and agreements for +more information on matching between building element geometry +and material layer set usage.
+ +

The IfcMaterialLayerSetUsage is always assigned to an +individual occurrence object only (i.e. to relevant subtypes of +IfcElement). The IfcMaterialLayerSet, referenced by +ForLayerSet can however be shared among several occurrence +objects. If the element type is available (i.e. the relevant +subtype of IfcElementType, then the +IfcMaterialLayerSet can be assigned to the type object. +The assignment between aÿsubtype of IfcElement and the +IfcMaterialLayerSetUsage is handled by +IfcRelAssociatesMaterial.

+ +

Use definition

+

The IfcMaterialLayerSetUsage is primarily intended to +be associated with planar building elements having a constant +thickness. With further agreements on the interpretation of +LayerSetDirection, the usage can be extended also to other +cases, e.g. to curved building elements, provided that the +material layer thicknesses are constant.

+

Generally, an element may be layered in any of its primary +directions, denoted by its x, y or z axis. The geometry use +definitions at eachÿspecific types of building element will +determine the applicableÿLayerSetDirection.

+ +

The following examples illustrate how the IfcMaterialLayerSetUsage attributes (LayerSetDirection, DirectionSense, OffsetFromReferenceLine) can +be used in different cases. The normative material use definitions are documented at each element (how these shall be used).

+ +

Figure 286 shows an example of the use of IfcMaterialLayerSetUsage aligned to the axis of a wall.

+ +
EXAMPLE  For a standard wall with extruded +geometric representation (vertical extrusion), the layer set +direction will be perpendicular to extrusion direction, +andÿcan be derived from the direction of the wall +axis. With the DirectionSense(positive in +this example) the individual IfcMaterialLayers are +assigned consecutively right-to-left or left-to-right. For a +curved wall, ""direction denoting the wall thickness"" can be +derived from the direction of the wall axis, and it will remain +perpendicular to the wall path. The +DirectionSenseÿapplies as well.
+
+NOTE  According to the IfcWallStandardCase material use +definition the LayerSetDirection for +IfcWallStandardCase is always AXIS2 (i.e. along the +y-axis), as shown in this example.
+ + + + +

Figure 286 — Material layer set usage for wall

+ +

Figure 287 shows an example of the use of IfcMaterialLayerSetUsage aligned to a slab.

+ +
EXAMPLE ÿFor a slab with perpendicular +extruded geometric representation, the LayerSetDirection +will coincide with the extrusion direction (in positive or +negative sense). In this example, the material layer set base is +the extruded profile and consistent with the +IfcExtrudedAreaSolid.Position,ÿwith the +DirectionSensebeing positive, the +individual IfcMaterialLayers are built up from the base +towards positive z direction in this case.
+
+NOTE ÿ
According to the IfcSlabStandardCase +material use definition the LayerSetDirection for +IfcSlabStandardCase is always AXIS3 (i.e. along the +z-axis).
+ + + + +

Figure 287 — Material layer set usage for slab

+ +

Figure 288 shows an example of the use of IfcMaterialLayerSetUsage aligned to a roof slab with non-perpendicular extrusion.

+ +
EXAMPLE ÿFor a slab with non-perpendicular +extruded geometric representation, the guidelines above apply as +well. The material layer thickness and the +OffsetFromReferenceLine is always measured +perpendicularly, even if the extrusion direction is not +perpendicular. Therefore the total material layer thickness is +not equal to the extrusion depth of the +geometry.
+ + + + +

Figure 288 — Material layer set usage for roof slab

+ +
" +4286;IfcMaterialUsageDefinition;" +

IfcMaterialUsageDefinition is a general supertype for all +material related information items in IFC that have occurrence +specific assignment parameters to assign a set of materials with +shape parameters to a reference geometry item of that +component.

+

There are two ways of assigning a set of materials with shape +parameters:

+
    +
  • a layer set to a reference curve - assigning a material layer +set with material layers having a sequence and thickness +parameter to a reference curve of an element - represented by the +'Axis' shape representation of that element
  • +
  • a profile set to a cardinal point - assigning a material +profile set with assigned profile geometry and insertion points +to a reference curve by an offset, called ""cardinal point"" - the +reference curve is represented by the 'Axis' shape representation +of that element
  • +
+

Each instantiable subtype of IfcMaterialUsageDefinition +has to be assigned to a subtype of IfcElement by using the +objectified relationship IfcRelAssociatesMaterial; it is +only valid in conjunction with an element occurrence.

+ +
+HISTORYÿ New entity in IFC2x4 +
+ +

Informal proposition

+
    +
  1. It is illegal to assign a subtype of +IfcMaterialUsageDefinition to a subtype of +IfcElementType, it shall only be assigned to an element +occurrence.
  2. +
+
" +4290;IfcMaterialProfileSetUsage;" + +

IfcMaterialProfileSetUsage determines the usage of IfcMaterialProfileSet in terms of its location relative to the associated element geometry. The location of a material profile set shall be compatible with the building element geometry (that is, material profiles shall fit inside the element geometry). The rules to ensure the compatibility depend on the type of the building element. For building elements with shape representations which are based on extruded solids, this is accomplished by referring to the identical profile definition in the shape model as in the material profile set.

+ +
NOTE ÿ Refer to the implementation guide and agreements for more information on matching between building element geometry and material profile set usage.
+
NOTE ÿ The referenced IfcMaterialProfileSet may represent a single material +profile, or a composite profile with two or more material profiles.
+ +
+HISTORYÿNew Entity in IFC2x4. +
+ +
" +4295;IfcMaterialProfileSetUsageTapering;" + +

IfcMaterialProfileSetUsageTapering specifies dual material profile sets in association with tapered prismatic (beam- or column-like) elements.

+ +
+HISTORYÿ New entity in IFC 2x4 +
+ +

Usage with tapered building elements

+

The inherited attribute ForProfileSet specifies the +profile and material at the start of the member, +ForProfileEndSet at its end. Start and end correspond to +the extrusion direction in the shape model of the shape +representation of the element or element type.

+

Both material profile sets should refer to the same material, +that is, only differ with respect to their profiles.

+ +

Usage with structural analysis curve members

+

IfcMaterialProfileSetUsageTapering may be used with the +structural analysis idealization +(IfcStructuralCurveMember) of uniform members as well as +of tapered members.

+

In case of uniform members, ForProfileSet and +ForProfileEndSet refer to the same material profile set. +In case of tapered members, ForProfileSet specifies the +profile and material at the start of the member, +ForProfileEndSet at its end. Start and end correspond to +the edge direction in the topological representation of the curve +member.

+ +
" +4304;IfcMaterialList;" +

IfcMaterialList is a list of the different materials +that are used in an element.

+ +
NOTE: The class IfcMaterialList will +normally be used where an element is described at a more abstract +level. For example, for an architectural specification writer, +the only information that may be needed about a concrete column +is that it contains concrete, reinforcing steel and mild steel +ligatures. It shall not be used for elements consisting of +material layers when the different layers can be defined and the +class IfcMaterialLayerSet can be used. Also, +IfcMaterialList shall not be used for elements consisting +of a single identifiable material (for example, to represent anisotropic +material).
+ +
+IFC2x4 CHANGEÿ The entity IfcMaterialList is deprecated and shall no longer +be used. Use IfcMaterialConstituentSet instead. +
+ +
" +4367;IfcDerivedUnit;" + +

Definition from ISO/CD 10303-41:1992: A derived unit is an expression of units.

+ +
+EXAMPLE: Newton per square millimetre is a derived unit. +
+ +
+NOTE: Corresponding ISO 10303 name: derived_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 1.5.1. +
+ +
" +4374;IfcDerivedUnitElement;" + +

Definition from ISO/CD 10303-41:1992: A derived unit element is one of the unit quantities +which makes up a derived unit.

+ +
+EXAMPLE: Newtons per square millimetre is a derived unit. +It has two elements, Newton whose exponent has a value of 1 and millimetre whose exponent is -2. +
+ +
+NOTE: Corresponding ISO 10303 name: derived_unit_element, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 1.5.1. +
+ +
" +4377;IfcNamedUnit;" + +

Definition from ISO/CD 10303-41:1992: A named unit is a unit quantity associated with the word, or group of words, by which the unit is identified.

+ +
+NOTE Corresponding ISO 10303 name: named_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New type in IFC Release 1.5.1. +
+ +" +4384;IfcContextDependentUnit;" + +

Definition from ISO/CD 10303-41:1992: A context dependent unit is a unit which is not related to the SI system.

+ +
+NOTE The number of parts in an assembly is a physical quantity measured in units that may be called ""parts"" but which cannot be related to an SI unit. +
+ +
+NOTE Corresponding ISO 10303 name: context_dependent_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 1.5.1. +
+ +
" +4388;IfcConversionBasedUnit;" + +

Definition from ISO/CD 10303-41:1992: A conversion based unit is a unit that is defined based on a measure with unit.

+ +
+NOTE Corresponding ISO 10303 name: conversion_based_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 1.5.1. +
+ +
+IFC 2x3 change: standard names of typical units added. +
+ +
+IFC 2x4 change: further names added: square inch, square foot, square mile, square yard, cubic inch, cubic foot, cubic yard, fluid ounce UK/US, ton UK/US, degree. +
+ +

Example: An inch is a converted unit. It is from the Imperial system, its name is ""inch"" and it can be related to the si unit, millimetre, through a measure with unit whose value is 25.4 millimetre. A foot is also a converted unit. It is from the Imperial system, its name is ""foot"" and it can be related to an IfcSIUnit, millimetre, either directly or through the unit called ""inch"". Note that several US customary units differ from Imperial units (nonmetric English units) of the same name.

+ +

To identify some commonly used conversion based units, the standard designations (case insensitive) for the Name attribute include the following:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Name Description
'inch' Length measure equal to 25.4 mm
'foot' Length measure equal to 304.8 mm
'yard' Length measure equal to 914 mm
'mile' Length measure equal to 1609 m
'square inch' Area measure equal to 0.0006452 square meters
'square foot' Area measure equal to 0.09290 square meters
'square yard' Area measure equal to 0.83612736 square meters
'acre' Area measure equal to 4046.86 square meters
'square mile' Area measure equal to 2 588 881 square meters
'cubic inch' Volume measure equal to 0.00001639 cubic meters
'cubic foot' Volume measure equal to 0.02832 cubic meters
'cubic yard' Volume measure equal to 0.7636 cubic meters
'litre' Volume measure equal to 0.001 cubic meters
'fluid ounce UK' Volume measure equal to 0.0000284130625 cubic meters
'fluid ounce US' Volume measure equal to 0.00002957353 cubic meters
'pint UK' Volume measure equal to 0.000568 cubic meters
'pint US' Volume measure equal to 0.000473 cubic meters
'gallon UK' Volume measure equal to 0.004546 cubic meters
'gallon US' Volume measure equal to 0.003785 cubic meters
'degree' Angle measure equal to π/180 rad
'ounce' Mass measure equal to 28.35 g
'pound' Mass measure equal to 0.454 kg
'ton UK' Mass measure equal to 1016.0469088 kg, also known as long ton, gross ton, shipper's ton
'ton US' Mass measure equal to 907.18474 kg, also known as short ton, net ton
'lbf' Force measure equal to 4.4482216153 N, pound-force
'kip' Force measure equal to 4448.2216153 N, kilopound-force
'psi' Pressure measure equal to 6894.7572932 Pa, pound-force per square inch
'ksi' Pressure measure equal to 6894757.2932 Pa, kilopound-force per square inch
'minute' Time measure equal to 60 s
'hour' Time measure equal to 3600 s
'day' Time measure equal to 86400 s
'btu' Energy measure equal to 1055.056 J, British Thermal Unit
+ +
" +4393;IfcConversionBasedUnitWithOffset;" + +

IfcConversionBasedUnitWithOffset is a unit which is converted from another unit by applying a conversion factor and an offset.

+ +
+HISTORY New entity in IFC 2x4. +
+ +

Example: The temperature unit Fahrenheit is based on the temperature unit Kelvin as follows:

+ +
f = k · 1.8 – 459.67
+ +

wherein k is an absolute temperature expressed in Kelvin and f is the same temperature in Fahrenheit. The following entity instances provide Fahrenheit as a unit:

+ +
+IfcConversionBasedUnitWithOffset(
+    IfcDimensionalExponents(0, 0, 0, 0, 1, 0, 0),
+    THERMODYNAMICTEMPERATUREUNIT,
+    'Fahrenheit',
+    IfcMeasureWithUnit(
+        IfcThermodynamicTemperatureMeasure(1.8),
+        IfcSiUnit(THERMODYNAMICTEMPERATUREUNIT, ?, KELVIN)),
+    -459.67); +
+ +
" +4395;IfcMeasureWithUnit;" + +

Definition from ISO/CD 10303-41:1992: A measure with unit is the specification of a physical quantity as defined in ISO 31 (clause 2).

+ +

IfcMeasureWithUnit has two usages:
+1. For representing measure value together with its unit on the entity type attribute level; thus + overriding the IFC model global unit assignments.
+2. For conversion based unit to give the conversion rate and its base. +

+ +
+NOTE Corresponding ISO 10303 name: measure_with_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 1.5.1. +
+ +
" +4567;IfcSIUnit;" + +

Definition from ISO/CD 10303-41:1992: An SI unit is the fixed quantity used as a standard in terms of which items are measured as defined by ISO 1000 (clause 2).

+ +

IfcSIUnit covers both standard base SI units such as meter and second, and derived SI units such as Pascal, square meter and cubic meter.

+ +
+NOTE Corresponding ISO 10303 name: si_unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 1.5.1. +
+ +
" +4619;IfcDimensionalExponents;" + +

Definition from ISO/CD 10303-41:1992: The dimensionality of any quantity can be expressed as a product of powers of the dimensions of base quantities. +The dimensional exponents entity defines the powers of the dimensions of the base quantities. All the physical +quantities are founded on seven base quantities (ISO 31 (clause 2)). +

+
NOTE: Length, mass, time, electric current, thermodynamic temperature, amount of substance, +and luminous intensity are the seven base quantities. +
+ +
EXAMPLE: A length of 2 millimetres has a length exponent of 1. The remaining exponents +are equal to 0. +
+ +
EXAMPLE: A velocity of 2 millimetres per second has a length exponent of 1 and +a time exponent of -1. The remaining exponents are equal to 0. +
+ +
+ NOTE Corresponding STEP name: dimensional_exponents, please refer to ISO/IS 10303-41 + for the final definition of the formal standard. +
+ +
+ HISTORY New entity in IFC Release 1.5.1. +
+ +
" +4709;IfcMonetaryUnit;" + +

IfcMonetaryUnit is a unit to define currency for money.

+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
+IFC2x4 CHANGE: Type of the attribute Currency changed. +
+ +
" +4711;IfcUnitAssignment;" + +

IfcUnitAssignment indicates a set of units which may be assigned. Within an IfcUnitAssigment each unit definition shall be unique; that is, there shall be no redundant unit definitions for the same unit type such as length unit or area unit. For currencies, there shall be only a single IfcMonetaryUnit within an IfcUnitAssignment.

+ +
+NOTE  A project (IfcProject) has a unit assignment which establishes a set of units which will be used globally within the project, if not otherwise defined. Other objects may have local unit assignments if there is a requirement for them to make use of units which do not fall within the project unit assignment. +
+ +
+HISTORY  New entity in IFC Release 1.5.1. +
+ +
" +4719;IfcFillAreaStyleHatching;" + +

Definition from ISO/CD 10303-46:1992: The fill area style hatching defines a styled pattern of curves for hatching an annotation fill area or a surface.

+ +

The IfcFillAreaStyleHatching is used to define simple, vector-based hatching patterns, based on styled straight lines. The curve font, color and thickness is given by the HatchLineAppearance, the angle by the HatchLineAngle and the distance to the next hatch line by StartOfNextHatchLine, being either an offset distance or a vector.

+ +
+NOTE  If the hatch pattern involves two (potentially crossing) rows of hatch lines, then two instances of IfcFillAreaStyleHatching should be assigned to the IfcFillAreaStyle. Both share the same (virtual) point of origin of the hatching that is used by the reference hatch line (or the PointOfReferenceHatchLine if there is an offset). +
+ +

For better control of the hatching appearance, when using hatch lines with other fonts then continuous, the PatternStart allows to offset the start of the curve font pattern along the reference hatch line (if not given, the PatternStart is at zero distance from the virtual point of origin). If the reference hatch line does not go through the origin (of the virtual hatching coordinate system), it can be offset by using the PatternStart PointOfReferenceHatchLine.

+ +
+NOTE  The coordinates of the PatternStart and the PointOfReferenceHatchLine are given relative to the assumed 0., 0. virtual point of origin at which the hatch pattern is later positioned by the FillStyleTarget point at IfcAnnotationFillAreaOccurrence. The measure values are given in global drawing length units and apply to the target plot scale for the scale depended representation subcontext. +
+ +
+NOTE  The use of PointOfReferenceHatchLine is deprecated. +
+ +

Figure 292 illustrates hatch attributes.

+ + + + +
+ + + + + +
Example 1
+This example shows simple hatching given by using a curve font ""continuous"" at HatchLineAppearance.
+
+The distance of hatch lines is given by a positive length measure. The +angle (here 45' if measures in degree) is provided by HatchLineAngle.
+
+The PatternStart is +set to NIL ($) in this example.
Example 2
+This shows hatching from example 1 with using a different curve font at HatchLineAppearance.
+
The distance of hatch lines is given by a positive +length measure, therefore the font pattern start is at a point at the +next hatch line given by a vector being perpendicular to the point of +origin at the reference hatch line.

The +PatternStart is set to NIL ($) in this example.
Example 3
+This example uses hatching from example 2 with a vector to determine the pattern start of the next hatch lines.

+The pattern start is the beginning of the first visual curve font pattern segment at IfcCurveFont.CurveFont.

The PatternStart is set to NIL ($) in this example.
+
Example 4
+This example uses hatching from example 3 where the pattern start is offset from the point of origin at the reference hatch line. That is, the first visible curve font pattern segment now does not start at the point of origin at the reference hatch line.

+
Example 5
+This example uses hatching from example 4 where the hatch pattern is shifted against the underlying coordinate system.

+The point that is mapped to the insertion point of the IfcAnnotationFillAreaOccurrence now has an X and Y offset from the start of the reference hatch line. That is, the reference hatch line now does not go through the insertion point of the hatching.



Example 6
+This example shows use of IfcFillAreaStyleHatching attributes for two IfcFillAreaStyleHatching's within one IfcFillAreaStyle.

Note that the PatternStart now displaces both the reference hatch line from the point of origin and the start of the curve pattern. This can be used in cases when more than one IfcFillAreaStyleHatching is used in an IfcFillAreaStyle in order to place rows of hatch lines with an offset from each other.
+

Figure 292 — Fill area style hatching

+ +
+NOTE  Corresponding ISO 10303 name: fill_area_style_hatching. Please refer to ISO/IS 10303-46:1994, p. 108 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The IfcFillAreaStyleHatching has been changed by making the attributes PatternStart and PointOfReferenceHatchLine OPTIONAL. The attribute StartOfNextHatchLine has changed to a SELECT with the additional choice of IfcPositiveLengthMeasure. Upward compatibility for file based exchange is guaranteed. +
+ +
" +4728;IfcCurveStyle;" + +

Definition from ISO/CD 10303-46:1992: A curve style specifies the visual appearance of curves.

+ +

An IfcCurveStyle provides the style table for presentation information assigned to geometric curves. The style is defined by a color, a font and a width. The IfcCurveStyle defines curve patterns as model patterns, that is, the distance between visible and invisible segments of curve patterns are given in model space dimensions (that have to be scaled using the target plot scale).

+ +

Styles are intended to be shared by multiple IfcStyledItem's, assigning the style to occurrences of (subtypes of) IfcGeometricRepresentationItem's. Measures given to a font pattern or a curve width are given in global drawing length units.

+ +
+NOTE  global units are defined at the single IfcProject instance, given by UnitsInContext:IfcUnitAssignment, the same units are used for the geometric representation items and for the style definitions. +
+ +

The measure values for font pattern and curve width apply to the model space with a target plot scale provided for the correct appearance in the default plot scale.. For different scale and projection dependent curve styles a different instance of IfcCurveStyle needs to be used by IfcPresentationStyleAssignment for different IfcGeometricRepresentationSubContext dependent representations.

+ +
+NOTE  the target plot scale is given by IfcGeometricRepresentationSubContext.TargetScale. +
+ +

An IfcCurveStyle can be assigned to IfcGeometricRepresentationItem's via the IfcPresentationStyleAssignment through an intermediate IfcStyledItem or IfcAnnotationCurveOccurrence.

+ +
+NOTE  Corresponding ISO 10303 name: curve_style. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +4733;IfcPresentationStyle;" + +

IfcPresentationStyle is an abstract generalization of style table for presentation information assigned to geometric representation items. It includes styles for curves, areas, surfaces, text and symbols. Style information may include colour, hatching, rendering, and text fonts.

+ +

Each subtype of  IfcPresentationStyle can be assigned to IfcGeometricRepresentationItem's via the IfcPresentationStyleAssignment through an intermediate IfcStyledItem or one of its subtypes.

+ +
+HISTORY  New entity in IFC2x3. +
+ +
" +4740;IfcTextStyle;" + +

Definition from ISO/CD 10303-46:1992: The text style is a presentation style for annotation text.

+ +

The IfcTextStyle provides the text style table for presentation information assigned to text literals. The style is defined by color, text font characteristics, and text box characteristics. The definitions are based upon:

+
    +
  • definitions from ISO/IS 10303-46:1994 for (old) vector based and monospace text.
  • +
  • definitions from Cascading Style Sheets, level 1, W3C Recommendation 17 Dec 1996, revised 11 Jan 1999, CSS1, for all true type text. The use of the CSS1 definitions is the preferred way to represent text styles.
  • +
+ +

An IfcTextStyle, when representing (old) vector based and monospace text, is instantiated with:

+
    +
  • TextCharacterAppearance:: IfcTextStyleForDefinedFont (with BackgroundColour = NIL)
  • +
  • TextStyle:: IfcTextStyleWithBoxCharacteristics
  • +
  • TextFontStyle:: IfcDraughtingPreDefinedTextFont or IfcExternallyDefinedTextFont
  • +
+ +

An IfcTextStyle, when representing (new) true type text, based on CSS1 definitions, is instantiated with:

+
    +
  • TextCharacterAppearance:: IfcTextStyleForDefinedFont
  • +
  • TextStyle:: IfcTextStyleTextModel
  • +
  • TextFontStyle:: IfcTextStyleFontModel
  • +
+ +

An IfcTextStyle can be assigned to IfcTextLiteral via the IfcPresentationStyleAssignment through an intermediate IfcAnnotationTextOccurrence.

+ +
+NOTE  Corresponding ISO 10303 name: text_style. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. In order to avoid ANDOR subtype relationships, the IfcTextBlockStyleSelect has been introduced that allows the combination of a text style as having box characteristic, and/or having spacing, or having none of those additional properties. +
+ +
+NOTE  Corresponding CSS1 definitions are: Font properties (font-family, font-style, font-variant, font-weight, font-size), Color and background properties (color, background-color) and Text properties (word-spacing, letter-spacing, text-decoration, text-transform, text-align, text-indent, line-height). +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The IfcTextStyle has been changed by adding TextFontStyle and different data types for TextStyle and IfcCharacterStyleSelect. +
+ +
" +4746;IfcTextStyleForDefinedFont;" + +

Definition from ISO/CD 10303-46:1992: A text style for defined font is a character glyph style for pre-defined or externally defined text fonts.

+ +

Definition from CSS1 (W3C Recommendation): These properties describe the color (often called foreground color) and background of an element (i.e. the surface onto which the content is rendered). One can set a background color.

+ +
+NOTE  The CSS1 definition allows also for a background image. This has not been incorporated into IFC. +
+ +

The IfcTextStyleForDefinedFont combines the text font color with an optional background color, that fills the text box, defined by the planar extent given to the text literal.

+ +
+NOTE  Corresponding ISO 10303 name: text_style_for_defined_font. Please refer to ISO/IS +10303-46:1994, p.122 for the final definition of the formal standard. The attribute BackgroundColour +has been added. +
+ +
+NOTE  Corresponding CSS1 definitions are Color and background properties (color, background-color). +
+ +
+HISTORY  New entity in IFC2x3. +
+ +
+IFC2x3 CHANGE  The IfcTextStyleForDefinedFont has been added and replaces IfcColour at the IfcCharacterStyleSelect. +
+ +
" +4749;IfcPreDefinedCurveFont;" + +

Definition from ISO/CD 10303-46:1992: The predefined curve font type is an abstract supertype provided to define an application specific curve font. The name label shall be constrained in the application protocol to values that are given specific meaning for curve fonts in that application protocol.

+ +
+NOTE: The IfcPreDefinedCurveFont is an abstract entity, subtypes of it provide the predefined curve font by agreement of the values of the inherited Name attribute. Currently the only subtype provided is IfcDraughtingPreDefinedCurveFont. +
+ +
+NOTE: Corresponding ISO 10303 name: pre_defined_curve_font. Please refer to ISO/IS 10303-46:1994, p. 103 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +4751;IfcDraughtingPreDefinedCurveFont;" + +

The draughting predefined curve font type defines a selection of widely used curve fonts for draughting purposes by name.

+ +
+NOTE  The IfcDraughtingPreDefinedCurveFont is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46 Technical Corrigendum 2: Integrated generic resources: Visual presentation. +
+ +

Figure 291 (from ISO 10303-46 TC2) illustrates predefined curve fonts.

+ + + +

Figure 291 — Draughting predefined curve font

+ +
+NOTE  If the IfcDraughtingPreDefinedCurveFont is used within an IfcCurveStyleFontAndScaling then the segment and space lengths that are given in the table are as such for the scale factor 1.0 +
+ +
+NOTE  Corresponding ISO 10303 name: pre_defined_curve_font. Please refer to ISO/IS 10303-46:1994 TC2, page 12 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +4756;IfcTextStyleWithBoxCharacteristics;" + +

The text style with box characteristics allows the presentation of annotated text by specifying the characteristics of the character boxes of the text and the spacing between the character boxes.

+ +
+NOTE  The IfcTextStyleWithBoxCharacteristics is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
+ +

The IfcTextStyleWithBoxCharacteristics is mainly used to provide some compatibility with ISO10303. Its usage is restricted to monospace text fonts (having uniform character boxes) and simple vector based text fonts. For true text fonts however the use of IfcTextStyleTextModel is required.

+ +

Figure 296 (from ISO 10303-46, page 91) illustrates angles. Figure 297 illustrates attribute use.

+ + + + + + + + + + + + +

Figure 296 — Text style box angles

Figure 297 — Text style box attributes

+ +
+NOTE  Corresponding ISO 10303 name: text_style_with_box_characteristics. Please refer to ISO/IS 10303-46:1994, p. 123 for the final definition of the formal standard. The four optional attributes BoxHeight, BoxWidth, BoxSlantAngle, BoxRotateAngle are included directly at the entity, and are not handled through the box_characteristic_select selecting box_height, box_width, box_slant_angle, box_rotate_angle, each being defined types.  +The CharacterSpacing attribute has been added from ISO/IS 10303-46:1994 entity text_style_with_spacing. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The attribute item CharacterSpacing has been added. +
+ +
" +4769;IfcTextStyleTextModel;" + +

Definition from CSS1 (W3C Recommendation): The properties defined in the text model affect the visual presentation of characters, spaces, words, and paragraphs.

+ +

The IfcTextStyleTextModel combines all text style properties, that affect the presentation of a text literal within a given extent. It includes the spacing between characters and words, the horizontal and vertical alignment of the text within the planar box of the extent, decorations (like underline), transformations of the literal (like uppercase), and the height of each text line within a multi-line text block.

+ +
+NOTE  Corresponding CSS1 definitions are Text properties (word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, text-align, text-indent, line-height). +
+ +
+HISTORY  New entity in IFC2x3. +
+ +
" +4783;IfcFillAreaStyle;" + +

Definition from ISO/CD 10303-46:1992: The style for filling visible curve segments, annotation fill areas or surfaces with tiles or hatches.

+ +

An IfcFillAreaStyle provides the style table for presentation information assigned to annotation fill areas or surfaces for hatching and tiling. The IfcFillAreaStyle defines hatches as model hatches, that is, the distance between hatch lines, or the curve patterns of hatch lines are given in model space dimensions (that have to be scaled using the target plot scale). The IfcFillAreaStyle allows for the following combinations of defining the style of hatching and tiling:

+ +
    +
  • Solid fill for areas and surfaces by only assigning IfcColour to the set of FillStyles. It then provides the background colour for the filled area or surface.
  • +
+ +
NOTE  Color information of surfaces for rendering is assigned by using IfcSurfaceStyle, not by using IfcFillAreaStyle.
+ +
    +
  • Vector based hatching for areas and surfaces based on a single row of hatch lines by assigning a single instance of IfcFillAreaStyleHatching to the set of FillStyles.
    • If an instance of IfcColour is assigned in addition to the set of FillStyles, it provides the background colour for the hatching.
  • Vector based hatching for areas and surfaces based on two (potentially crossing) rows of hatch lines by assigning two instances of IfcFillAreaStyleHatching to the set of FillStyles.
  • + +
    • If an instance of IfcColour is assigned in addition to the set of FillStyles, it provides the background colour for the hatching.
    +
+ +
+NOTE  Assigning more then two instances of IfcFillAreaStyleHatching to define three or more rows of hatch lines is not encouraged. +
+ +
    +
  • Tiling for areas and surfaces by assigning a single instance of IfcFillAreaStyleTiles to the set of FillStyles.
    • If an instance of IfcColour is assigned in addition to the set of FillStyles, it provides the background colour for the tiling.
    +
+ +
+IFC2x3 NOTE  The use of IfcFillAreaStyleTiles is discouraged., as its definition might change is future releases. +
+ +
    +
  • Externally defined hatch style by assigning a single instance of IfcExternallyDefinedHatchStyle to the set of FillStyles. +
    • If an instance of IfcColour is assigned in addition to the set of FillStyles, it provides the background colour for the hatching.
    +
  • +
+ +

Measures given to a hatch or tile pattern are given in global drawing length units.

+ +
+NOTE  Global units are defined at the single IfcProject instance, given by UnitsInContext:IfcUnitAssignment, the same units are used for the geometric representation items and for the style definitions. +
+ +

The measure values for hatch or tile pattern apply to the model space with a target plot scale provided for the correct appearance in the default plot scale. For different scale and projection dependent fill area styles a different instance of IfcFillAreaStyle needs to be used by IfcPresentationStyleAssignment for different IfcGeometricRepresentationSubContext dependent representations.

+ +
+NOTE  the target plot scale is given by IfcGeometricRepresentationSubContext.TargetScale. +
+ +

An IfcFillAreaStyle can be assigned to IfcFillArea via the IfcPresentationStyleAssignment through an intermediate IfcStyledItem or subtype IfcAnnotationFillAreaOccurrence.

+ +
+NOTE  Corresponding ISO 10303 name: fill_area_style. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +4793;IfcFillAreaStyleTiles;" + +

Definition from ISO/CD 10303-46:1992: The fill area style tiles defines a two dimensional tile to be used for the filling of annotation fill areas or other closed regions. The content of a tile is defined by the tile set, and the placement of each tile determined by the filling pattern which indicates how to place tiles next to each other. Tiles or parts of tiles outside of the annotation fill area or closed region shall be clipped at the of the area or region.

+ +
+NOTE Corresponding ISO 10303 name: fill_area_style_tiles. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4797;IfcOneDirectionRepeatFactor;" + +

Definition from ISO/CD 10303-46:1992: A one time repeat factor is a vector used in the fill area style hatching and fill area style tiles entities for determining the origin of the repeated hatch line relative to the origin of the previous hatch line, Given the initial position of any hatch line, the one direction repeat factor determines two new positions according to the equation:

+ +
+

I + k * R    k X{-1,1}

+
+ +
+NOTE: Corresponding ISO 10303 name: one_direction_repeat_factor. Please refer to ISO/IS 10303-46:1994, p. 112 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +4800;IfcTwoDirectionRepeatFactor;" + +

Definition from ISO/CD 10303-46:1992: A two direction repeat factor combines two vectors which are used in the fill area style tiles entity for determining the shape and relative location of tiles. Given the initial position of any tile, the two direction repeat factor determines eight new positions according to the equation:

+ +
+

k1* R1 + k2* R2 +      k X{-1,1} 

+
+ +
+NOTE Corresponding ISO 10303 name: two_direction_repeat_factor. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4804;IfcFillAreaStyleTileSymbolWithStyle;" + +

The fill area style tile symbol with style is a symbol that is used as a tile within an annotated tiling.

+ +
+NOTE: The IfcFillAreaStyleTileSymbolWithStyle is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
+ +
+NOTE: Corresponding ISO 10303 name: fill_area_style_tile_symbol_with_style. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +4806;IfcStyledItem;" + +

Definition from ISO/CD 10303-46:1992: The styled item is an assignment of style for presentation to a geometric representation item as it is used in a representation.

+ +
+NOTE  Corresponding ISO 10303 name: styled_item. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +

The IfcStyledItem holds presentation style information for products, either explicitly for an IfcGeometricRepresentationItem being part of an IfcShapeRepresentation assigned to a product, or by assigning presentation information to IfcMaterial being assigned as other representation for a product.

+
    +
  • If the IfcStyledItem is used within a reference from an IfcProductDefinitionShape then one Item shall be provided.
  • +
  • If the IfcStyledItem is used within a reference from an IfcMaterialDefinitionRepresentation then no Item shall be provided.
  • +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x2 Addendum 1 CHANGE  The entity IfcStyledItem has been made non abstract and the attribute Name added. +
+ +
+IFC2x3 CHANGE The attribute Item has been made optional, upward compatibility for file +based exchange is guaranteed. +
+ +
+IFC2x4 CHANGE The subtype IfcAnnotationOccurrence and its subtypes are deleted. Use IfcStyledItem for all instantiations. The data type of Styles has been changed to IfcStyleAssignmentSelect +
+ +

Use Definition

+ +

Figure 293 illustrates use of IfcStyledItem for the two usage examples:

+
    +
  • As a presentation for a geometric representation item
  • +
  • As a presentation for a material definition
  • +
+
NOTE  The new IfcStyleAssignmentSelect allows the direct assignment styles, such as IfcCurveStyle, IfcSurfaceStyle without using the intermediate IfcPresentationStyleAssignment
+ + + + +

Figure 293 — Styled item

+ +
" +4814;IfcPresentationStyleAssignment;" + +

Definition from ISO/CD 10303-46:1992: The presentation style assignment is a set of styles which are assigned to styled items for the purpose of presenting these styled items.

+ +
+NOTE Corresponding ISO 10303 name: presentation_style_assignment. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in Release IFC2x2. +
+ +
" +4825;IfcSymbolStyle;" + +

Definition from ISO/CD 10303-46:1992: The symbol style is the presentation style that indicates the presentation of annotation symbols.

+ +
+NOTE: Corresponding ISO 10303 name: symbol_style. Please refer to ISO/IS 10303-46:1994, p. 124 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in Release IFC2x2. +
+ +
" +4829;IfcSurfaceStyle;" + +

IfcSurfaceStyle is an assignment of one or many surface style elements to a surface, defined by subtypes of IfcSurface, IfcFaceBasedSurfaceModel, IfcShellBasedSurfaceModel, or by subtypes of IfcSolidModel. The positive direction of the surface normal relates to the positive side. In case of solids the outside of the solid is to be taken as positive side.

+ +
+NOTE: The surface style is often referred to as material definition in rendering applications. +
+ +
+NOTE Corresponding ISO 10303 entity: surface_style_usage and surface_side_style. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. The surface style definition in regard to support of rendering has been greatly expanded beyond the scope of ISO/IS 10303-46. +
+ +
+HISTORY New Entity in IFC 2.x. +
+ +
" +4847;IfcSurfaceStyleShading;" + +

Definition from ISO/CD 10303-46:1992: The surface style rendering allows the realistic visualization of surfaces referring to rendering techniques based on the laws of physics and mathematics.

+ +

The entity IfcSurfaceStyleShading allows for colour information used for shading, whereas subtypes provide data for more sophisticated rendering techniques. The surface colour is used for colouring or simple shading of the assigned surfaces.

+ +
+NOTE Corresponding ISO 10303 entity: surface_style_rendering. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. No rendering method is defined for each surface style (such as constant, colour, dot or normal shading), therefore the attribute rendering_method has been omitted. +
+ +
+HISTORY: New entity in IFC 2x. +
+ +
" +4850;IfcSurfaceStyleRendering;" + +

IfcSurfaceStyleRendering holds the properties for visualization related to a particular surface side style.

+ +

It allows rendering properties to be defined by:

+
    +
  • a transparency component (Transparency attribute)
  • +
  • a colour component (SurfaceColour attribute inherited from IfcSurfaceStyleShading)
  • +
  • a reflectance component, given either by +
      +
    • applying reflectance factors to the surface colour: +
        +
      • diffuse component (SurfaceColour * DiffuseFactor)
      • +
      • transmission component (SurfaceColour * TransmissionFactor)
      • +
      • diffuse transmission component (SurfaceColour * DiffuseTransmissionFactor)
      • +
      • reflection component (SurfaceColour * ReflectionFactor)
      • +
      • specular component (SurfaceColour * SpecularFactor attribute together with SpecularHighlight)
      • +
    • +
    • explicitly defining such factors as colours (DiffuseColour, TransmissionColour, DiffuseTransmissionColour, ReflectionColour and SpecularColour)
    • +
  • +
  • a displacement component, currently only given by a texture map with the TextureType = bump
  • +
  • a coverage component, currently only given by the alpha component of the texture map (2 or 4 component colour texture)
  • +
+ +
+NOTE: The inherited attribute SurfaceColour is treated as the ambient colour and specifies how much ambient light from light sources this surface shall reflect. Ambient light is omnidirectional and depends only on the number of light sources, not their positions with respect to the surface. +
+ +
+NOTE: If the reflectance method, as given by the IfcReflectanceMethodEnum is ""GLASS"", the transmission factor controls the level of transparency in the glass, In this case the transparency factor is interpreted as transmission factor. +
+ +
+NOTE: Both Transparency and TransmissionColour (or factor) are included, the following definitions apply: +
    +
  • Transparency is the ratio of the transmitted flux in a solid angle of 2 * PI sr (one hemisphere). It is a simple colour filtration that does not account for refraction.
  • +
  • Transmission factor of a material is the ratio of transmitted flux in a given solid angle to the transmitted flux of a completely diffuse material with 100% transmission in the same solid angle. It is the portion of light that goes through the material and may be refracted.
  • +
+
+ +
+NOTE: IFC 2x2 adds additional capability for presentation of physically accurate illuminance on surfaces. VRML type rendering and rendering based on ISO 10303-46 continues to be supported by a subset of the information. For reflectance equations and further information about the surface style properties and its processing, see: +
    +
  • ISO/IEC 14772-1: 1997: The Virtual Reality Modeling Language
  • +
+
+ +
+NOTE: The definition of IfcSurfaceStyleRenderingProperties includes the definitions as found in ISO 10303-46:1994, in particular of: +
    +
  • surface_style_rendering_with_properties
  • +
  • surface_style_rendering_ambient
  • +
  • surface_style_rendering_ambient_diffuse
  • +
  • surface_style_rendering_ambient_diffuse_specular
  • +
  • surface_style_transparent
  • +
+
+ +
In addition to the attributes as defined in ISO 10303-46, (ambient_reflectance, diffuse_reflectance, specular_reflectance, specular_exponent, and specular_colour), the current IFC definition adds other colours, reflectance factors and specular roughness. +
+ +
+HISTORY: New Entity in IFC 2x. +
+ +
" +4879;IfcSurfaceStyleLighting;" + +

IfcSurfaceStyleLighting is a container class for properties for calculation of physically exact illuminance related to a particular surface style.

+ +

Figure 294 shows the reflection and transmission components from an incident ray. The sum of the components for reflection and transmission is a value of 1.0 denoting that the incident ray is completely decomposed into reflection and transmission components. Each value of reflection and transmission is therefore within the range 0.0 to 1.0.

+ + + + +

Figure 294 — Surface style lighting

+ +

All these factors can be measured physically and are ratios for the red, green and blue part of the light. These properties are defined in the model as Type IfcColorRGB with a factor for each colour.

+ +
+EXAMPLE  A green glass transmits only green light, so its transmission factor is 0.0 for red, between 0.0 and 1.0 for green and 0.0 for blue. A green surface reflects only green light, so the reflectance factor is 0.0 for red, between 0.0 and 1.0 for green and 0.0 for blue. +
+ +
+HISTORY  New entity in IFC 2x2. +
+ +
" +4884;IfcSurfaceStyleWithTextures;" + +

The entity IfcSurfaceStyleWithTextures allows to include image textures in surface styles. These image textures can be applied repeating across the surface or mapped with a particular scale upon the surface.

+ +

The entity IfcSurfaceStyleWithTextures is part of the surface style table for presentation information assigned to surfaces for shading, rendering and lighting with textures. The mapping of the texture onto the surface or the solid is determined by the texture coordinates, in absense of an IfcTextureCoordinate assigned to each surface texture, a default mapping of the texture to the geometric face or surface applies.

+ +

Surface textures included in the IfcSurfaceStyleWithTextures are two dimensional map formats. They define 2D images that contain an array of colour values describing the texture. Depending on the number of IfcSurfaceTextures being included in the list of Textures the IfcSurfaceStyleWithTextures either describes a single texture, or a multi texture.

+
    +
  • single texture: a single surface texture is applied to the styled geometric item (entirely or partly) with optional repetition and texture transformation
  • +
  • multi texture: two or more surface textures are applied to the styled geometric item (entirely or partly) with optional repetition, texture transformation or texture coordinate mapping being specific for each texture.
  • +
+

Informal proposition

+
    +
  1. Only one instance of IfcSurfaceStyleWithTextures shall be referenced by an IfcStyledItem and be assigned to an IfcGeometricRepresentationItem
  2. +
+ +
+NOTE  The definitions of texturing within this standard have been developed in dependence on the texture component of X3D. See ISO/IEC 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1, 18 Texturing component for the definitions in the international standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  inverse attribute HasTextureCoordinates deleted. +
+ +
" +4886;IfcSurfaceTexture;" + +

An IfcSurfaceTexture provides a 2-dimensional +image-based texture map. It can either be given by referencing an +external image file through an URL reference +(IfcImageTexture), including the image file as a blob +(long binary) into the data set (IfcBlobTexture), or by +explicitly including an array of pixels +(IfcPixelTexture).

+

The following definitions from ISO/IEC 19775-1 X3D Architecture +and base components (X3D Specification) +apply:

+
    +
  • Texture: An image +used in a texture map to create visual appearance effects when +applied to geometry nodes.
  • +
  • Texture map: A +texture plus the general parameters necessary for mapping the +texture to geometry.
  • +
+

Texture are defined by 2D images that contain an array of colour +values describing the texture. The texture values are interpreted +differently depending on the number of components in the texture +and the specifics of the image format. In general, texture may be +described using one of the following forms:

+
    +
  1. Intensity textures (one-component)
  2. +
  3. Intensity plus alpha opacity textures (two-component)
  4. +
  5. Full RGB textures (three-component)
  6. +
  7. Full RGB plus alpha opacity textures (four-component)
  8. +
+
+

NOTE  Image formats specify an alpha opacity, not transparency (where alpha = 1 - transparency).

+
+ +

Figure 295 illustrates the texture coordinate system.

+ + + + +

Figure 295 — Surface texture coordinates

+ +

The following definitions from ISO/IEC 19775-1 X3D Architecture and base components (X3D Specification) on texture coordinates apply:

+
    +
  • Texture maps are defined in a 2D coordinate system (s, t) that ranges from [0.0, 1.0] in both directions. The bottom edge of the image corresponds to the S-axis of the texture map, and left edge of the image corresponds to the T-axis of the texture map. The lower-left pixel of the image corresponds to s=0, t=0, and the top-right pixel of the image corresponds to s=1, t=1. Texture maps may be viewed as two dimensional colour functions that, given an (s, t) coordinate, return a colour value colour(s, t).
  • +
+ +

If multiple surface textures are included in the +IfcSurfaceStyleWithTextures applying them to a geometric +item, a mode and optional parameters can be included that blending +operations.

+

The RepeatS and RepeatT Boolean flags control +whether the texture map is repeated outside the [0.0, 1.0] texture +coordinate range, when applied to a geometric surface, or clamped +to lie within the [0.0, 1.0] range. The TextureTransform +applies a 2D non-uniform transformation to the texture before it is +applied to a geometric surface.

+

The following definitions from ISO/IEC 19775-1 X3D Architecture +and base components (X3D Specification) +apply:

+
    +
  • These parameters +support changes to the size, orientation, and position of textures +on shapes. Note that these operations appear reversed when viewed +on the surface of geometry. For example, a scale value of (2 +2) will scale the texture coordinates and have the net effect of +shrinking the texture size by a factor of 2 (texture coordinates +are twice as large and thus cause the texture to repeat). A +translation of (0.5 0.0) translates the texture coordinates +.5 +units along the S-axis and has the net effect of translating the +texture −0.5 along the S-axis on the geometry's surface. A +rotation of π/2 of the texture coordinates results in a +−π/2 rotation of the texture on the geometry.
  • +
  • The center +field specifies a translation offset in texture coordinate space +about which the rotation and scale fields are +applied. The scale field specifies a scaling factor in S and +T of the texture coordinates about the center point. +scale values shall be in the range (−∞,∞). +The rotation field specifies a rotation in radians of the +texture coordinates about the center point after the scale +has been applied. A positive rotation value makes the texture +coordinates rotate counterclockwise about the centre, thereby +rotating the appearance of the texture itself clockwise. The +translation field specifies a translation of the texture +coordinates.
    +The following conventions +apply: +
      +
    • center = +TextureTransform.LocalOrigin;
      +rotation = TextureTransform.Axis1
      +scale S = TextureTransform.Scale
      +scale T = TextureTransform.Scale2
    • +
    +
  • +
+ +
+NOTE  The definitions of texturing within this standard have been developed in dependence on the texture component of X3D. See ISO/IEC 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1, 18 Texturing component for the definitions in the international standard. +
+ +
+HISTORY  New entity in IFC 2x2. +
+ +
+IFC2x4 CHANGE  Attribute TextureType replaces by Mode, attributes Parameter and MapsTo aded, new inverse attribute UsedInStyle. +
+ +
" +4897;IfcPixelTexture;" + +

An IfcPixelTexture provides a 2D image-based texture map as an explicit array of pixel values (list of Pixel binary attributes). In contrary to the IfcImageTexture the IfcPixelTexture holds a 2 dimensional list of pixel color +(and opacity) directly, instead of referencing to an URL.

+ +

The following definitions from ISO/IEC 19775-1 X3D Architecture and base components (X3D Specification) apply:

+
    +
  • The PixelTexture node defines a 2D image-based texture map as an explicit array of pixel values (image field) and parameters controlling tiling repetition of the texture onto geometry.
  • +
  • Texture maps are defined in a 2D coordinate system (s, t) that ranges from 0.0 to 1.0 in both directions. The bottom edge of the pixel image corresponds to the S-axis of the texture map, and left edge of the pixel image corresponds to the T-axis of the texture map. The lower-left pixel of the pixel image corresponds to s=0.0, t=0.0, and the top-right pixel of the image corresponds to s = 1.0, t = 1.0.
  • +
  • The Image field specifies a single uncompressed 2-dimensional pixel image. Image fields contain three integers representing the width, height and number of components in the image, followed by width×height hexadecimal values representing the pixels in the image. Pixel values are limited to 256 levels of intensity (that is, 0x00-0xFF hexadecimal). +
      +
    1. A one-component image specifies one-byte hexadecimal value representing the intensity of the image. For example, 0xFF is full intensity in hexadecimal (255 in decimal), 0x00 is no intensity (0 in decimal).
    2. +
    3. A two-component image specifies the intensity in the first +(high) byte and the alpha opacity in the second (low) byte.
    4. +
    5. Pixels in a three-component image specify the red component in the first (high) byte, followed by the green and blue components (for example, 0xFF0000 is red, 0x00FF00 is green, 0x0000FF is blue).
    6. +
    7. Four-component images specify the alpha opacity byte after red/green/blue (e.g., 0x0000FF80 is semi-transparent blue). A value of 00 is completely transparent, FF is completely opaque, 80 is semi-transparent.
    8. +
    +
  • +
  • Note that alpha equals (1.0 -transparency), if alpha and transparency each range from 0.0 to 1.0.
  • +
+ +
+HISTORY: New class in IFC2x2. +
+ +
" +4907;IfcImageTexture;" + +

An IfcImageTexture provides a 2-dimensional texture that can be applied to a surface of an geometric item and that provides lighting parameters of a surface onto which it is mapped. The texture is provided as an image file at an external location for which an URL is provided.

+ +

The following definitions from ISO/IEC 19775-1 X3D Architecture and base components (X3D Specification) apply:

+
    +
  • The ImageTexture node defines a texture map by specifying an image file and general parameters for mapping to geometry.
  • +
  • The texture is read from the URL specified by the url field. When the url field contains no [resolvable] values, texturing is disabled. Browsers shall support the JPEG and PNG (see ISO/IEC 15948) image file formats.
  • +
  • Texture nodes that require support for the PNG image format shall interpret the PNG pixel formats in the following way: +
      +
    1. Greyscale pixels without alpha or simple transparency are treated as intensity textures.
    2. +
    3. >Greyscale pixels with alpha or simple transparency are treated as intensity plus alpha textures.
    4. +
    5. RGB pixels without alpha channel or simple transparency are treated as full RGB textures.
    6. +
    7. RGB pixels with alpha channel or simple transparency are treated as full RGB plus alpha textures.
    8. +
    +
  • +
  • If the image specifies colours as indexed-colour (that is, palettes or colourmaps), the following semantics should be used (note that `greyscale' refers to a palette entry with equal red, green, and blue values): +
      +
    1. If all the colours in the palette are greyscale and there is no transparency chunk, it is treated as an intensity texture.
    2. +
    3. If all the colours in the palette are greyscale and there is a transparency chunk, it is treated as an intensity plus opacity texture.
    4. +
    5. >If any colour in the palette is not grey and there is no transparency chunk, it is treated as a full RGB texture.
    6. +
    7. If any colour in the palette is not grey and there is a transparency chunk, it is treated as a full RGB plus alpha texture.
    8. +
    +
  • +
  • Texture nodes that require support for JPEG files shall interpret JPEG files as follows: +
      +
    1. Greyscale files (number of components equals 1) are treated as intensity textures.
    2. +
    3. YCbCr files are treated as full RGB textures.
    4. +
    5. No other JPEG file types are required. It is recommended that other JPEG files are treated as a full RGB textures.
    6. +
    +
  • +
  • Texture nodes that recommend support for GIF files shall follow the applicable semantics described above for the PNG format.
  • +
+ +

The Uniform Resource Locator (URL) is a form of an URI and specified in RFC1738 by IETF. It supports resources located on a particular server being accessed by a particular protocol (usually http), and resources located at a local machine.

+ +
+NOTE  Exchange files following the ifcZIP convention may include a sub directory structure for image resources to be stored together with the product data set. +
+ +
+

NOTE  The definitions of texturing within this standard have been developed in dependence on the texture component of X3D. See ISO/IEC 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1, 18 Texturing component for the definitions in the international standard. +

+ +
+HISTORY  New entity in Release IFC2x2. +
+ +
" +4909;IfcExternallyDefinedSurfaceStyle;" + +

IfcExternallyDefinedSurfaceStyle is a definition of a surface style through referencing an external source, such as a material library for rendering information.

+ +
+NOTE  In order to achieve expected results, the externally defined surface style should normally only be given in addition to an explicitly defined surface styles. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The spelling has been corrected from IfcExternallyDefinedSufaceStyle with no upward compatibility. +
+ +
" +4910;IfcExternallyDefinedHatchStyle;" + +

Definition from ISO/CD 10303-46:1992: The externally defined hatch style is an entity which makes an external reference to a hatching style.

+ +
+NOTE: The allowable values for the name source and item reference, by which the externally defined hatch style is identified, need to be determined by implementer agreements. +
+ +
+NOTE: Corresponding ISO 10303 name: fill_style_select. Please refer to ISO/IS 10303-46:1994 for +the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +4911;IfcBlobTexture;" + +

An IfcBlobTexture provides a 2-dimensional distribution of the lighting parameters of a surface onto which it is mapped. The texture itself is given as a single binary blob, representing the content of a pixel format file. The file format of the pixel file is given by the RasterFormat attribute and allowable formats are guided by where rule SupportedRasterFormat.

+ +
+NOTE  Toolbox specific implementations of the binary datatype may restrict the maximum length of the binary blob to capture the raster file content. +
+ +

For interpretation of the texture nodes see IfcImageTexture definition.

+ +
+HISTORY  New class in IFC2x3. +
+ +
+IFC2x4 CHANGE  Data type of RasterCode has been corrected to BINARY. +
+ +
" +4916;IfcSurfaceStyleRefraction;" + +

IfcSurfaceStyleRefraction extends the surface style lighting, or the surface style rendering definition for properties for calculation of physically exact illuminance by adding seldomly used properties. Currently this includes the refraction index (by which the light ray refracts when passing through a prism) and the dispersion factor (or Abbe constant) which takes into account the wavelength dependency of the refraction.

+ +
+NOTE: If such refraction properties are used, the IfcSurfaceStyle should include within its set of Styles (depending on whether rendering or lighting is used) an instance of IfcSurfaceStyleLighting and IfcSurfaceStyleRefraction, or an instance of IfcSurfaceStyleRendering and IfcSurfaceStyleRefraction. +
+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4925;IfcCurveStyleFont;" + +

Definition from ISO/CD 10303-46:1992: A curve style font combines several curve style font pattern entities into a more complex pattern. The resulting pattern is repeated along the curve.

+ +
+NOTE: Corresponding ISO 10303 name: curve_style_font. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +4928;IfcCurveStyleFontPattern;" + +

Definition from ISO/CD 10303-46:1992: A curve style font pattern is a pair of visible and invisible curve segment length measures in presentation area units.

+ +
+NOTE Corresponding ISO 10303 name: curve_style_font_pattern. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4932;IfcCurveStyleFontAndScaling;" + +

Definition from ISO/CD 10303-46:1992: A curve style font and scaling is a curve style font and a scalar factor for that font, so that a given curve style font may be applied at various scales.

+ +

The IfcCurveStyleFontAndScaling allows for the reuse of the same curve style definition in several sizes. The definition of the CurveFontScale is the scaling of a base curve style pattern to be used as a new or derived curve style pattern.

+ +
+NOTE  The CurveFontScale should not be mixed up with the target plot scale. +
+ +

An example for IfcCurveStyleFontAndScaling is the sizing of a basic curve style dash pattern 'dash' (visible 0.01m, invisible 0.005m) into 'dash large' with CurveFontScale = 2 (resulting in visible 0.02m, invisible 0.01m), and into 'dash small' with CurveFontScale = 0.5 (resulting in visible 0.005m, invisible 0.0025m).

+ +
+NOTE  Corresponding ISO 10303 name: curve_style_font_and_scaling. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
" +4941;IfcTextLiteral;" + +

The text literal is a geometric representation item which describes a text string using a string literal and additional position and path information.

+ +
+NOTE  The IfcTextLiteral is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange. +
+ +
+NOTE  Corresponding ISO 10303 name: text_literal. Please refer to ISO/IS 10303-46:1994 for the +final definition of the formal standard. The attributes font and alignment have been removed as those should be handled by the text style. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The IfcTextLiteral has been changed by removing Font and Alignment. +
+ +
" +4946;IfcAnnotationFillArea;" + +

Definition from ISO/CD 10303-46:1992: An annotation fill area is a set of curves that may be filled with hatching, colour or tiling. The annotation fill are is described by boundaries which consist of non-intersecting, non-self-intersecting closed curves. These curves form the boundary of planar areas to be filled according to the style for the annotation fill area.

+ +
+NOTE: A curve that is not surrounded by any other curve is a border between an unfilled area on the outside and a filled area on the inside. Another curve may surround an unfilled area if it is surrounded by another curve whose inside is a filled area. +
+ +

Figure 300 (from ISO 10303-46) illustrates annotation fill area.

+ + + +

Figure 300 — Annotation fill area

+ +
+NOTE  Corresponding ISO 10303 name: annotation_fill_area. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +

The IfcAnnotationFillArea defines an area by a definite OuterBoundary, that might include InnerBoundaries. The areas defined by the InnerBoundaries are excluded from applying the fill area style.

+ +

Informal Proposition:

+
    +
  1. Any curve that describes an inner boundary shall not intersect with, nor include, another curve defining an inner boundary.
  2. +
  3. The curve defining the outer boundary shall not intersect with any curve defining an inner boundary, nor shall it be surrounded by a curve defining an inner boundary.
  4. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The two attributes OuterBoundary and InnerBoundaries are added and replace the previous single boundary. +
+ +
" +4949;IfcDefinedSymbol;" + +

A defined symbol is a symbolic representation that gets its shape information by an established convention, either through a predefined symbol, or an externally defined symbol.

+ +
+NOTE: The IfcDefinedSymbol is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
+ +
+NOTE Corresponding ISO 10303 name: defined_symbol. The target attribute used the 2d Cartesian transformation operator, including the non-uniform subtype, which is available in IFC (instead of the symbol_target). Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4955;IfcPreDefinedSymbol;" + +

A predefined symbol is a symbol that gets its shape information by a conforming name that is specified within subtypes of the entity.

+ +
+NOTE: The IfcPreDefinedSymbol is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
+ +
+NOTE Corresponding ISO 10303 name: pre_defined_symbol. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4956;IfcExternallyDefinedSymbol;" + +

An externally defined symbol is a symbol that gets its shape information by an agreed reference to an external source.

+ +
+NOTE: The allowable symbol names and sources have to be established by implementers agreements.
+ +
+NOTE: The IfcExternallyDefinedSymbol is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
+ +
+NOTE Corresponding ISO 10303 name: externally_defined_symbol. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
" +4957;IfcTextureCoordinate;" + +

The IfcTextureCoordinate a an abstract supertype of the different kinds to apply texture coordinates to geometries. For vertex based geometries an explicit assignment of 2D texture vertices to the 3D geometry points is supported by the subtype IfcTextureMap, in addition there can be a procedural description of how texture coordinates shall be applied to geometric items. If no IfcTextureCoordinate is provided for the IfcSurfaceTexture, the default mapping shall be used.

+ +
+

See relevant subtypes of IfcGeometricRepresentationItem for default texture mapping description.

+
+ +
+NOTE  The definitions of texturing within this standard have been developed in dependence on the texture component of X3D. See ISO/IEC 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1, 18 Texturing component for the definitions in the international standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The attribute Texture is deleted. +
+ +
+IFC2x4 CHANGE  The inverse attribute AnnotatedSurface is deleted, and the inverse AppliesTextures is added. +
+ +
" +4961;IfcTextureCoordinateGenerator;" + +

The IfcTextureCoordinateGenerator describes a procedurally defined mapping function with input parameter to map 2D texture coordinates to 3D geometry vertices. The allowable Mode values and input Parameter need to be agreed upon in view definitions and implementer agreements.

+ +
+

It is recommended to use the texture coordinate generation modes as defined in X3D.

+
+ +

The following definitions from ISO/IEC 19775-1 X3D Architecture and base components (X3D Specification) apply:

+
    +
  • The TextureCoordinateGenerator supports the automatic generation of texture coordinates for geometric shapes.
  • +
  • The mode field describes the algorithm used to compute texture coordinates. +
      +
    • SPHERE,
    • +
    • CAMERASPACENORMAL,
    • +
    • CAMERASPACEPOSITION,
    • +
    • CAMERASPACEREFLECTIONVECTOR,
    • +
    • SPHERE-LOCAL,
    • +
    • COORD,
    • +
    • COORD-EYE,
    • +
    • NOISE,
    • +
    • NOISE-EYE,
    • +
    • SPHERE-REFLECT,
    • +
    • SPHERE-REFLECT-LOCAL
    • +
    +
  • +
+ +
+NOTE  The definitions of texturing within this standard have been developed in dependence on the texture component of X3D. See ISO/IEC 19775-1.2:2008 X3D Architecture and base components Edition 2, Part 1, 18 Texturing component for the definitions in the international standard. +
+ +
+HISTORY New entity in IFC2x2. +
+ +
+IFC2x2 Addendum 2 CHANGE  The attribute Texturehas been deleted. +
+ +
" +4964;IfcTextureMap;" + +

An IfcTextureMap provides the mapping of the +2-dimensional texture coordinates to the surface onto which it is +mapped. It is used for mapping the texture to surfaces of vertex +based geometry models, such as

+
    +
  • IfcFacetedBrep
  • +
  • IfcFacetedBrepWithVoids
  • +
  • IfcFaceBasedSurfaceModel
  • +
  • IfcShellBasedSurfaceModel
  • +
+

The IfcTextureMap has a list of TextureVertex, +that corresponds to the points of the face bound of the vertex +based geometry item. The corresponding pair of lists is:

+
    +
  1. the list of Polygon of type IfcCartesianPoint, +and
  2. +
  3. the list of Vertices of type +IfcTextureVertex.
  4. +
+

Each IfcTextureVertex (given as S, T coordinates of the +2-dimension texture coordinate system) corresponds to the geometric +coordinates of the IfcCartesianPoint (given as 3-dimension +X, Y, and Z coordinates within the object coordinate system of the +geometric item).

+

The following definitions from ISO/IEC 19775-1 X3D Architecture +and base components (X3D Specification) +apply:

+
    +
  • The TextureCoordinate node is a geometry property node that +specifies a set of 2D texture coordinates used by vertex-based +geometry nodes to map textures to vertices.
  • +
+
+

NOTE  In contrary to the +X3D vertext based geometry, for example IndexedFaceSet and +ElevationGrid, the vertext based geometry in IFC may include inner +loops. The areas of inner loops have to be cut-out from the texture +applied to the outer loop.

+
+ +

Figure 301 illustrates applying a texture map to a vertex based geometry.

+ + + + +

Figure 301 — Texture map

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The attribute Texture is deleted, and the attribute TextureMaps is added. +
+ +
+IFC2x4 CHANGE  The attribute TextureMap is replaced by Vertices, and the attribute AppliedTo is added. +
+ +

Informal propositions:

+
    +
  1. The FaceBound referenced in AppliedTo shall be used by the vertex based geometry, to which this texture map is assigned to by through the IfcStyledItem.
  2. +
+ +
" +4967;IfcTextureVertex;" + +

An IfcTextureVertex is a list of 2 (S, T) texture coordinates.

+ +

The following additional definitions from ISO 19775 apply:

+ +
+

Each vertex-based geometry node uses a set of 2D texture +coordinates that map textures to vertices. Texture map values ( +ImageTexture, PixelTexture) range from [0.0, 1.0] along the S-axis and +T-axis. However, texture coordinate values may be in the range +(-∞,∞). Texture coordinates identify a location +(and thus a +colour value) in the texture map. The horizontal coordinate S is +specified first, followed by the vertical coordinate T. If the texture +map is repeated in a given direction (S-axis or T-axis), a texture +coordinate C (s or t) is mapped into a texture map that has N pixels in +the given direction as follows:

+
+
Texture map location = (C - floor(C)) × N
+
+

If the texture map is not +repeated, the texture coordinates are +clamped to the 0.0 to 1.0 range as follows:

+
+
Texture map location = N,     if C > 1.0,
= 0.0, if C < 0.0,
= C × N, if 0.0 ≤ C ≤ 1.0.
+
+
+

Texture coordinates may be transformed (scaled, rotated, translated) by supplying a TextureTransform as a component of the texture's definition.

+
+ +
+HISTORY: New entity in IFC 2x2. +
+ +
" +4969;IfcTextLiteralWithExtent;" + +

The text literal with extent is a text literal with the additional explicit information of the planar extent (or surrounding text box). An alignment attribute defines, how the text box is aligned to the placement and how it may expand.

+ +
+NOTE  The IfcTextLiteralWithExtent is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation.
+ +
+NOTE  Corresponding ISO 10303 name: text_literal_with_extent. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The IfcTextLiteralWithExtent has been changed by adding BoxAlignment. +
+ +
" +4981;IfcLightSource;" + +

Definition from ISO/CD 10303-46:1992: The light source entity is determined by the reflectance specified in the surface style rendering. Lighting is applied on a surface by surface basis: no interactions between surfaces such as shadows or reflections are defined.

+ +
+NOTE: Corresponding STEP entity: light_source. Please refer to ISO/IS 10303-46:1994, p. 31 for the final definition of the formal standard. +
+ +
+NOTE: In addition to the attributes as defined in ISO10303-46 the following additional properties from ISO/IEC 14772-1:1997 (VRML) are added: ambientIntensity and Intensity. The attribute Name has been added as well (as it is not inherited via representation_item). +
+ +
+HISTORY: This is a new Entity in IFC 2x, renamed and enhanced in IFC2x2. +
+ +
" +4990;IfcLightSourceAmbient;" + +

Definition from ISO/CD 10303-46:1992: The light source ambient entity is a subtype of light source. It lights a surface independent of the surface's orientation and position.

+ +
+NOTE: Corresponding ISO 10303 entity: light_source_ambient. Please refer to ISO/IS 10303-46:1994, p. 31 for the final definition of the formal standard. +
+ +
+NOTE: In addition to the attributes as defined in ISO 10303-46 the additional property from ISO/IEC 14772-1:1997 (VRML) AmbientIntensity is inherited from the supertype. +
+ +
+HISTORY: This is a new entity in IFC 2x, renamed and enhanced in IFC2x2. +
+ +
" +4991;IfcLightSourceDirectional;" + +

Definition from ISO/CD 10303-46:1992: The light source directional is a subtype of light source. This entity has a light source direction. With a conceptual origin at infinity, all the rays of the light are parallel to this direction. This kind of light source lights a surface based on the surface's orientation, but not position.

+ +

Definition from ISO/IEC 14772-1:1997: The directional light node defines a directional light source that illuminates along rays parallel to a given 3-dimensional vector. Directional light nodes do not attenuate with distance. Directional light nodes are specified in the local coordinate system and are affected by ancestor transformations.

+ +
+NOTE: Corresponding ISO 10303 entity: light_source_directional. Please refer to ISO/IS 10303-46:1994, p. 32 for the final definition of the formal standard. +
+ +
+NOTE: In addition to the attributes as defined in ISO 10303-46 the additional property from ISO/IEC 14772-1:1997 (VRML) AmbientIntensity and Intensity are inherited from the supertype. +
+ +
+HISTORY: This is a new entity in IFC 2x, renamed and enhanced in IFC2x2. +
+ +
" +4993;IfcLightSourcePositional;" + +

Definition from ISO/CD 10303-46:1992: The light source positional entity is a subtype of light source. This entity has a light source position and attenuation coefficients. A positional light source affects a surface based on the surface's orientation and position.

+ +

Definition from ISO/IEC 14772-1:1997: The Point light node specifies a point light source at a 3D location in the local coordinate system. A point light source emits light equally in all directions; that is, it is omnidirectional. Point light nodes are specified in the local coordinate system and are affected by ancestor transformations.

+ +

Point light node's illumination falls off with distance as specified by three attenuation coefficients. The attenuation factor is

+ +
+1/max(attenuation[0] + attenuation[1] × r + attenuation[2] × r 2 , 1), +
+ +

where r is the distance from the light to the surface being illuminated. The default is no attenuation. An attenuation value of (0, 0, 0) is identical to (1, 0, 0). Attenuation values shall be greater than or equal to zero.

+ +
+NOTE: Corresponding ISO 10303 entity: light_source_positional. Please refer to ISO/IS 10303-46:1994, p. 32 for the final definition of the formal standard. +
+ +
+NOTE: In addition to the attributes as defined in ISO10303-46 the additional property from ISO/IEC 14772-1:1997 (VRML) Radius and QuadricAttenuation are added to this subtype and the AmbientIntensity and Intensity are inherited from the supertype. +
+ +
+HISTORY: This is a new entity in IFC 2x, renamed and enhanced in IFC2x2. +
+ +
" +5000;IfcLightSourceSpot;" + +

Definition from ISO/CD 10303-46:1992: The light source spot entity is a subtype of light source. Spot light source entities have a light source colour, position, direction, attenuation coefficients, concentration exponent, and spread angle. If a point lies outside the cone of influence of a light source of this type as determined by the light source position, direction and spread angle its colour is not affected by that light source.

+ +
+NOTE  The IfcLightSourceSpot adds the BeamWidthAngle which defines the inner cone in which the light source emits light at uniform full intensity. The light source's emission intensity drops off from the inner solid angle (BeamWidthAngle) to the outer solid angle (SpreadAngle). +
+ +

Definition from ISO/IEC 14772-1:1997: The Spot light node defines a light source that emits light from a specific point along a specific direction vector and constrained within a solid angle. Spot lights may illuminate geometry nodes that respond to light sources and intersect the solid angle defined by the Spot light. Spot light nodes are specified in the local coordinate system and are affected by ancestors' transformations.

+ +

Figure 304 (from VRML97) shows the definition of spot light.

+ + + + +

Figure 304 — Light source spot

+ +
+NOTE  Corresponding ISO 10303 entity: light_source_spot. Please refer to ISO/IS 10303-46:1994, p. 33 for the final definition of the formal standard. +
+ +
+NOTE  In addition to the attributes as defined in ISO10303-46 the additional property from ISO/IEC 14772-1:1997 (VRML) Radius, BeamWidth, and QuadricAttenuation are added to this subtype and the AmbientIntensity and Intensity are inherited from the supertype. +
+ +
+HISTORY  This is a new entity in IFC 2x, renamed and enhanced in IFC2x2. +
+ +
" +5005;IfcLightSourceGoniometric;" + +

IfcLightSourceGoniometric defines a light source for which exact lighting data is available. It specifies the type of a light emitter, defines the position and orientation of a light distribution curve and the data concerning lamp and photometric information.

+ +

Figure 303 shows an example of a light emitter having two light sources (of type IfcLightSourceGoniometric).

+ + + + +

Figure 303 — Light source goniometric

+ + +
+HISTORY: New entity in IFC2x2. +
+ +
" +5027;IfcLightIntensityDistribution;" + +

IfcLightIntensityDistribution defines the the luminous intensity of a light source that changes according to the direction of the ray. It is based on some standardized light distribution curves, which are defined by the LightDistributionCurve attribute.

+ +
+New entity in IFC2x2. +
+ +
" +5035;IfcLightDistributionData;" + +

IfcLightDistributionData defines the luminous intensity of a light source given at a particular main plane angle. It is based on some standardized light distribution curves; the MainPlaneAngle is either the

+ +
    +
  • A angle; if the IfcLightDistributionCurveEnum is set to TYPE_A
  • +
  • B angle; if the IfcLightDistributionCurveEnum is set to TYPE_B
  • +
  • C angle; if the IfcLightDistributionCurveEnum is set to TYPE_C
  • +
+ +

For each MainPlaneAngle (considered as being the row of a table) a list of SecondaryPlaneAngle's are given (considered to be the columns of a table). They are either the:

+ +
    +
  • α angle; if the IfcLightDistributionCurveEnum is set to TYPE_A
  • +
  • β angle; if the IfcLightDistributionCurveEnum is set to TYPE_B
  • +
  • γ angle; if the IfcLightDistributionCurveEnum is set to TYPE_C
  • +
+ +

For each pair of MainPlaneAngle and SecondaryPlaneAngle the LuminousIntensity is provided (the unit is given by the IfcUnitAssignment referring to the LuminousIntensityDistributionUnit, normally cd/klm).

+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +5039;IfcPresentationLayerAssignment;" + +

The presentation layer assignment provides the layer name (and optionally a description and an identifier) for a collection of geometric representation items. The IfcPresentationLayerAssignment corresponds to the term ""CAD Layer"" and is used mainly for grouping and visibility control.

+ +
+NOTE  The use of presentation layer shall be restricted to simple grouping and displaying purposes. +
+ +

Visibility and access control and layer style assignment (colour, line style, line width) is handled by the subtype IfcPresentationLayerAssignmentWithStyle.

+ +
+NOTE  Corresponding ISO 10303 name: presentation layer assignment. Please refer to ISO/IS 10303-46:1994, p. 36 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +

Attribute use definition

+ +

Figure 305 illustrates assignment of items by shape representation or representation item. The set of AssignedItems can either include a whole shape representation, or individual geometric representation items. If both, the IfcShapeRepresentation has a layer assignment, and an individual geometric representation item in the set of IfcShapeRepresentation.Items, then the layer assignment of the IfcGeometricRepresentationItem overides the layer assignment of the IfcShapeRepresentation.

+ + + + +

Figure 305 — Presentation layer assignment

+ +
" +5046;IfcPresentationLayerWithStyle;" + +

An IfcPresentationLayerAssignmentWithStyle extends the presentation layer assignment with capabilities to define visibility control, access control and common style information.

+ +

The visibility control allows to define a layer to be either 'on' or 'off', and/or 'frozen' or 'not frozen'. The access control allows to block graphical entities from manipulations by setting a layer to be either 'blocked' or 'not blocked'. Common style information can be given to the layer.

+ +
+NOTE  Style information assigned to layers is often restricted to 'layer colour', 'curve font', and/or 'curve width'. These styles are assigned by using the IfcCurveStyle within the LayerStyles. +
+ +
+NOTE: If a styled item is assigned to a layer using the IfcPresentationLayerAssignmentWithStyle, it inherits the style information from the layer. In this case, it should omit its own style information. If the styled item has style information assigned (such as by IfcCurveStyle, IfcFillAreaStyle, IfcTextStyle, IfcSurfaceStyle, IfcSymbolStyle), then it overrides the style provided by the IfcPresentationLayerAssignmentWithStyle. +
+ +
+NOTE  The IfcPresentationLayerAssignmentWithStyle extends the presentation_layer_assignment entity as defined in ISO/IS 10303-46:1994, p. 36. +
+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  The attributes have been modified without upward compatibility. +
+ +
" +5056;IfcParameterizedProfileDef;" + +

The parameterized profile definition +defines a 2D position coordinate system to which the parameters of the +different profiles relate to. All profiles are defined centric to the +origin of the position coordinate system, or more specific, the origin +[0.,0.] shall be in the center of the bounding box of the profile.

+ +

The Position attribute of IfcParameterizedProfileDef +is used to position the profile within the XY plane of the underlying +coordinate system of the swept surface geometry, the swept area +solid or the sectioned spine. It can be used to position the profile at +any point which becomes the origin [0.,0.,0.] of the extruded +or rotated surface or solid.

+ +

The Position attribute should not be used if the transformation +can be specified in a containing object instead. In particular, this +applies if the IfcParameterizedProfileDef is referenced as +SweptArea in subtypes of IfcSweptAreaSolid or as +CrossSections in IfcSectionedSpine.

+ +

Several subtypes of IfcParameterizedProfileDef provide +shape parameters which are optional. Sending systems should always +provide values for these parameters if possible. If these parameters +are left unspecified, receiving systems may retrieve values for them +by external reference (if a reference to an external document or library +is given; see guidance at IfcProfileDef), or estimate them, or +simply assume zero values.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x Platform CHANGE  The IfcParameterizedProfileDef +is introduced as an intermediate new abstract entity that unifies the +definition and usage of the position coordinate system for all +parameterized profiles. The Position attribute has been removed at all +subtypes (like IfcRectangleProfileDef, IfcCircleProfileDef, +etc.). +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center +of the bounding box. +
+ +
+IFC2x4 CHANGE  Position attribute made optional (default: identity transformation).
+Several radius parameters in subtypes have been changed from optional IfcPositiveLengthMeasure (assumed default: 0.) to optional IfcNonNegativeLengthMeasure (default: unspecified). This change allows to explicitly specify zero radius. Sending systems shall export 0. values if parameters are known to be 0.
+Subtypes IfcCraneRailAShapeProfileDef and IfcCraneRailFShapeProfileDef deleted. Rail profiles shall be modeled as IfcArbitraryClosedProfileDef or as IfcAsymmetricIShapeProfileDef together with appropriate external reference. +
+ +
" +5068;IfcProfileDef;" + +

IfcProfileDef +is the supertype of all definitions of standard and arbitrary profiles +within IFC. It is used to define a standard set of commonly used +section profiles by their parameters or by their explicit curve geometry.

+ +
    +
  • Parameterized profiles are 2D primitives, which are used within the industry to describe cross + sections by a description of its parameters.
  • +
  • Arbitrary profiles are cross + sections defined by an outer boundary as bounded curve, which may also + include holes, defined by inner boundaries.
  • +
  • Derived profiles, based on a + transformation of a parent profile, are also part of the profile + definitions available.
  • +
  • In addition composite + profiles can be defined, which include two or more profile definitions + to define the resulting profile.
  • +
+ +
+HISTORY  New class in IFC Release 1.5, the capabilities have been extended in IFC Release 2x. +Profiles can now support swept surfaces and swept area solids with +inner boundaries. It had been renamed from IfcAttDrivenProfileDef. +
+ +
+IFC2x4 CHANGE  Changed from ABSTRACT to non-abstract for uses which do not +require an explicitly defined geometry. Added inverse attributes HasProperties and HasExternalReference. +
+ + +

Use in material association

+ +

Beams, columns, and similarly shaped building elements and their type objects may +be associated with a section profile definition, combined with material definition, +by means of IfcRelAssociatesMaterial together with IfcMaterialProfileSet +and IfcMaterialProfileSetUsage. This way, building elements and element types +with same section and material can share a common section profile definition and +association.

+ +

The profile definition in material association is required to be consistent with +shape representations of the respective building elements.

+ +

A higher-level description of spatial aligment of the section profile of a member +(such as centered, bottom-left, in the geometric centroid, and more) can be provided +within IfcMaterialProfileSetUsage by means of a cardinal point reference. +This can be used redundant to geometric data in order to convey design intent.

+ + +

Use in shape models

+ +

Profile definitions are used within the geometry and geometric model +resource to create either swept surfaces, swept area solids, or +sectioned spines.

+ +

The purpose of the profile +definition within the swept surfaces or swept area solids is to define +a uniform cross section being swept:

+ +
    +
  • along a line (extrusion) using IfcSurfaceOfLinearExtrusion or IfcExtrudedAreaSolid
  • +
  • along a circular arc (revolution) using IfcSurfaceOfRevolution or IfcRevolvedAreaSolid
  • +
  • along a directrix lying on a reference surface using IfcSurfaceCurveSweptAreaSolid
  • +
+ +

The purpose fo the profile +definition within the sectioned spine is to define a varying cross +sections at several positions along a spine curve. The subtype IfcDerivedProfileDef +is particularly suited to provide the consecutive profiles to be based +on transformations of the start profile and thus maintaining the +identity of vertices and edges.

+ +
+NOTE  Subtypes of the IfcProfileDef +contain parameterized profiles (as subtypes of IfcParameterizedProfileDef) +which establish their own 2D position coordinate system, profiles given +by explicit curve geometry (either open or closed profiles) and two +special types for composite profiles and derived profiles, based on a +2D Cartesian transformation. +
+ +

An IfcProfileDef +is treated as bounded area if it is used within swept area solids. In +this case, the inside of the profile is part of the profile. The +attribute ProfileType is set to AREA. An IfcProfileDef +is treated as a curve if it is used within swept surfaces. In this +case, the inside of the profile (if the curve is closed) is not part of +the profile. The attribute ProfileType +is set to CURVE.

+ + +

Figure 320 illustrates use of parameterized profiles within a swept area solid.

+ + + +
+ + + + + + + + + + + +
+ + + + + +

Position
+The IfcProfileDef is defined within the underlying +coordinate system which is defined by the swept surface or swept area solid +that uses the profile definition. It is the xy plane

+ +
    +
  • of IfcSweptSurface.Position or
  • +
  • of IfcSweptAreaSolid.Position or
  • +
  • of each list member of IfcSectionedSpine.CrossSectionPositions.
  • +
+ +

In the figure to the left, the z axis of the position coordinate system points outwards of the drawing plane.

+ +

Note: The subtype IfcParameterizedProfileDef optionally provides an additional 2D position coordinate system relative to the underlying coordinate system of the IfcProfileDef.

+ +
+ + + + + +

Sweeping

+ +

In the later use of the IfcProfileDef +within the swept surface or swept area solid,  e.g. the IfcExtrudedAreaSolid +(here used as an example), the profile boundaries (here based on the 2D +position coordinate system of IfcParameterizedProfileDef) +are placed within the xy plane of the 3D position coordinate system of +the swept surface or swept area solid.

+ +

The profile is inserted into the underlying coordinate system either:

+ +
    +
  • directly in case of using IfcArbitraryClosedProfileDef + and IfcArbitraryOpenProfileDef,
  • + +
  • through an intermediate position coordinate system in case of + using IfcParameterizedProfileDef.
  • + +
  • through an 2D Cartesian transformation operator (applied directly + to the curve position when using arbitrary profile definitions, + or applied to the position coordinate system when using parameterized + profile definitions) in case of using IfcDerivedProfileDef.
  • + +
  • when using IfcCompositeProfileDef the insertion depends on + the subtype of the included sub-profiles.
  • +
+ +
+

Figure 320 — Profile sweeping

+ +

Profile types

+ +

Results of the different usage of the ProfileType attribute are demonstrated here. The ProfileType defines whether the inside (the bounded area) is part of the profile definition (Area) or not (Curve). Figure 321 illustrates the resulting area or curve depending on ProfileType.

+ + + +
+ + + + + + + +
+ +
+ProfileType = AREA + +
+ +
+ProfileType = CURVE + +
+

Figure 321 — Profile types

+ + +

Profile specification by external reference

+ +

If the profile is standardized by a norm or a catalogue, a reference +to this norm or catalogue should be provided by means of HasExternalReference. +This inverse relationship is used to associate an IfcExternalReference (notably +IfcClassificationReference or IfcLibraryReference) with the +profile.

+ +

IfcClassificationReference is used to refer to a profile norm (a common standard or +manufacturer's standard). In this case,

+
    +
  • IfcClassificationReference.ItemReference +contains the formal profile designation from the norm. +(On the other hand, IfcProfileDef.ProfileName contains a displayable name which may +not necessarily be the same as the formal designation.)
  • +
  • IfcClassificationReference.Name carries the short name of the profile norm.
  • +
  • Optionally, the norm can be further described by +IfcClassificationReference.ReferencedSource.
  • +
+ +

IfcLibraryReference is used to refer to a library which contains profile +definitions. In this case,

+
    +
  • IfcLibraryReference.ItemReference contains the identifier of the +profile within the library and is meant to be machine-readable (in contrast to +IfcProfileDef.ProfileName which should be human-readable).
  • +
  • IfcLibraryReference.Location and .Name or .ReferencedLibrary +further describe the library.
  • +
+ +

If an external reference is provided, sending systems shall ensure that +the shape of the profile definition object agrees with the definitions in the +referenced classification or library.

+ + + +

Direct instances of IfcProfileDef

+ +

Usually, only subtypes of IfcProfileDef should be instantiated. +In some special cases, e.g. if the profile object is used for purposes +other than geometric models (e.g. for structural analysis models), it may be +possible to directly instantiate IfcProfileDef and further specify +the profile only by external reference or by profile properties. The latter +are tracked by the inverse attribute HasProperties.

+ +
" +5078;IfcArbitraryOpenProfileDef;" + +

The open profile IfcArbitraryOpenProfileDef defines an arbitrary two-dimensional open profile for the use within the swept surface geometry. It is given by an open boundary from with the surface can be constructed.

+ +
+HISTORY  New entity in IFC2x. +
+ +

Informal proposition:

+
    +
  1. The Curve has to be an open curve.
  2. +
+ +

Figure 308 illustrates the arbitrary open profile definition. The Curve is defined in the underlying coordinate system. The underlying coordinate system is defined by the swept surface that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptSurface.Position
  • +
+

The Curve attribute defines a two dimensional open bounded curve.

+ + + + +

Figure 308 — Arbitrary open profile

+ +
" +5083;IfcCenterLineProfileDef;" + +

The profile IfcCenterLineProfileDef defines an arbitrary two-dimensional open, not self intersecting profile for the use within the swept solid geometry. It is given by an area defined by applying a constant thickness to a centerline, generating an area from which the solid can be constructed.

+ +

Among else, IfcCenterLineProfileDef is used to model cold-formed +steel or aluminium sections (Sigma, Zeta, Omega, and similar sections +which are not covered by subtypes of IfcParameterizedProfileDef). +However, since IfcCenterLineProfileDef does not provide shape parameters +except for the thickness, there is generally a need to further specify the +profile definition by means of

+
    +
  • the name, +
  • external reference to a document or library,
  • +
  • profile properties,
  • +
+

or a combination of them. See IfcProfileDef for guidance on external references for profiles.

+ +
+HISTORY  New entity in IFC2x3. +
+ +

Informal proposition:

+
    +
  1. The Curve has to be an open curve.
  2. +
  3. The Curve has to be a non-intersecting curve.
  4. +
+ +

Figure 311 illustrates the center line profile definition. The Curve is defined in the underlying coordinate system. The underlying coordinate system is defined by the swept surface that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptSurface.Position
  • +
+

The Curve attribute defines a two dimensional open bounded curve. The Thickness attribute defines a constant thickness along the curve.

+ + + + +

Figure 311 — Centerline profile

+ +
" +5085;IfcArbitraryClosedProfileDef;" + +

The closed profile IfcArbitraryClosedProfileDef defines an arbitrary two-dimensional profile for the use within the swept surface geometry, the swept area solid or a sectioned spine. It is given by an outer boundary from which the surface or solid can be constructed.

+ +
+HISTORY: New entity in IFC 1.5. Entity has been renamed from IfcArbitraryProfileDef in IFC Release 2x. +
+ +

Informal proposition:

+
    +
  1. The OuterCurve has to be a closed curve.
  2. +
  3. The OuterCurve shall not intersect.
  4. +
+ +

Figure 307 illustrates the arbitrary closed profile definition. The OuterCurve is defined in the underlying coordinate system. The underlying coordinate system is defined by the swept surface or swept area solid that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+

or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. The OuterCurve +attribute defines a two dimensional closed bounded curve.

+ + + + +

Figure 307 — Arbitrary closed profile

+
" +5091;IfcArbitraryProfileDefWithVoids;" + +

The IfcArbitraryProfileDefWithVoids defines an arbitrary closed two-dimensional profile with holes defined for the use for the swept area solid or a sectioned spine. It is given by an outer boundary and inner boundaries from with the solid the can be constructed.

+ +
+HISTORY  New entity in IFC2x. +
+ +

Informal propositions:

+
    +
  1. The outer curve and all inner curves shall be closed curves.
  2. +
  3. The outer curve shall enclose all inner curves.
  4. +
  5. No inner curve shall intersect with the outer curve or any other inner curve.
  6. +
  7. No inner curve may enclose another inner curve.
  8. +
+ +

Figure 309 illustrates the arbitrary closed profile definition with voids. The OuterCurve, defined at the supertype IfcArbitraryClosedProfileDef +and the inner curves are defined in the same underlying coordinate system. The common underlying coordinate system is defined by the swept area solid that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. The OuterCurve attribute defines a two dimensional closed bounded curve, the InnerCurves define a set of two dimensional closed bounded curves.

+ + + + +

Figure 309 — Arbitrary profile with voids

+ +
" +5096;IfcCompositeProfileDef;" +

The IfcCompositeProfileDef +defines the profile by composition of other profiles. The composition +is given by a set of at least two other profile definitions. Any +profile definition (except for another composite profile) can be used +to construct the composite.

+ +
+HISTORY  New entity in IFC2x. +
+ +

Figure 314 illustrates the composite profile definition. The IfcCompositeProfileDef does not define an own position coordinate system, it is directly defined in the underlying coordinate system. The underlying coordinate system is defined by the swept surface or swept area solid that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+

Or in case of sectioned spines it is the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. The IfcCompositeProfileDef is defined using other profile definitions. Those other profile definitions are directly inserted into the underlying coordinate system.

+
    +
  • In case of parameterized profile definitions, the Position attribute of those standard profiles is used to place the profiles relatively to each other.
  • +
  • In case of arbitrary profile definitions, each Cartesian coordinate is given directly within the underlying coordinate system.
  • +
+ +
+NOTE  The black coordinate axes show the underlying coordinate system of the swept surface or swept area solid. +
+ + + + +

Figure 314

+ +

Twin profiles special case

+ +

If twin profiles are modeled by profile composition, the base profile should +only be specified once. It is then included into the composite profile directly +and additionally indirectly via IfcMirroredProfileDef. For example, a +double angle made of two L100x10 with 10mm air gap between them, i.e. a +_| |_ shape, can be modeled as

+ +
+single_L : IfcLShapeProfileDef := IfcLShapeProfileDef(AREA, 'L100X100X10',
+    IfcAxis2Placement2D(IfcCartesianPoint(((.100+.010)/2., .0)), ?),
+    .100, .100, .010, .012, ?, 0., ?, ?);
+ 
+double_L : IfcCompositeProfileDef := IfcCompositeProfileDef(AREA, 'double angle',
+    (single_L, IfcMirroredProfileDef(AREA, ?, single_L, ?)), 'twin profile'); +
+ +
" +5101;IfcDerivedProfileDef;" + +

IfcDerivedProfileDef defines the profile by transformation from the parent profile. The transformation is given by a two dimensional transformation operator. Transformation includes translation, rotation, mirror and scaling. The latter can be uniform or non uniform. The derived profiles may be used to define swept surfaces, swept area solids or sectioned spines.

+ +

The transformation effects the position, rotation, mirroring or scale of the profile at the underlying coordinate system, i.e. the coordinate system defined by the swept surface or swept area solid that uses the profile definition. It is the xy plane of either:

+ +
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+ +

or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. The position and potential rotation of the ParentProfile within the underlying coordinate system is taken into consideration before applying the Cartesian transformation operator.

+ +

Note, if only mirroring is required, IfcMirroredProfileDef should be used instead.

+ +
+HISTORY: New entity in IFC Release 2x. +
+ +

Figure 316 illustrates examples of derived profiles.

+ + + + +
+ + + + + + + + + + + + + + + + + + +
+ + + + + +

Parameter
+The IfcDerivedProfileDef +is defined using the IfcCartesianTransformationOperator2D +(CTO), which is applied to the parent profile definition.
+

+ +

Example
+The example shows an uniform scaling and a transformation +of an IfcRectangleProfileDef +to match the lower-left cardinal point. The attributes of the CTO are:
+

+ +
Axis1 = NIL (defaults to 1.,0.)
+ Axis2 = NIL (defaults to 0.,1.)
+ LocalOrigin = IfcCartesianPoint(<1/2 XDim>,<1/2 YDim>)
+ Scale = 2.
+
+ +Note: The ParentProfile has a Position += IfcCartesianPoint(<1/2 XDim>,<1/2 YDim>) already.
+ +
+ + + + + +

Parameter
+The IfcDerivedProfileDef is defined using +non uniform transformationsby applying the IfcCartesianTransformationOperator2DnonUniform +as a subtype of the 2D CTO.

+ +

Example
+The example shows a non-uniform scaling and a translation of an IfcRectangleProfileDef +to match the lower-left cardinal point. The attributes of the CTO are:

+ +
Axis1 = NIL (defaults to 1.,0.)
+ Axis2 = NIL (defaults to 0.,1.)
+ LocalOrigin = IfcCartesianPoint(0.,<1/2 YDim)
+ Scale  = 1.
+ Scale2 = 2.
+
+ +Note: The ParentProfile has a Position += IfcCartesianPoint(<1/2 XDim>,<1/2 YDim>) already. + +
+ + + + + +

Parameter
+The IfcDerivedProfileDef +is defined using mirroring by applying the IfcCartesianTransformationOperator2D +(CTO) to the parent profile.

+ +

Example
+The example shows a mirroring of an IfcLShapeProfileDef +to match the centre cardinal point. The attributes of the CTO are:

+ +
Axis1 = (-1.,0.)
+ Axis2 = NIL (defaults to 0.,1.)
+ LocalOrigin = IfcCartesianPoint(0.,0.)
+ Scale = NIL (defaults to 1.)
+
+ +Note: The ParentProfile has a Position = IfcCartesianPoint(0.,0.). + +

This example is for illustration only. +If the transformation results only in mirroring like shown in the example, then +IfcMirroredProfileDef should be used instead of IfcDerivedProfileDef.

+ +
+ +Note: The following color map applies:
+ +
    +
  • black coordinate axes show the + underlying coordinate system of the swept surface, swept area solid, or + sectioned spine
  • + +
  • red coordinate axes + show the position coordinate system of the parent profile
  • + +
  • brown coordinate axes + show the position coordinate system of the derived profile
  • +
+ +
+

Figure 316 — Derived profile

+ +
" +5107;IfcMirroredProfileDef;" + +

The IfcMirroredProfileDef defines the profile by mirroring the parent profile about the y axis of the parent profile coordinate system. That is, left and right of the parent profile are swapped.

+ +

Notes:

+ +

IfcMirroredProfileDef is primarily useful together with +IfcCShapeProfileDef, IfcLShapeProfileDef, +IfcUShapeProfileDef, or IfcZShapeProfileDef as +parent profile but can be used with other parent profile types as well.

+ +

Mirroring of an IfcParameterizedProfileDef is performed after +translation and rotation according to its Position attribute. +For example, if the parent profile's Position offsets it by half +of its width to the right, then the mirrored profile will be offset by +half of its width to the left.

+ +

Mirroring about the x axis, i.e. swapping top and bottom, can be +achieved by mirroring about the y axis coupled with 180 degree rotation +about the z axis. +In general, rotation happens in a containing object such as +IfcSweptAreaSolid, i.e. after mirroring by IfcMirroredProfileDef +was performed. +If the parent profile is an IfcParameterizedProfileDef, rotation +can alternatively happen already in the parent profile by means of its +Position attribute, i.e. before mirroring by IfcMirroredProfileDef +was performed.

+ +
+HISTORY  New entity in IFC2x4. +
+ +
" +5112;IfcProfileProperties;" + +

This is a collection of properties applicable to section profile definitions.

+ +

The following sets of extended profile property definitions are part of this IFC release:

+ + + +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x4 CHANGE  Entity made non-abstract. Subtypes IfcGeneralProfileProperties, IfcStructuralProfileProperties, and IfcStructuralSteelProfileProperties deleted. Attribute ProfileName deleted, use ProfileDefinition.ProfileName instead. Attribute ProfileDefinition made mandatory. Attributes Name, Description, and HasProperties added. +
+ +
" +5117;IfcIShapeProfileDef;" + +

IfcIShapeProfileDef +defines a section profile that provides the defining parameters of a +symmetrical 'I' section to be used by the swept surface geometry or the +swept area solid. The I-shape profile has values for its overall depth, +width and its web and flange thickness. Additionally a fillet radius +may be given. It represents a I-section that is symmetrical about its +major and minor axes; and that has both top and bottom flanges being +equal and centred on the web.

+ +

IfcIShapeProfileDef can also be used to model I sections with +sloped or rounded flanges. The slope and radius cannot be expressed in +explicit attributes, but they may be retrieved by reference to an +external document or library. See IfcProfileDef for guidance on +external references for profile definitions.

+ +
+HISTORY  New entity in IFC2x. +
+ +
+IFC2x4 CHANGE  Type of FilletRadius relaxed to allow for zero radius. +
+ +

Figure 318 illustrates parameters of the I-shape profile definition.

+ + + + +
+ + + + + + + + + + + +
+

Position +
+The parameterized +profile defines its own position coordinate system. +The underlying +coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+by using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile. Explicit coordinate offsets are used to define +cardinal points (e.g. upper-left bound). +

Parameter +
+The parameterized profile +is defined by a set of parameter attributes, see attribute definition +below.

+

+ Note: +The black coordinate axes show the +underlying coordinate system of the swept surface or swept area solid
+

Position +
+The profile is inserted into the underlying +coordinate system of the swept area solid by using the Position +attribute. In this example (cardinal point of lower left corner) the +attribute values of IfcAxis2Placement2D +are:

+
+

Location += IfcCartesianPoint(<1/2 +OverallWidth>,<1/2 OverallDepth>)
+RefDirection = NIL (defaults to 1.,0.)

+
+

Parameter
+If the FilletRadius +is given, it is equally applied to all four corners created by the web +and flanges.

+
+

Figure 318 — I-shape profile

+ +
" +5127;IfcAsymmetricIShapeProfileDef;" + +

IfcAsymmetricIShapeProfileDef +defines a section profile that provides the defining parameters of a +singly symmetric I-shaped section. Its parameters and orientation relative to the +position coordinate system are according to the following illustration. +The centre of the position coordinate system is in the profile's centre +of the bounding box.

+ +

The inherited attributes are redefined as:

+
    +
  • OverallWidth -- BottomFlangeWidth
  • +
  • FlangeThickness -- BottomFlangeThickness
  • +
  • FilletRadius -- BottomFlangeFilletRadius
  • +
+

The overall width of the profile is implicitly given by the maximum of +the bottom flange width and the top flange width.

+ +

IfcAsymmetricIShapeProfileDef can also be used to model rail profiles +if the application scenario does not require a full explicit shape model of the +rail profile. Alternatively, IfcArbitraryClosedProfileDef can be +used to provide the exact shape of rail profiles. Either way, a reference +to an external document or library should be provided to further define the +profile as described at IfcProfileDef.

+ +
+HISTORY  New entity in Release IFC2x Edition 2. +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center of the bounding box. The attribute CentreOfGravityInY has been made OPTIONAL. +
+ +
+IFC2x4 CHANGE  Bottom flange is not necessarily wider than top flange. TopFlangeThickness changed from OPTIONAL to mandatory. Type of TopFlangeFilletRadius relaxed to allow for zero radius. Trailing attribute CentreOfGravityInY deleted, use respective property in IfcExtendedProfileProperties instead. +
+ +

Figure 310 illustrates parameters of the asymmetric I-shaped section definition. The parameterized profile defines its own position coordinate system. The underlying coordinate system is defined by the swept area solid that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

By using offsets of the position location, the parameterized profile can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile. The parameterized profile is defined by a set of parameter attributes. In the illustrated example, the 'CentreOfGravityInY' property in IfcExtendedProfileProperties, if provided, is negative.

+ + + + +

Figure 310 — Assymetric I-shape profile

+ +
" +5131;IfcLShapeProfileDef;" + +

IfcLShapeProfileDef +defines a section profile that provides the defining parameters of an +L-shaped section (equilateral L profiles are also covered by this +entity) to be used by the swept area +solid. Its parameters and orientation relative to the position +coordinate system are according to the following illustration. The +shorter leg has the same direction as the positive Position.P[1]-axis, the longer +or equal leg the same as the positive Position.P[2]-axis. The centre of the +position coordinate system is in the profiles centre +of the bounding box.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center of the bounding box. +
+ +
+IFC2x4 CHANGE  Width changed from OPTIONAL to mandatory. The previously informal rule that the longer leg is the Depth has been formalized. Types of FilletRadius and EdgeRadius were relaxed to allow for zero values. Trailing attributes CentreOfGravityInX and CentreOfGravityInY deleted, use respective properties in IfcExtendedProfileProperties instead. WHERE rule which required Width <= Depth removed.
+ +

Figure 319 illustrates parameters of equal-sided and non-equal sided L-shaped section definitions.

+ + + + +
+ + + + + + + + + + + +
+ + + + + +

Position
+The parameterized profile defines its own position coordinate system. +The underlying coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

by using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile.

+ +

In the illustrated example, the 'CentreOfGravityInX' and 'CentreOfGravityInY' properties in IfcExtendedProfileProperties, if provided, are both negative.

+ +
+ +
+ +Note: +The black coordinate axes show the +underlying coordinate system of the swept surface or swept area solid + +
+ +

Position
+The profile is inserted into the underlying +coordinate system of the swept area solid by using the Position +attribute. In this example (cardinal point of gravity) the +attribute values of IfcAxis2Placement2D +are:

+ +
+

Location = IfcCartesianPoint(
+              +|CentreOfGravityInX|,
+              +|CentreOfGravityInY|)
+RefDirection = NIL (defaults to 1.,0.)

+
+ +

In the illustrated example, the x and y value of Position.Location, i.e. the measures |CentreOfGravityInX| and |CentreOfGravityInY| are both positive. On the other hand, the properties named 'CentreOfGravityInX' and 'CentreOfGravityInY' in IfcExtendedProfileProperties, if provided, must both be set to 0 now because the centre of gravity of the resulting profile definition is located in the coordinate origin.

+ +
+

Figure 319 — L-shape profile

+ +
" +5139;IfcUShapeProfileDef;" + +

IfcUShapeProfileDef defines +a section profile that provides the defining parameters of a U-shape +(channel) section to be used by the swept area solid. Its parameters +and orientation relative to the position coordinate system are +according to the following illustration. The centre of the position +coordinate system is in the profile's centre of the bounding box.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center of the bounding box. +
+ +
+IFC2x4 CHANGE  Type of FilletRadius and EdgeRadius relaxed to allow for zero radius. +Trailing attribute CentreOfGravityInX deleted, use respective property in IfcExtendedProfileProperties instead. +
+ +

Figure 327 illustrates parameters of the U-shape profile definition.

+ + + +
+ + + + + + + +
+ + + + + +

Position
+The parameterized profile defines its own position coordinate system. +The underlying coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

By using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile.

+ +
+

Figure 327 — U-shape profile

+ +
" +5149;IfcCShapeProfileDef;" + +

IfcCShapeProfileDef defines +a section profile that provides the defining parameters of a C-shaped +section to be used by the swept area solid. This section is typically +produced by cold forming steel. Its parameters and orientation relative +to the position coordinate system are according to the following +illustration. The centre of the position coordinate system is in the +profile's centre of the bounding box.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center of the bounding box. +
+ +
+IFC2x4 CHANGE  Type of InternalFilletRadius relaxed to allow for zero radius. +Trailing attribute CentreOfGravityInX deleted, use respective property in IfcExtendedProfileProperties instead. +
+ +

Figure 315 illustrates parameters of the C-shape profile definition. The parameterized profile defines its own position coordinate system. The underlying coordinate system is defined by the swept area solid that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

By using offsets of the position location, the parameterized profile can be positioned centric (using x,y offsets = 0.), or at any position relative to the profile. The parameterized profile is defined by a set of parameter attributes. In the illustrated example, the 'CentreOfGravityInX' property in IfcExtendedProfileProperties, if provided, is negative.

+ + + + +

Figure 315 — C-shape profile

+ +
" +5158;IfcZShapeProfileDef;" + +

IfcZShapeProfileDef defines +a section profile that provides the defining parameters of a Z-shape +section to be used by the swept area solid. Its parameters and +orientation relative to the position coordinate system are according to +the following illustration. The centre of the position coordinate +system is in the profile's centre of the bounding box.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x Edition 4 CHANGE  Type of FilletRadius and EdgeRadius relaxed to allow for zero radius. +
+ +

Figure 328 illustrates parameters of the Z-shape profile definition.

+ + + +
+ + + + + + + +
+ + + + +

Position
+The parameterized profile defines its own position coordinate system. +The underlying coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

By using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile.

+ +
+

Figure 328 — Z-shape profile

+ +
" +5166;IfcTShapeProfileDef;" + +

IfcTShapeProfileDef defines +a section profile that provides the defining parameters of a T-shaped +section to be used by the swept area solid. Its parameters and +orientation relative to the position coordinate system are according to +the following illustration. The centre of the position coordinate +system is in the profile's centre of the bounding box.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x3 CHANGE  All profile origins are now in the center of the bounding box. +
+ +
+IFC2x4 CHANGE  Type of FilletRadius, FlangeEdgeRadius, and WebEdgeRadius relaxed to allow for zero radius. Trailing attribute CentreOfGravityInY deleted, use respective property in IfcExtendedProfileProperties instead. +
+ +

Figure 326 illustrates parameters of the T-shape profile definition.

+ + + +
+ + + + + + + +
+ + + + +

Position
+The parameterized profile defines its own position coordinate system. +The underlying +coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

by using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile.

+ +
+

Figure 326 — T-shape profile

+ +
" +5178;IfcCircleProfileDef;" +

IfcCircleProfileDef defines a circle as the profile definition used by the swept surface geometry or by the swept area solid. It is given by its Radius attribute and placed within the 2D position coordinate system, established by the Position attribute.

+ +
+HISTORY  New class in IFC 1.5. +
+ +

Figure 313 illustrates parameters for the circle profile definition. The parameterized profile defines its own position coordinate system. The underlying coordinate system is defined by the swept surface or swept area solid that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+

Or in case of sectioned spines, it is the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. By using offsets of the position location, the parameterized profile can be positioned centric (using x,y offsets = 0.), or at any position relative to the profile. Explicit coordinate offsets are used to define cardinal points (e.g. upper-left bound). The Position attribute defines the 2D position coordinate system of the circle.
The Radius attribute defines the radius of the circle.

+ + + + +

Figure 313 — Circle profile

+
" +5181;IfcCircleHollowProfileDef;" +

IfcCircleHollowProfileDef +defines a section profile that provides the defining parameters of a +circular hollow section (tube) to be used by the swept area solid. Its +parameters and orientation relative to the +position coordinate system are according to the following +illustration.The centre of the position coordinate system is in the +profile's centre of the bounding box (for symmetric profiles identical +with the centre of gravity).

+ +
+HISTORY  New entity in IFC2x2. +
+ +

Figure 312 illustrates parameters of the circular hollow profile definition. The parameterized profile defines its own position coordinate system. The underlying coordinate system is defined by the swept area solid that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

By using offsets of the position location, the parameterized profile can be positioned centric (using x,y offsets = 0.), or at any position relative to the profile. Explicit coordinate offsets are used to define cardinal points (for example, upper-left bound). The parameterized profile is defined by a set of parameter attributes.

+ + + + +

Figure 312 — Circle hollow profile

+ +
" +5184;IfcEllipseProfileDef;" +

IfcEllipseProfileDef defines an ellipse as the profile definition used by the swept surface geometry +or the swept area solid. It is given by its semi axis attributes and placed within the 2D position coordinate system, established by the Position attribute.

+ +
+HISTORY  New entity in IFC2x +
+ +

Figure 317 illustrates parameters for the ellipse profile definition. The parameterized profile defines its own position coordinate system. +The underlying coordinate system is defined by the swept surface or swept area solid that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+

Or in case of sectioned spines it is the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. By using offsets of the position location, the parameterized profile can be positioned centric (using x,y offsets = 0.), or at any position relative to the profile. Explicit coordinate offsets are used to define cardinal points (for example, upper-left bound). The location of the position coordinate system defines the center of the ellipse. The SemiAxis1 attribute defines the first radius of the ellipse in the direction of the X axis, the SemiAxis2 attribute defines the second radius of the ellipse in the direction of the Y axis.

+ +
+NOTE  The semi axes of the ellipse are rectangular to each other by definition. +
+ + + + +

Figure 317 — Ellipse profile

+ +
" +5187;IfcRectangleProfileDef;" +

IfcRectangleProfileDef defines a rectangle as the profile definition used by the swept surface geometry or the swept area solid. It is given by its X extent and its Y extent, and placed within the 2D position coordinate system, established by the Position attribute. It is placed centric within the position coordinate system.

+ +
+HISTORY: New class in IFC 1.5. The use definition has changed in IFC Release 2x. +
+ +

Figure 323 illustrates parameters of the rectangle profile definition.

+ + + +
+ + + + + + + +
+

Position +
+The parameterized profile defines its own position coordinate system. +The underlying +coordinate system is defined by the swept surface or swept area solid +that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. +
+
+By using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile. Explicit coordinate offsets are used to define +cardinal points (for example, upper-left bound). +

Parameter +
+The IfcRectangleProfileDef +is defined within the position +coordinate system, where the XDim +defines the length measure +for the length of the rectangle (half along the positive x-axis) and +the YDim +defines the length measure for the width of the +rectangle (half along the positive y-axis).

+
+

Figure 323 — Rectangle profile

+ +
" +5192;IfcRectangleHollowProfileDef;" + +

IfcRectangleHollowProfileDef defines a section profile that provides the defining parameters of a rectangular (or square) hollow section to be used by the swept surface geometry or the swept area solid. Its parameters and orientation relative to the position coordinate system are according to the following illustration. A square hollow section can be defined by equal values for h and b. The centre of the position coordinate system is in the profiles centre of the bounding box (for symmetric profiles identical with the centre of gravity). Normally, the longer sides are parallel to the y-axis, the shorter sides parallel to the x-axis.

+ +
+HISTORY  New entity in IFC2x2. +
+ +
+IFC2x4 CHANGE  Types of InnerFilletRadius and OuterFilletRadius relaxed to allow for zero values. +
+ +

Figure 322 illustrates parameters of a rectangular or square hollow profile definition.

+ + + +
+ + + + + + + +
+ + + + + +

Position
+The parameterized profile defines its own position coordinate system. +The underlying coordinate system is defined by the swept area solid +that uses the profile definition. It is the xy plane of:

+
    +
  • IfcSweptAreaSolid.Position
  • +
+

by using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile.

+ +
+

Figure 322 — Rectangle hollow profile

+ +
" +5199;IfcRoundedRectangleProfileDef;" + +

IfcRoundedRectangleProfileDef defines a rectangle with equally rounded corners as the profile definition used by the swept surface geometry or the swept area solid. It is given by the X extent, the Y extent, and the radius for the rounded corners, and placed within the 2D position coordinate system, established by the Position attribute. It is placed centric within the position coordinate system, that is, in the center of the bounding box. +

+ +
+HISTORY  New class in IFC2x. +
+ +
+IFC2x PLATFORM CHANGE  The IfcRoundedRectangleProfileDef is now subtyped from IfcRectangleProfileDef. The XDim and YDim attributes have been removed (now inherited from supertype). +
+ +

Figure 324 illustrates parameters of the rounded rectangle profile definition.

+ + + +
+ + + + + + + +
+

Position +
+The parameterized profile defines its own position coordinate system. +The underlying +coordinate system is defined by the swept surface or swept area solid +that uses the profile definition. It is the xy plane of either:

+
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. +
+
+By using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile. Explicit coordinate offsets are used to define +cardinal points (e.g. upper-left bound). +

Parameter +
+The IfcRoundedRectangleProfileDef +is defined within the +position coordinate system, where the XDim +defines the measure +for the length of the rectangle (half along the positive x-axis), the YDim +defines the length measure for the width of the rectangle (half along +the positive y-axis) and the RoundingRadius +defines the radius +of curvature in all four corners of the rectangle.

+
+

Figure 324 — Rounded rectangle profile

+ +
" +5202;IfcTrapeziumProfileDef;" + +

IfcTrapeziumProfileDef defines a trapezium as the profile definition used by the swept surface geometry or the swept area solid. It is given by its Top X and Bottom X extent and its Y extent as well as by the offset of the Top X extend, and placed within the 2D position coordinate system, established by the Position attribute. It is placed centric within the position coordinate system, that is, in the center of the bounding box.

+ +
+HISTORY  New class in IFC 1.5. The use definition has changed in IFC2x. +
+ +

Figure 325 illustrates parameters of the trapezium profile definition.

+ + + +
+ + + + + + + +
Position +
+The parameterized profile defines its own position coordinate system. +The underlying +coordinate system is defined by the swept surface or swept area solid +that uses the profile definition. It is the xy plane of either: +
    +
  • IfcSweptSurface.Position
  • +
  • IfcSweptAreaSolid.Position
  • +
+or in case of sectioned spines the xy plane of each list member of IfcSectionedSpine.CrossSectionPositions. +
+
+By using offsets of the position location, the parameterized profile +can be positioned centric (using x,y offsets = 0.), or at any position +relative to the profile. Explicit coordinate offsets are used to define +cardinal points (e.g. upper-left bound). +

Parameter +
+The IfcTrapeziumProfileDef +is defined within the position +coordinate system, where the BottomDim +defines the length +measure for the bottom line (half along the positive x-axis) and the YDim +defines the length measure for the parallel distance of bottom and top +line (half along the positive y-axis). The top line starts with a +distance of TopXOffset +from [-BottomLine/2,YDim] (which can be +negative, zero, or positive) and has a length of TopXDim +along +the positive x-axis.

+
+

Figure 325 — Trapezium profile

+ +
" +5207;IfcReinforcementBarProperties;" + +

IfcReinforcementProperties defines the set of properties for a specific combination of reinforcement bar steel grade, bar type and effective depth.

+ +
+HISTORY  New entity in IFC2x2. +
+ +

The total cross section area for the specific steel grade is always provided. Additionally also general reinforcing bar configurations as a count of bars may be provided as defined in attribute BarCount. In this case the nominal bar diameter should be identical for all given bars as defined in attribute NominalBarDiameter.

+ +
" +5217;IfcSectionProperties;" + +

IfcSectionProperties defines the cross section properties for a single longitudinal piece of a cross section. It is a special-purpose helper class for IfcSectionReinforcementProperties.

+ +
+HISTORY  New entity in IFC2x2. +
+ +

The section piece may be either uniform or tapered. In the latter case an end profile should also be provided. The start and end profiles are assumed to be of the same profile type. Generally only rectangular or circular cross section profiles are assumed to be used.

+ +
" +5224;IfcSectionReinforcementProperties;" + +

IfcSectionReinforcementProperties defines the cross section properties of reinforcement for a single longitudinal piece of a cross section with a specific reinforcement usage type.

+ +
+HISTORY  New entity in IFC2x2. +
+ +

Several sets of cross section reinforcement properties represented by instances of IfcReinforcementProperties may be attached to the section reinforcement properties +(IfcReinforcementDefinitionProperties of IfcStructuralElementsDomain schema), +one for each combination of steel grades and reinforcement bar types and sizes.

+ +
" +5243;IfcApplication;" + +

IfcApplication holds the information about an IFC compliant application developed by an application developer. The IfcApplication utilizes a short identifying name as provided by the application developer.

+ +
+HISTORY  New entity in IFC R1.5. +
+ +
" +5253;IfcOwnerHistory;" + +

IfcOwnerHistory defines all history and identification related information. In order to provide fast access it is directly attached to all independent objects, relationships and properties.

+ +

IfcOwnerHistory is used to identify the creating and owning application and user for the associated object, as well as capture the last modifying application and user.

+ +
+HISTORY  New entity in IFC R1.0. Modified in IFC R2x4. +
+ +

Informal propositions

+
    +
  1. If LastModifiedDate is defined but ChangeAction is not asserted, then the state of ChangeAction is assumed to be UNDEFINED.
  2. +
  3. If both LastModifiedDate and ChangeAction are asserted, then the state of ChangeAction applies to the value asserted in LastModifiedDate.
  4. + +
+ +
" +5275;IfcTable;" + +

An IfcTable is a data structure for the provision of information in the form of rows and columns. Each instance may have IfcTableColumn instances that define the name, description and units for each column. The rows of information are stored as a list of IfcTableRow objects.

+ +

Limitation: For backwards compatibility, the rows of an IfcTable object are constrained to have the same number of cells. The first Row of the table provides the number of cells. All other rows are forced to include the same number of cells. This is enforced by the WR2.

+ +

Figure 335 illustrates table use.

+ + + +

Figure 335 — Table use

+ +

Figure 336 depicts how tables were structured prior to IFC2x4.

+ + + +

Figure 336 — Table use alternative

+ +
+HISTORY  New entity in IFC R1.5. +
+ +
+IFC2x4 CHANGE  Columns attribute added. +
+ + +
" +5284;IfcTableRow;" + +

IfcTableRow contains data for a single row within an IfcTable.

+ +

Limitation: For backward compatibility, all IfcTableRow objects referenced by an IfcTable shall have the same number of Row Cells. The actual number of Cells shall be taken from the number of cells of the first IfcTableRow for that table. The number of Cells is calculated by the derived attribute NumberOfCellsInRow in the associated IfcTable.

+ +

Figure 337 illustrates table row use.

+ + + +

Figure 337 — Table row use

+ +

Figure 338 depicts how table rows were structured prior to IFC2x4 with the use of the IsHeading flag. Note that the use of the IfcTableColumn constructs should be used instead of the IsHeading flag (which remains for backward compatibility only):

+ + + +

Figure 338 — Table row use alternative

+ +
+HISTORY  New entity in IFC R1.5. +
+ +
" +5288;IfcTableColumn;" + +

An IfcTableColumn is a data structure that captures column information for use in an IfcTable. Each instance defines the name, description, identifier, and units of measure that are applicable to the columnar data associated with the IfcTableRow objects.

+ +

The use of IfcTableColumn supercedes the IsHeading flag associated with IfcTableRow.

+ +
+HISTORY  New entity in IFC2x4. +
+ +
" +5295;IfcBooleanResult;" +

Definition from ISO/CD 10303-42:1992: A Boolean result +is the result of a regularized operation on two solids to create +a new solid. Valid operations are regularized union, regularized +intersection, and regularized difference. For purpose of Boolean +operations, a solid is considered to be a regularized set of +points. The final Boolean result depends upon the operation and +the two operands. In the case of the difference operator the +order of the operands is also significant. The operator can be +either union, intersection or difference. The effect of these +operators is described below:

+
    +
  • Union on two solids is the new solid that is the +regularization of the set of all points that are in either the +first operand or the second operand or in both.
  • +
  • Intersection on two solids is the new solid that is the +regularization of the set of all points that are in both the +first operand and the second operand.
  • +
  • The result of the difference operation on two solids is the +regularization of the set of all points which are in the first +operand, but not in the second operand.
  • +
+ +
+NOTE For example if the first operand is a block and the second operand is a solid cylinder of suitable dimensions and location, the boolean result produced with the difference operator would be a block with a circular hole. +
+
+NOTE Corresponding ISO 10303-42 entity: boolean_result. The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. Please refer to ISO/IS 10303-42:1994, p.175 for the final definition of the formal standard. +
+
+HISTORY: New class in IFC Release 1.5.1. +
+ +
" +5304;IfcHalfSpaceSolid;" + +

Definition from ISO/CD 10303-42:1992: A half space solid is defined by the half space which is the regular subset of the domain which lies on one side of an unbounded surface. The side of the surface which is in the half space is determined by the surface normal and the agreement flag. If the agreement flag is TRUE, then the subset is the one the normal points away from. If the agreement flag is FALSE, then the subset is the one the normal points into. For a valid half space solid the surface shall divide the domain into exactly two subsets. Also, within the domain the surface shall be manifold and all surface normals shall point into the same subset.

+ +
+NOTE A half space is not a subtype of solid model (IfcSolidModel), half space solids are only useful as operands in Boolean expressions. +
+ +
+NOTE Corresponding STEP entity: half_space_solid. Please refer to ISO/IS 10303-42:1994, p. 185 for the final definition of the formal standard. The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. +
+
+HISTORY New class in IFC Release 1.5 +
+ +

Informal propositions:

+
    +
  1. The base surface shall divide the domain into exactly two subsets. If the half space solid is of subtype boxed half space (IfcBoxedHalfSpace), the domain in question is that of the attribute enclosure. In all other cases the domain is all of space and the base surface shall be unbounded.
  2. The base surface shall be an unbounded surface (subtype of IfcElementarySurface).
  3. +
+ +

Figure 258 illustrates the definition of the IfcHalfSpaceSolid within a given coordinate system. The base surface is given by an unbounded plane, the red boundary is shown for visualization purposes only.

+ + + + +

Figure 258 — Half space solid geometry

+ +
" +5310;IfcBoxedHalfSpace;" +

Definition from ISO/CD 10303-42:1992: This entity is a subtype of the half space solid which is trimmed by a surrounding rectangular box. The box has its edges parallel to the coordinate axes of the geometric coordinate system.

+ +
+NOTE  The purpose of the box is to facilitate CSG computations by producing a solid of finite size. +
+ +

The IfcBoxedHalfSpace is +used (as its supertype IfcHalfSpaceSolid) only within +Boolean operations. It divides the domain into exactly two +subsets, where the domain in question is that of the attribute +Enclosure.

+

The purpose of the attribute Enclosure is to provide a +search box for the other operand in the Boolean operation. It +shall be sufficiently large to fully enclose the resulting solid +after the Boolean operation with the half space. It however does +not alter the final result. The result of the Boolean operation +would be the same, as if executed by the supertype +IfcHalfSpaceSolid. See Figure 253 below.

+ + + + +

Figure 253 — Boxed half space operands

+ +
+NOTE Corresponding ISO 10303-42 entity: boxed_half_space, please refer to ISO/IS 10303-42:1994, p. 185 for the final definition of the formal standard. The IFC class IfcBoundingBox is used for the definition of the enclosure, providing the same definition as box_domain. +
+
+HISTORY  New entity in IFC Release 1.5.1, improved documentation available in IFC Release 2x. +
+
+IFC2x4 CHANGE  Usage correct, position coordinate system for Enclosure is the object coordinate system. +
+ +

The IfcBoundingBox (relating to ISO 10303-42:1994 box_domain) that provides the enclosure is given for the convenience of the receiving application to enable the use of size box comparison for efficiency (for example, to check first whether size boxes intersect, if not no calculations has to be done to check whether the solids of the entities intersect).

+ +

The Enclosure therefore helps to prevent dealing with infinite-size related issues. The enclosure box is positioned within the object coordinate system, established by the ObjectPlacement of the element represented (for example, by IfcLocalPlacement). Figure 254 shows the Enclosure box being sufficiently large to fully enclose the Boolean result.

+ + + + +

Figure 254 — Boxed half space geometry

+ +
+ " +5313;IfcBoundingBox;" +

+ Definition from ISO/CD 10303-42:1992: A box domain + is an orthogonal box parallel to the axes of the geometric + coordinate system which may be used to limit the domain of + a half space solid. A box domain is specified by the + coordinates of the bottom left corner, and the lengths of + the sides measured in the directions of the coordinate + axes. +

+

+ Every semantic object having a + physical extent might have a minimum default representation + of a bounding box. The bounding box is therefore also used + as minimal geometric representation for any geometrically + represented object. Therefore the IfcBoundingBox is + subtyped from IfcGeometricRepresentationItem. +

+ +
+NOTE Corresponding ISO 10303-42 entity: box_domain, please refer to ISO/IS 10303-42:1994, p. 186 for the final definition of the formal standard. In IFC the bounding box can also be used outside of the context of an IfcBoxedHalfSpace. +
+
+HISTORY New entity in IFC Release 1.0. +
+ +

As shown in Figure 252, the IfcBoundingBox is defined with its own location which can be used to place the IfcBoundingBox relative to the geometric coordinate system. The IfcBoundingBox is defined by the lower left corner (Corner) and the upper right corner (XDim, YDim, ZDim measured within the parent co-ordinate system).

+ + + + +

Figure 252 — Bounding box

+ +
" +5319;IfcPolygonalBoundedHalfSpace;" +

The polygonal bounded +half space is a special subtype of a half space solid, where the +material of the half space used in Boolean expressions is bounded by a +polygonal boundary. The base +surface of the half space is positioned by its normal relativeto the +object coordinate system +(as defined at the supertype IfcHalfSpaceSolid), and +its polygonal (with or without arc segments) boundary is defined in the +XY plane of the position +coordinate system established by the Position +attribute, the subtraction body is extruded perpendicular to the XY +plane of the position coordinate system, that is, into the direction of the +positive Z axis defined by the Position attribute.

+

The boundary is defined by a 2 dimensional polyline (or 2 dimensional composite curve, +consisting of straight segments and circular arc segments) +within the +XY plane of the position coordinate system. The side of the surface +which is in the half space is determined by the surface normal and the +agreement flag. If the agreement flag is TRUE, then the subset is the +one the normal points away from. If the agreement flag is FALSE, then +the subset is the one the normal points into.

+ +
+NOTE  A polygonal bounded half space is not a subtype of IfcSolidModel, half space solids are only useful as operands in Boolean expressions. +
+
+HISTORY  New class in IFC Release 2x. +
+ +

Informal propositions:

+
    +
  1. The IfcPolyline or the IfcCompositeCurve +providing the PolygonalBoundary +shall be closed.
  2. +
  3. If the PolygonalBoundary +is given by an IfcCompositeCurve, it shall only +have IfcCompositeCurveSegment's of type IfcPolyline, +or IfcTrimmedCurve (having a BasisCurve +of type IfcLine, or IfcCircle)
  4. +
+ +

Figure 259 illustrates a polygonal bounded half space.

+
    +
  • Black coordinates indicate the object coordinate system (usually provided by IfcLocalPlacement).
  • +
  • Green coordinates indicate the position coordinate system; the PolygonalBoundary is given within this coordinate system. It is provided by IfcPolygonalBoundedHalfSpace.Position. This coordinate system is relative to the object coordinate system. The extrusion direction of the subtraction body is the positive Z axis.
  • +
  • Red coordinates indicate the normal of the plane. It is provided by the BaseSurface (IfcSurface.Position). This normal is also relative to the object coordinate system.
  • +
+ + + + +

Figure 259 — Polygonal half space geometry

+ +

Purpose
+The polygonal bounded half space is used to limit the volume of the +half space in Boolean difference expressions. Only the part that is +defined by a theoretical intersection between the half space solid and +an extruded area solid, defined by extruding the polygonal boundary, is +used for Boolean expressions.

+

Parameter
+The PolygonalBoundary defines the 2D polyline which +bounds the effectiveness of the half space in Boolean expressions. The BaseSurface +is defined by a plane, and the normal of the plane together with the AgreementFlag +defines the side of the material of the half space.

+ +
" +5324;IfcSolidModel;" + +

Definition from ISO/CD 10303-42:1992: A solid model is a complete representation of the nominal shape of a product such that all points in the interior are connected. Any point can be classified as being inside, outside, or on the boundary of a solid. There are several different types of solid model representations.

+ +
+NOTE: Corresponding ISO 10303-42 entity: solid_model, only three subtypes have been incorporated into the current IFC Release - subset of manifold_solid_brep (IfcManifoldSolidBrep, constraint to faceted B-rep), swept_area_solid (IfcSweptAreaSolid), the swept_disk_solid (IfcSweptDiskSolid) and subset of csg_solid (IfcCsgSolid). The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. Please refer to ISO/IS 10303-42:1994, p. 170 for the final definition of the formal standard. +
+
+HISTORY: New entity in IFC Release 1.5 +
+ +
" +5330;IfcManifoldSolidBrep;" +

Definition from ISO/CD 10303-42:1992: A manifold solid +B-rep is a finite, arcwise connected volume bounded by one or +more surfaces, each of which is a connected, oriented, finite, +closed 2-manifold. There is no restriction on the genus of the +volume, nor on the number of voids within the volume.

+

The Boundary Representation (B-rep) of a manifold solid +utilizes a graph of edges and vertices embedded in a connected, +oriented, finite, closed two manifold surface. The embedded graph +divides the surface into arcwise connected areas known as faces. +The edges and vertices, therefore, form the boundaries of the +face and the domain of a face does not include its boundaries. +The embedded graph may be disconnected and may be a pseudo graph. +The graph is labeled; that is, each entity in the graph has a +unique identity. The geometric surface definition used to specify +the geometry of a face shall be 2-manifold embeddable in the +plane within the domain of the face. In other words, it shall be +connected, oriented, finite, non-self-intersecting, and of +surface genus 0.

+

Faces do not intersect except along their boundaries. Each +edge along the boundary of a face is shared by at most one other +face in the assemblage. The assemblage of edges in the B-rep do +not intersect except at their boundaries (i.e., vertices). The +geometry curve definition used to specify the geometry of an edge +shall be arcwise connected and shall not self intersect or +overlap within the domain of the edge. The geometry of an edge +shall be consistent with the geometry of the faces of which it +forms a partial bound. The geometry used to define a vertex shall +be consistent with the geometry of the faces and edges of which +it forms a partial bound.

+

A B-rep is represented by one or more closed shells which +shall be disjoint. One shell, the outer, shall completely enclose +all the other shells and no other shell may enclose a shell. The +facility to define a B-rep with one or more internal voids is +provided by a subtype. The following version of the Euler formula +shall be satisfied, where V, E, F, Ll and S are the +numbers of unique vertices, edges, faces, loop uses and shells in +the model and Gs is the sum of the genus of the +shells.

+
+
+

+
+
+ +

Instances of type IfcManifoldSolidBrep shall be of type +IfcFacetedBrep, using only IfcPolyLoop for the +bounds of IfcFaceBound, or of type IfcAdvancedBrep, +using only IfcAdvancedFace for the face geometry, and +IfcEdgeCurve for the edges.

+ +
+NOTE: Corresponding ISO 10303-42 entity: manifold_solid_brep. Please refer to ISO/IS 10303-42:1994, p. 170 for the final definition of the formal standard. IfcManifoldSolidBrep is defined as ABSTRACT supertype to prevent it from direct instantiation. +
+
+HISTORY: New entity in IFC Release 1.0 +
+ +

Informal proposition:

+
    +
  1. The dimensionality of a manifold solid brep shall be 3.
  2. +
  3. The extent of the manifold solid brep shall be finite and +non-zero.
  4. +
  5. All elements of the manifold solid brep shall have defined +associated geometry.
  6. +
  7. The shell normals shall agree with the B-rep normal and point +away from the solid represented by the B-rep.
  8. +
  9. Each face shall be referenced only once by the shells of the +manifold solid brep.
  10. +
  11. The Euler equation shall be satisfied for the boundary +representation, where the genus term ""shell term"" us the sum of +the genus values for the shells of the brep.
  12. +
+
" +5334;IfcFacetedBrep;" +

Definition from ISO/CD 10303-42:1992: A faceted B-rep +is a simple form of boundary representation model in which all +faces are planar and all edges are straight lines. Unlike the +B-rep model, edges and vertices are not represented explicitly in +the model but are implicitly available through the poly loop +entity. A faceted B-rep has to meet the same topological +constraints as the manifold solid B-rep.

+ +
+NOTE The faceted B-rep has been introduced in order to support the larger number of systems that allow boundary type solid representations with planar surfaces only. +
+ +
+NOTE Corresponding ISO 10303-42 entity: faceted_brep. Please refer to ISO/IS 10303-42:1994, p. 173 for the final definition of the formal standard. In the current IFC Release faceted B-rep with voids is represented by an own subtype and not defined via an implicit ANDOR supertype constraint as in ISO/IS 10303-42:1994. This change has been made due to the fact, that only ONEOF supertype constraint is allowed within the IFC data schema. +
+
+HISTORY  New entity in IFC Release 1.0 +
+ +

Informal proposition:

+
    +
  1. All the bounding loops of all the faces of all the shells in +the IfcFacetedBrep shall be of type +IfcPolyLoop.
  2. +
  3. All vertices shall be referenced by all polyloops, sharing the vertex. That is, each Cartesian point shall be referenced by at least three polyloops.
  4. +
+ +

Figure 257 illustrates use of IfcFacetedBrep for boundary representation models with planar surfaces only. The diagram shows the topological and geometric representation items that are used for faceted breps. Each IfcCartesianPoint, used within the IfcFacetedBrep shall be referenced three times by an IfcPolyLoop bounding a different IfcFace.

+ + + + +

Figure 257 — Faceted B-rep

+ +
" +5336;IfcFacetedBrepWithVoids;" +

The IfcFacetedBrepWithVoids +is a specialization of a faceted B-rep which contains one or more +voids in its interior. The voids are represented as closed shells +which are defined so that the shell normal point into the +void.

+ +
+NOTEÿ Corresponding ISO 10303-42 entity: brep_with_voids (see note above). Please refer to ISO/IS 10303-42:1994, p. 173 for the final definition of the formal standard. In IFC faceted B-rep with voids is represented by this subtype IfcFacetedBrepWithVoids and not defined via an implicit ANDOR supertype constraint as in ISO/IS 10303-42:1994 between an instance of faceted_brep AND brep_with_voids. This change has been made due to the fact, that only ONEOF supertype constraint is allowed within the IFC object model. +
+
+HISTORYÿ New entity in IFC Release 1.0 +
+
+IFC2x4 CHANGEÿ Subtyping changed from IfcManifoldSolidBrep to IfcFacetedBrep with upward compatibility for file based exchange. +
+ +

Informal propositions:

+
    +
  1. Each void shell shall be disjoint from the outer shell and +from every other void shell
  2. +
  3. Each void shell shall be enclosed within the outer shell but +not within any other void shell. In particular the outer shell is +not in the set of void shells
  4. +
  5. Each shell in the IfcManifoldSolidBrep shall be +referenced only once.
  6. +
  7. All the bounding loops of all the faces of all the shells in +the IfcFacetedBrep shall be of type +IfcPolyLoop.
  8. +
+
" +5338;IfcAdvancedBrep;" +

An advanced B-rep is a boundary +representation model in which all faces, edges and vertices are +explicitly represented. It is a solid with explicit topology and +elementaty or free-form geometry. The faces of the B-rep are of +type IfcAdvancedFace. An advanced B-rep has to meet the +same topological constraints as the manifold solid B-rep.

+
NOTE The advanced B-rep has been introduced in +order to support the increasing number of applications that can +define and exchange B-rep models based on NURBS or other b-spline +surfaces.
+ +
+NOTE Corresponding ISO 10303-42 entity: advanced_brep_shape_representation. Please refer to ISO/IS 10303-514:1999 for the final definition of the formal standard. There is no explicit entity in ISO 10303-42 for an advanced B-rep, the advanced_brep_shape_representation only ensures that only such kind of manifold B-rep's are used in a shape representation. +
+
+HISTORY New entity in IFC2x4 +
+ +

Informal proposition:

+
    +
  1. each face is a face surface;
  2. +
  3. each face surface has its geometry defined by an elementary +surface, swept surface or a b-spline surface;
  4. +
  5. the edges used to define the boundaries of the face shall all +reference an edge curve
  6. +
  7. each curve used to define the geometry of the faces and face +bounds shall be either a conic, or a line or a polyline or a +b-spline curve
  8. +
  9. the edges used to define the face boundaries shall all be +trimmed by vertices of type vertex point
  10. +
  11. no loop used to define a face bound shall be of the oriented +subtype
  12. +
+ +

Figure 249 illustrates use of IfcAdvancedBrep for boundary representation models with b-spline surfaces. The diagram shows the topological and geometric representation items that are used for advanced B-reps, based on IfcAdvancedFace.

+ + + + +

Figure 249 — Advanced Brep

+ +
" +5341;IfcAdvancedBrepWithVoids;" +

The IfcAdvancedBrepWithVoids is a specialization of an +advanced B-rep which contains one or more voids in its interior. +The voids are represented as closed shells which are defined so +that the shell normal point into the void.

+ +
+NOTEÿ Corresponding ISO 10303-42 entity: brep_with_voids (see note above). Please refer to ISO/IS 10303-42:1994, p. 173 for the final definition of the formal standard. In IFC advanced B-rep with voids is represented by this subtype IfcAdvancedBrepWithVoids and not defined via an implicit ANDOR supertype constraint as in ISO/IS 10303-42:1994 between an instance of manifold_solid_brep AND brep_with_voids. This change has been made due to the fact, that only ONEOF supertype constraint is allowed within the IFC object model. +
+
+HISTORYÿ New entity in IFC2x4 +
+ +

Informal propositions:

+
    +
  1. Each void shell shall be disjoint from the outer shell and +from every other void shell
  2. +
  3. Each void shell shall be enclosed within the outer shell but +not within any other void shell. In particular the outer shell is +not in the set of void shells
  4. +
  5. Each shell in the IfcManifoldSolidBrep shall be +referenced only once.
  6. +
  7. All the faces of all the shells in the IfcAdvancedBrep +and the IfcAdvancedBrepWithVoids.Voids shall be of type +IfcAdvancedFace.
  8. +
+
" +5344;IfcSweptAreaSolid;" +

+ Definition from ISO/CD 10303-42:1992: The swept area + solid entity collects the entities which are defined + procedurally by sweeping action on planar bounded surfaces. + The position is space of the swept solid will be dependent + upon the position of the swept area. The swept area will be + a face of the resulting swept area solid, except for the + case of a revolved area solid with angle equal to 2π + (or 360 degrees). +

+

+ The swept area is defined by a + cross section (also referred to as profile), which is given + as a closed two-dimensional boundary on an implicit plane. + The swept area is defined in the xy plane of the position + coordinate system, which is given for the swept area solid. +

+
+NOTE Corresponding ISO 10303-42 entity: swept_area_solid, The data type of SweptArea is modified and given by a profile definition (IfcProfileDef). A position coordinate system is defined by the Position attribute has been added. Please refer to ISO/IS 10303-42:1994, p. 183 for the final definition of the formal standard. +
+
+HISTORY New entity in IFC Release 1.5, the capabilities have been enhanced in IFC Release 2x. +
+ +
" +5352;IfcExtrudedAreaSolid;" +

The IfcExtrudedAreaSolid is defined by sweeping a cross +section provided by a profile definition. The direction of the +extrusion is given by the ExtrudedDirection attribute and +the length of the extrusion is given by the Depth +attribute. If the planar area has inner boundaries (holes +defined), then those holes shall be swept into holes of the solid. +The extruded direction can be any direction which is not +perpendicular to the z axis of the position coordinate system of +the profile.

+

The following definitions from ISO 10303-42 apply:

+
+

An extruded area +solid is a solid defined by sweeping a bounded planar surface. The +direction of translation is defined by a direction vector, and the +length of the translation is defined by a distance depth. The +planar area may have holes which will sweep into holes in the +solid.

+
+

The ExtrudedDirection is given within the position +coordinate system as defined by +IfcSweptAreaSolid.Position. Extrusions are not restricted +to be perpendicular to the extruded surface of the profile.

+ +

Figure 255 illustrates geometric parameters of the extruded area solid. The extruded area solid defines the extrusion of a 2D area (given by a profile definition) by an direction and depth. The result is a +solid. The swept area is given by a profile definition. This profile is defined:

+
    +
  • as a 2D bounded curve within the xy plane of the position coordinate system,
  • +
  • as a 2D bounded curve with holes within the xy plane of the position coordinate system,
  • +
  • or as a 2D primitive, defined within a 2D position coordinate system, that is placed relative to the xy plane of the position coordinate system
  • +
+ + + + +

Figure 255 — Extruded area solid geometry

+ +
+NOTE  Corresponding ISO 10303-42 entity: extruded_area_solid. Please refer to ISO/IS 10303-42:1994, p. 183 for the final definition of the formal standard. The data type of the inherited SweptArea attribute is different, i.e. of type IfcProfileDef. The Position attribute has been added to position the cross section used for the linear extrusion. +
+
+HISTORY  New entity in IFC Release 1.5, capabilities of this entity have been enhanced in IFC Release 2x.

+
+ +

Texture use definition

+

For side faces, textures are aligned facing upright continuously +along the sides with origin at the first point of an arbitrary +profile, and following the outer bound of the profile +counter-clockwise (as seen from above). For parameterized profiles, +the origin is defined at the +Y extent for rounded profiles (having +no sharp edge) and the first sharp edge counter-clockwise from the ++Y extent for all other profiles. Textures are stretched or +repeated on each side along the outer boundary of the profile +according to RepeatS. Textures are stretched or repeated +on each side along the extrusion axis according to +RepeatT.

+

For top and bottom caps, textures are aligned facing +front-to-back, with the origin at the minimum X and Y extent. +Textures are stretched or repeated on the top and bottom to the +extent of each face according to RepeatS and +RepeatT.

+

For profiles with voids, textures are aligned facing upright +along the inner side with origin at the first point of an arbitrary +profile, and following the inner bound of the profile clockwise (as +seen from above). For parameterized profiles, the origin of inner +sides is defined at the +Y extent for rounded profiles (having no +sharp edge such as hollow ellipses or rounded rectangles) and the +first sharp edge clockwise from the +Y extent for all other +profiles.

+ +

Figure 256 illustrates default texture mapping with a repeated texture (RepeatS=True and RepeatT=True). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis points back to the left, and the Z axis points up. For an IfcExtrudedAreaSolid having a profile of IfcIShapeProfileDef, the side texture coordinate origin is the first corner counter-clockwise from the +Y axis, which equals +(-0.5*IfcIShapeProfileDef.OverallWidth, +0.5*IfcIShapeProfileDef.OverallDepth), while the top (end cap) +texture coordinates start at (-0.5*IfcIShapeProfileDef.OverallWidth, +-0.5*IfcIShapeProfileDef.OverallDepth).

+ + + + +

Figure 256 — Extruded area solid textures

+ +
" +5357;IfcExtrudedAreaSolidTapered;" +

IfcExtrudedAreaSolidTapered is defined by sweeping a cross +section along a linear spine. The cross section may change along +the sweep from the shape of the start cross section into the +shape of the end cross section. The resulting solid is bounded by +three or more faces: A start face, an end face (each defined by +start and end planes and sections), and one or more lateral +faces. Each lateral face is a ruled surface defined by a pair of +corresponding edges of the start and end section.

+
NOTE Given that the start and end section is +provided by a polygon, the corresponding vertices of the start +and end cross section are connected, forming a quadrilateral +polygon between each pair of corresponding vertices. The surface +defined by the bounding quadrilateral polygon is a ruled surface, +that could be approximated by triangulation.
+

The linear spine is defined by:

+
    +
  • Start point: +SELF\IfcSweptAreaSolid.Position.Location
  • +
  • Direction: +SELF\IfcExtrudedAreaSolid.ExtrudedDirection
  • +
  • Distance: SELF\IfcExtrudedAreaSolid.Depth
  • +
+

The start cross section is defined by +SELF\IfcSweptAreaSolid.SweptArea:

+
    +
  • A bounded planar surface lying in the XY plane of the +position coordinate system defined by +SELF\IfcSweptAreaSolid.Position.P[1] and +SELF\IfcSweptAreaSolid.Position.P[2]
  • +
  • The linear spine starts at the plane of the start cross +section. The spine is not necessarily perpendicular to the +plane.
  • +
+

The end cross section is defined by EndSweptArea:

+
    +
  • A bounded planar surface lying in the XY plane of the +position coordinate system defined by translating the start +position coordinates provided by +SELF\IfcSweptAreaSolid.Position along the spine direction +by the spine distance. The plane of the end cross section is +coplanar to the plane of the start cross section.
  • +
  • +
      +
    • The end cross section is topologically similar to the start +cross section (i.e. having the same number of vertices and +edges).
    • +
    • The end cross section can either be defined by the same +paramteric profile using different parameter values, or by a 2D +Cartesian transformation of the start profile within the end +cross section plane.
    • +
    +
  • +
+

In case of two parameterized profiles the shape is constructed +as follows:

+
    +
  • The end profile, defined by a cross section based on the same +profile paramterization as the start profile, is translated by +the spine distance along the spine direction.
  • +
  • It may be shifted within the XY plane of the end postion +coordinate system and may be twisted using the rotation +parameter.
  • +
  • The shift and rotation parameter are provided by the end +cross section being of type IfcParameterizedProfileDef, +where +
      +
    • Shift is +EndSweptArea\IfcParameterizedProfileDef.Position.Location
    • +
    • Rotation is +EndSweptArea\IfcParameterizedProfileDef.Position.RefDirection
    • +
    +
  • +
  • Corresponding vertices of the start and end cross section are +connected. Lateral faces are constructed as ruled surfaces +between corresponding edges of start and end cross section.
  • +
+

In case of Cartesian transformation of the start cross section +the shape is constructed as follows:

+
    +
  • The cross section curve, which starts as a curve in the XY +plane of the position coordinate system, is first scaled about +the origin by the scale parameter. It is then translated by the +spine distance along the spine direction. It maybe twisted by +using the rotation parameter.
  • +
  • The scale and rotation parameter are provided by the end +cross section being of type IfcDerivedProfileDef, where +
      +
    • Scale is +EndSweptArea\IfcDerivedProfileDef.Operator.Scale
    • +
    • Rotation is +EndSweptArea\IfcDerivedProfileDef.Operator.Axis1
    • +
    +
  • +
  • Corresponding vertices of the start and end cross section are +connected. Lateral faces are constructed as ruled surfaces +between corresponding edges of start and end cross section.
  • +
+ +
+HISTORY New entity in IFC2x4. +
+ +

Informal propositions

+
    +
  1. Mirroring within IfcDerivedProfileDef.Operator shall +not be used
  2. +
+ +
" +5360;IfcRevolvedAreaSolid;" +

An IfcRevolvedAreaSolid is a solid created by revolving +a cross section provided by a profile definition about an axis. The +axis and the cross section shall be in the same plane.

+
NOTE Both the axis and the cross section are +required to lie in the xy plane of the object position coordinate +system.
+

The following definitions from ISO 10303-42 apply:

+
+

A revolved area solid +is a solid formed by revolving a planar bounded surface about an +axis. The axis shall be in the plane of the surface and the axis +shall not intersect the interior of the bounded surface. The +bounded surface may have holes which will sweep into holes in the +solid. The direction of revolution is clockwise when viewed along +the axis in the positive direction. More precisely if A is +the axis location and d is the axis direction and C +is an arc on the surface of revolution generated by an arbitrary +point p on the boundary of the swept area, then C +leaves p in direction d x (p - A) as +the area is revolved.

+
+ +

Figure 262 illustrates geometric parameters of the revolved solid. The revolved area solid defines the revolution of a 2D area (given by a profile definition) by an axis and angle. The result is a solid. The swept area is given by a profile definition. This profile is defined:

+
    +
  • as a 2D bounded curve within the xy plane of the position coordinate system,
  • +
  • as a 2D bounded curve with holes within the xy plane of the position coordinate system,
  • +
  • or as a 2D primitive, defined within a 2D position coordinate system, that is placed relative to the xy plane of the position coordinate system
  • +
+

The AxisLine can have any orientation within the XY plane, it does not have to be parallel to the y-axis as shown in the illustration.

+ + + + +

Figure 262 — Revolved area solid geometry

+ +
+NOTE  Corresponding ISO 10303-42 entity: revolved_area_solid. Please refer to ISO/IS 10303-42:1994, p. 184 for the final definition of the formal standard. The data type of the inherited SweptArea attribute is different, i.e. of type IfcProfileDef. The position attribute has been added to position the cross section used for the revolution. +
+
+HISTORY  New entity in IFC Release 1.5, capabilities of this entity have been enhanced in IFC Release 2x. +
+ +

Informal propositions:

+
    +
  1. The AxisLine shall lie in the plane of the +SweptArea (as defined at supertype +IfcSweptAreaSolid).
  2. +
  3. The AxisLine shall not intersect the interior of the +SweptArea (as defined at supertype +IfcSweptAreaSolid).
  4. +
  5. The Angle shall be between 0° and 360°, or 0 +and 2π (depending on the unit type for +IfcPlaneAngleMeasure).
  6. +
+ +

Texture Use Definition

+

For side faces, textures are aligned facing upright along the +sides with origin at the first point of an arbitrary profile, and +following the outer bound of the profile counter-clockwise (as seen +from above). For parameterized profiles, the origin is defined at +the +Y extent for rounded profiles (having no sharp edge) and the +first sharp edge counter-clockwise from the +Y extent for all other +profiles. Textures are stretched or repeated on each side along the +outer boundary of the profile according to RepeatS. +Textures are stretched or repeated on each side along the outermost +(longest) revolution path according to RepeatT, where +coordinates are compressed towards the axis of revolution.

+

For top and bottom caps, textures are aligned facing +front-to-back, with the origin at the minimum X and Y extent. +Textures are stretched or repeated on the top and bottom to the +extent of each face according to RepeatS and +RepeatT.

+

For profiles with voids, textures are aligned facing upright +along the inner side with origin at the first point of an arbitrary +profile, and following the inner bound of the profile clockwise (as +seen from above). For parameterized profiles, the origin of inner +sides is defined at the +Y extent for rounded profiles (having no +sharp edge such as hollow ellipses or rounded rectangles) and the +first sharp edge clockwise from the +Y extent for all other +profiles.

+ +

Figure 263 illustrates default texture mapping with a repeated texture (RepeatS=True and RepeatT=True). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis points back to the left, and the Z axis points up. For an IfcRevolvedAreaSolid having a profile of IfcTShapeProfileDef and revolved at 22.5 degrees, the side texture coordinate origin is the first corner counter-clockwise from the +Y axis, which equals (-0.5*IfcTShapeProfileDef.OverallWidth, +0.5*IfcTShapeProfileDef.OverallDepth), while the top (end cap) texture coordinates start at (-0.5*IfcTShapeProfileDef.OverallWidth, -0.5*IfcTShapeProfileDef.OverallDepth).

+ + + + +

Figure 263 — Revolved area solid textures

+ +
" +5367;IfcRevolvedAreaSolidTapered;" +

IfcRevolvedAreaSolidTapered is defined by revolving a +cross section along a circular arc. The cross section may change +along the revolving sweep from the shape of the start cross +section into the shape of the end cross section. Corresponding +vertices of the start and end cross sections are then connected. +The bounded surface may have holes which will sweep into holes in +the solid.

+

The rotation axis is defined by:

+
    +
  • Start point: +SELF\IfcSweptAreaSolid.Position.Location
  • +
  • Direction: SELF\IfcRevolvedAreaSolid.Axis
  • +
  • Rotation axis: SELF\IfcRevolvedAreaSolid.AxisLine, +created from start point and direction by appying a 1 unit +magnitude.
  • +
  • Orientation: Positive angles are applied clockwise when +looking into the positive direction of the rotation axis.
  • +
+

The start cross section is defined by +SELF\IfcSweptAreaSolid.SweptArea:

+
    +
  • A bounded planar surface lying in the XY plane of the +position coordinate system defined by +SELF\IfcSweptAreaSolid.Position.P[1] and +SELF\IfcSweptAreaSolid.Position.P[2]
  • +
  • The rotation axis lies in the plane of the start cross +section but shall not intersect the interior of the start cross +section.
  • +
+

The end cross section is defined by EndSweptArea:

+
    +
  • A bounded planar surface lying in the XY plane of the +position coordinate system defined by rotating the start position +coordinates provided by SELF\IfcSweptAreaSolid.Position +around the rotation axis by the angle given by +SELF\IfcRevolvedAreaSolid.Angle.
  • +
  • +
      +
    • The end cross section is topologically similar to the start +cross section (having the same number of vertices and edges).
    • +
    • The end cross section can either be defined by the same +paramteric profile using different parameter values, or by a 2D +Cartesian transformation of the start profile within the end +cross section plane.
    • +
    +
  • +
+

The solid is generated by transforming the start cross section +into to end cross section. A start face, an end face (each +defined by start and end cross sections), and one or more lateral +faces. Each lateral face is a ruled surface defined by a pair of +corresponding edges of the start and end section. The ruled +surfaces are constructed in the cylindrical coordinate space +defined by the supertype IfcRevolvedAreaSolid.""

+ +
+HISTORY New entity in IFC2x4. +
+ +

Informal propositions

+
    +
  1. Mirroring within IfcDerivedProfileDef.Operator shall +not be used
  2. +
+ +
" +5370;IfcSurfaceCurveSweptAreaSolid;" +

The IfcSurfaceCurveSweptAreaSolid is the result of +sweeping an area along a directrix that lies on a reference +surface. The swept area is provided by an IfcProfileDef +(or subtypes). The profile definition is based on a 2D coordinate +system, which is inserted into the XY plane of the 3D +Position coordinate system inherited from the supertype +IfcSweptAreaSolid.

+

The following definitions from ISO 10303-42 apply:

+
+

A surface curve swept +area solid is a type of swept area solid which is the result of +sweeping a face along a Directrix lying on a +ReferenceSurface. The orientation of the +SweptArea is related to the direction of the surface +normal.

+

The +SweptArea is required to be a curve bounded surface lying +in the plane z = 0 and this is swept along the Directrix +in such a way that the origin of the local coordinate system used +to define the SweptArea is on the Directrix and +the local x-axis is in the direction of the normal to the +ReferenceSurface at the current point. The resulting solid +has the property that the cross section of the surface by the +normal plane to the Directrix at any point is a copy of +the SweptArea.

+

The orientation of +the SweptArea as it sweeps along the Directrix is +precisely defined by a Cartesian Transformation Operator 3D with +attributes:

+
    +
  • LocalOrigin +as point (0; 0; 0),
  • +
  • Axis1 as +the normal N to the ReferenceSurface at the point of the +Directrix with parameter u.
  • +
  • Axis3 as +the direction of the tangent vector t at the point of the +Directrix with parameter u.
    +The remaining attributes are defaulted to define a corresponding +transformation matrix T(u), which varies with the +Directrix parameter u.
  • +
+

NOTE  The +geometric shape of the solid is not dependent upon the curve +parameterization; the volume depends upon the area swept and the +length of the Directrix.

+
+

The attributes of the Cartesian Transformation Operator (as +shown above) should apply to the Position coordinate +system, in which the profile is inserted. The Directrix +and the ReferenceSurface are positioned within the 3D +Position coordinate system.

+ +
+NOTE  Corresponding ISO 10303-42 entity: surface_curve_swept_area_solid. Please refer to ISO 10303-42 ed.2:1999, p. 274 for the definition in the international standard. +
+
+HISTORY  New entity in IFC2x2. +
+ +

Informal propositions:

+
    +
  1. The SweptArea shall lie in the plane z = 0.
  2. +
  3. The Directrix shall lie on the +ReferenceSurface.
  4. +
+ +
" +5375;IfcFixedReferenceSweptAreaSolid;" +

A fixed reference swept area solid is a type of swept area solid +which is the result of sweeping a surface along a +Directrix. The orientation of the curve during the +sweeping operation is controlled by the FixedReference +direction.

+

The SweptArea is required to be a curve bounded surface +lying in the plane z = 0 and this is swept along the +Directrix in such a way that the origin of the local +coordinate system used to define the SweptArea is on the +Directrix and the local X axis is in the direction of the +projection of FixedReference onto the normal plane to the +directrix at this point. The resulting solid has the property that +the cross section of the surface by the normal plane to the +Directrix at any point is a copy of the +SweptArea.

+
+

NOTE The swept face +is given by IfcProfileDef (or subtypes), the profile +definition is given within a 2D coordinate system, which is +inserted into the XY plane of the Position coordinate +system inherited from the supertype +IfcSweptAreaSolid.

+
+

The orientation of the SweptArea as it sweeps along the +Directrix is precisely defined by a +CartesianTransformationOperator3d with attributes:

+
    +
  • LocalOrigin as point (0; 0; 0),
  • +
  • Axis1 as the FixedReference.
  • +
  • Axis3 as the direction of the tangent vector t +at the point of the Directrix with parameter +u.
  • +
+

The remaining attributes are defaulted to define a corresponding +transformation matrix T(u), which varies with the +Directrix parameter u.

+
+

NOTE The geometric shape of the +solid is not dependent upon the curve parameterization; the volume +depends upon the area swept and the length of the +Directrix.

+
+

The attributes of the Cartesian Transformation Operator (as +shown above) should apply to the Position coordinate +system, in which the profile is inserted. The Directrix +and the FixedReference are positioned within the 3D +Position coordinate system.

+ +
+NOTE The entity is defined in analogy to the ISO 10303-42 entity: fixed_reference_swept_surface. Please refer to ISO/DIS 10303-42:2003(E) p. 103. +
+
+HISTORY New entity in IFC2x4. +
+ +

Informal propositions:

+
    +
  1. The SweptArea shall lie in the plane z = 0.
  2. +
  3. The FixedReference shall not be parallel to a tangent +vector to the directrix at any point along this curve.
  4. +
  5. The Directrix curve shall be tangent continuous.
  6. +
+ +
" +5380;IfcCsgSolid;" +

+ Definition from ISO/CD 10303-42:1992: A solid + represented as a CSG model is defined by a collection of + so-called primitive solids, combined using regularized + Boolean operations. The allowed operations are + intersection, union, and difference. As a special case a + CSG solid can also consists of a single CSG primitive. +

+

+ A CSG solid requires two kinds of information for its + complete definition: geometric and structural. +

+
    +
  • The geometric information is conveyed by solid models. + These typically primitive volumes such as cylinders, wedges + and extrusions, but can include general B-Rep models. Solid + models can also be half space solids. +
  • +
  • The structural information is in a tree (strictly an + acyclic directed graph) of Boolean result and CSG solids, + which represent a ‘recipe’ for building the + solid. The terminal nodes are the geometric primitives and + other solids. Every CSG solid has precisely one Boolean + result associated with it which is the root of the tree + that defines the solid. (There may be further Boolean + results within the tree as operands). The significance of a + CSG solid entity is that the solid defined by the + associated tree is thus identified as a significant object + itself, and in this way it is distinguished from other + Boolean result entities representing intermediate results + during the construction process. +
  • +
+

+ Definition from IAI: The following primitive volumes + can be parts of the CSG tree: solid models, i.e. faceted + B-Rep (IfcFacetedBrep, IfcFacetedBrepWithVoids), + swept area solid (IfcExtrudedAreaSolid, + IfcRevolvedAreaSolid, IfcSurfaceCurveSweptAreaSolid), + swept disk solids (IfcSweptDiskSolid), half space + solids (IfcHalfSpaceSolid and subtypes), and CSG + primitives (subtypes of IfcCsgPrimitive3D). +

+
+NOTE Corresponding ISO 10303-42 entity: csg_solid, please refer to ISO/IS 10303-42:1994, p.174 for the final definition of the formal standard. +
+
+HISTORY New class in IFC Release 1.5.1 +
+ +
" +5385;IfcCsgPrimitive3D;" + +

IfcCsgPrimitive3D is an abstract supertype of all three dimensional primitives used as either tree root item, or as Boolean results within a CSG solid model. All 3D CSG primitives are defined within a three-dimensional placement coordinate system.

+ +
+NOTEÿ No directly corresponding ISO 10303-42 entity, the select type primitive_3d covers the same individual 3D CSG primitives, the position attribute has been added to apply equally to all subtypes. Please refer to ISO/IS 10303-42:1994, p. 234 for the final definition of the formal standard. +
+ +
+HISTORYÿ New entity in IFC2x3. +
+ +
" +5393;IfcBlock;" +

The IfcBlock is a Construction Solid Geometry (CSG) 3D +primitive. It is defined by a position and a positve distance along +the three orthogonal axes. The inherited Position +attribute has the IfcAxisPlacement3D type and +provides:

+
    +
  • SELF\IfcCsgPrimitive3D.Position: The location and +orientation of the axis system for the primitive.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Location: The block +has one vertex at location and the edges are aligned with the +placement axes in the positive sense.
  • +
+

The XLength, YLength, and ZLength +attributes define the size of the IfcBlock along the three +axes.

+

The following definitions from ISO 10303-42 apply:

+
+

A block is a solid +rectangular parallelepiped, defined with a location and placement +coordinate system. The block is specified by the positive lengths +x, y, and z along the axes of the placement coordinate system, and +has one vertex at the origin of the placement coordinate +system.

+ +

Figure 250 illustrates geometric parameters of a block where the block positioned within its own placement coordinate system. The values for XLength, YLength, and ZLength are applied to the positive direction of the X, Y, and Z axis.

+ + + + +

Figure 250 — Block geometry

+ +
+NOTE  Corresponding ISO 10303-42 entity: block, the position attribute has been promoted to the immediate supertype IfcCsgPrimitive3D. Please refer to ISO 10303-42:1994, p. 244 for the definition in the international standard. +
+
+HISTORY  New entity in IFC2x3. +
+ +

Texture use definition

+

On each side face, textures are aligned facing upright. On the +top and bottom faces, textures are aligned facing front-to-back. +Textures are stretched or repeated to the extent of each face +according to RepeatS and RepeatT.

+ +

Figure 251 illustrates default texture mapping with a clamped texture (RepeatS=False and RepeatT=False). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis points back to the left, and the Z axis points up.

+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SideNormalOrigin XOrigin YOrigin ZS AxisT Axis
Left-X0+YLength0-Y+Z
Right+X0+YLength0+Y+Z
Front+X000+X+Z
Back+Y+XLength+YLength0-X+Z
Bottom-Z+XLength00-X+Y
Top+Z00+ZLength+X+Y
+

Figure 251 — Block textures

+ +" +5397;IfcRectangularPyramid;" +

The IfcRectangularPyramid is a Construction Solid +Geometry (CSG) 3D primitive. It is a solid with a rectangular base and +a point called apex as the top. The tapers from the base to the +top. The axis from the center of the base to the apex is +perpendicular to the base. The inherited Position +attribute defines the IfcAxisPlacement3D and provides the +location and orientation of the pyramid:

+
    +
  • SELF\IfcCsgPrimitive3D.Position: The location and +orientation of the axis system for the primitive. 
  • +
  • SELF\IfcCsgPrimitive3D.Position.Location: The center +of the circular area being the bottom face of the cone.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Position[3]: The +z-axis of the inherited placement coordinate system provides the +center axis of the IfcRightCircularCone, and the apex is +at the Height value applied to the positive direction of +the z-axis. The BottomRadius defines the circular base at +the xy-plane of the placement coordinate system.
  • +
+ +

As shown in Figure 260, the pyramid is positioned within its own placement coordinate system. The origin is the center of the bottom rectangle, that lies in the XY plane. The apex lies on the positive z axis at [0, 0, Height].

+ + + + +

Figure 260 — Rectangular pyramid geometry

+ +
+NOTE  Corresponding ISO 10303 entity: right_circular_cone, the position attribute has been promoted to the immediate supertype IfcCsgPrimitive3D. No semi_angle attribute, and the radius defines the bottom radius, since only a non-truncated cone is in scope. Please refer to ISO/IS 10303-42:1994, p. 176 for the final definition of the formal standard. +
+
+HISTORY  New entity in IFC2x3 +
+ +

Texture use definition

+ +

On each triangular side face, textures are aligned facing upright. +Textures are stretched or repeated to the extent of the base of each face according to RepeatS. +Textures are stretched or repeated towards the top point according to Repeat T, +where the top point has coordinates of (0.5,1.0) if RepeatT is False.

+ +

On the bottom face, textures are aligned facing front-to-back.

+ +

Figure 261 illustrates default texture mapping with a clamped texture (RepeatS=False and RepeatT=False). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis +points back to the left, and the Z axis points up.

+ + + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SideNormalOrigin XOrigin YOrigin ZS AxisT Axis
Left-X0+YLength0-Y(towards top point)
Right+X0+YLength0+Y(towards top point)
Front+X000+X(towards top point)
Back+Y+XLength+YLength0-X(towards top point)
Bottom-Z+XLength00-X+Y
+

Figure 261 — Right circular cone textures

+ +
" +5401;IfcRightCircularCylinder;" +

The IfcRightCircularCylinder is a Construction Solid +Geometry (CSG) 3D primitive. It is a solid with a circular base and +top. The cylindrical surface between if formed by points at a fixed +distance from the axis of the cylinder. The inherited +Position attribute defines the IfcAxisPlacement3D +and provides:

+
    +
  • SELF\IfcCsgPrimitive3D.Position: The location and +orientation of the axis system for the primitive.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Location: The center +of the circular area being the bottom face of the cylinder.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Position[3]: The z +axis provides the center axis and the height is measured from the +origin along the positive direction of the z axis.
  • +
+

The following definitions from ISO 10303-42 apply:

+
+

A right circular +cylinder is a CSG primitive in the form of a solid cylinder of +finite height. It is defined by an axis point at the centre of one +planar circular face, an axis, a height, and a radius. The faces +are perpendicular to the axis and are circular discs with the +specified radius. The height is the distance from the first +circular face centre in the positive direction of the axis to the +second circular face centre.

+
+ +

Figure 266 illustrates geometric parameters of the cylinder. The cylinder is positioned within its own placement coordiante system. The origin is the center of the bottom circular disk, that lies in the XY plane. The center of the top circular disk is on the positive z axis at [0, 0, Height].

+ + + + +

Figure 266 — Right circular cylinder geometry

+ +
+NOTE  Corresponding ISO 10303 entity: right_circular_cyclinder, the position attribute has been promoted to the immediate supertype IfcCsgPrimitive3D. Please refer to ISO/IS 10303-42:1994, p. 177 for the definition in the international standard. +
+
+HISTORY  New entity in IFC2x3. +
+ +

Texture use definition

+

On the circular side, textures are aligned facing upright with +origin at the back (+Y direction) revolving counter-clockwise. +Textures are stretched or repeated to the extent of the +circumference according to RepeatS. Textures are stretched or +repeated to the extent of the Height according to +RepeatT.

+

On the top and bottom faces, textures are aligned facing +front-to-back, with the center of the circle aligned to the center +of the texture.

+ +

Figure 267 illustrates default texture mapping with a clamped texture (RepeatS=False and RepeatT=False). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis +points back to the left, and the Z axis points up.

+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SideNormalOrigin XOrigin YOrigin ZS AxisT Axis
Side-Y0+Radius0-X+Z
Bottom-Z000-X+Y
Top+Z00+Height+X+Y
+

Figure 267 — Right circular cylinder textures

+ +
" +5404;IfcRightCircularCone;" +

The IfcRightCircularCone is a Construction Solid +Geometry (CSG) 3D primitive. It is a solid with a circular base and +a point called apex as the top. The tapers from the base to the +top. The axis from the center of the circular base to the apex is +perpendicular to the base. The inherited Position +attribute defines the IfcAxisPlacement3D and provides the +location and orientation of the cone:

+
    +
  • SELF\IfcCsgPrimitive3D.Position: The location and +orientation of the axis system for the primitive. 
  • +
  • SELF\IfcCsgPrimitive3D.Position.Location: The center +of the circular area being the bottom face of the cone.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Position[3]: The +z-axis of the inherited placement coordinate system provides the +center axis of the IfcRightCircularCone, and the apex is +at the Height value applied to the positive direction of +the z-axis. The BottomRadius defines the circular base at +the xy-plane of the placement coordinate system.
  • +
+ +

Figure 264 illustrates geometric parameters of the cone. The cone is positioned within its own placement coordinate system. The origin is the center of the bottom circular disk, that lies in the XY plane. The apex lies on the positive z axis at [0, 0, Height].

+ + + + +

Figure 264 — Right circular cone geometry

+ +
+NOTE  Corresponding ISO 10303 entity: right_circular_cone, the position attribute has been promoted to the immediate supertype IfcCsgPrimitive3D. No semi_angle attribute, and the radius defines the bottom radius, since only a non-truncated cone is in scope. Please refer to ISO/IS 10303-42:1994, p. 176 for the final definition of the formal standard. +
+
+HISTORY  New entity in IFC2x3 +
+ +

Texture use definition

+

On the circular side, textures are aligned facing upright with +origin at the back (+Y direction) revolving counter-clockwise. +Textures are stretched or repeated to the extent of the base +circumference according to RepeatS. Textures are compressed +linearly going upwards towards the top point according to +RepeatT.

+

On the bottom face, textures are aligned facing front-to-back, +with the center of the circle aligned to the center of the +texture.

+ +

Figure 265 illustrates default texture mapping with a clamped texture (RepeatS=False and RepeatT=False). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis points back to the left, and the Z axis points up.

+ + + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SideNormalOrigin XOrigin YOrigin ZS AxisT Axis
Side-Y0+Radius0-X(towards top point)
Bottom-Z000-X+Y
+

Figure 265 — Right circular cone textures

+ +
" +5407;IfcSphere;" +

The IfcSphere is a Construction Solid Geometry (CSG) 3D +primitive. It is a solid where all points at the surface have the +same distance from the center point. The inherited +Position attribute defines the IfcAxisPlacement3D +and provides:

+
    +
  • SELF\IfcCsgPrimitive3D.Position: The location and +orientation of the axis system for the primitive. 
  • +
  • SELF\IfcCsgPrimitive3D.Position.Location: The center +of the sphere.
  • +
  • SELF\IfcCsgPrimitive3D.Position.Position[3]: The z +axis points at its positve direction towards the north pole, and by +its negative directions towards the south pole.
  • +
+

The following definitions from ISO 10303-42 apply:

+
+

A sphere is a CSG +primitive with a spherical shape defined by a centre and a +radius.

+
+ +

Figure 270 illustrates geometric parameters of the sphere. The sphere is positioned within its own placement coordiante system. The origin is the center of the sphere.

+ + + + +

Figure 270 — Sphere geometry

+ +
+NOTE  Corresponding STEP entity: sphere, the position attribute, including the centre point,  has been promoted to the immediate supertype IfcCsgPrimitive3D. Please refer to ISO/IS 10303-42:1994, p. 175 for the final definition of the formal standard. +
+
+HISTORY  New entity in IFC2x3. +
+ +

Texture Use Definition

+

Textures are aligned facing upright with origin at the back (+Y direction) revolving counter-clockwise. Textures are stretched or repeated to the extent of the circumference at the equator according to RepeatS and RepeatT.

+ +

Figure 271 illustrates default texture mapping with a clamped texture (RepeatS=False and RepeatT=False). The image on the left shows the texture where the S axis points to the right and the T axis points up. The image on the right shows the texture applied to the geometry where the X axis points back to the right, the Y axis points back to the left, and the Z axis points up.

+ + + + + +
+ + + + + + + + + + + + + + + + + + + +
SideNormalOrigin XOrigin YOrigin ZS AxisT Axis
Side-Y0+Radius0(-X, then curving counter-clockwise)(+Y, then curving towards top)
+

Figure 271 — Sphere textures

+ +
" +5409;IfcSweptDiskSolid;" +

Definition from ISO 10303-42:2002: A swept +disk solid is the solid produced by sweeping a circular disk +along a three dimensional curve. During the sweeping operation +the normal to the plane of the circular disk is in the direction +of the tangent to the directrix curve and the center of the disk +lies on the directrix. The circular disk may, optionally, have a +central hole, in this case the resulting solid has a through +hole, or, an internal void when the directrix forms a close +curve.

+

The StartParam and +EndParam parameter are optional, if not provided they +default to the start and end of the Directrix. Only if the +Directrix is given by a bounded or by a closed curve, it +is permissible to omit the values of StartParam and +EndParam.

+

If the transitions between consecutive segments of the +Directrix are not tangent continuous, the resulting solid +is created by a miter at half angle between the two segments. +Informal proposition restricts the permissible angle between two +non-tangent continuous segments.

+ +

Figure 272 illustrates an example.

+
    +
  • Directrix given as IfcCompositeCurve being +tangent continuous between its segments
  • +
  • Directrix being a bounded and open curve
  • +
  • No StartParam and EndParam are provided, start +and end default to start and end of the bounded curve of the +Directrix
  • +
+ +
NOTE  Although the example shows a Directrix as a composite curve on a planar reference surface, the definition of IfcSweptDiskSolid is not restricted to be based on planer curves. However view definitions or implementer agreements may provide restrictions.
+ + + + +

Figure 272 — Swept disk solid geometry

+ +
+NOTE  Corresponding ISO 10303-42 entity: swept_disk_solid. Please refer to ISO/FDIS 10303-42:2002, p. 282 for the definition of the formal standard. +
+
+HISTORY  New entity in IFC Release 2x2. +
+
+IFC2x4 CHANGE  The attribute StartParam and EndParam have been made optional. +
+ +

Informal proposition

+
    +
  1. If the Directrix curve definition is not tangent +continuous, the transition between the segments has to be within +an acceptable limit of tangent discontinuity. Very sharp edges +may result in nearly impossible miter. Implementer agreements may +define acceptable limits for tangent discontinuity.
  2. +
  3. The segments of the Directrix shall be long enough to +apply the Radius. In case of an arc segment forming part +of the Directrix ,its radius shall be greater then the +disk Radius
  4. +
  5. The Directrix shall not be based on an intersecting +curve.
  6. +
+
" +5419;IfcSweptDiskSolidPolygonal;" +

The IfcSweptDiskSolidPolygonal is a IfcSweptDiskSolid where the Directrix is restricted to be provided by an IfcPolyline only. An optional FilletRadius attribute can be asserted, it is then applied as a fillet to all transitions between the segments of the IfcPolyline.

+ +
+HISTORY New entity in IFC2x4. +
+ +

Informal proposition

+
    +
  1. The FilletRadius, if provided, has to be smaller then +or equal to the length of the start and end segment of the +IfcPolyline, and smaller then or equal to one half of the +lenght of the shortest inner segment.
  2. +
+
" +5423;IfcSectionedSpine;" +

Definition from ISO 10303-42:1999: A sectioned +spine is a representation of the shape of a three dimensional +object composed of a spine curve and a number of planar cross +sections. The shape is defined between the first element of cross +sections and the last element of this set.

+
+

NOTE A sectioned spine may be used to represent a surface or a +solid but the interpolation of the shape between the +cross-sections is not defined. For the representation of a solid +all cross-sections are closed curves.

+
+

A sectioned spine +(IfcSectionedSpine) is a representation of the shape of a +three dimensional object composed by a number of planar cross +sections, and a spine curve. The shape is defined between the +first element of cross sections and the last element of the cross +sections. A sectioned spine may be used to represent a surface or +a solid but the interpolation of the shape between the cross +sections is not defined.

+

For the representation of a solid all cross sections are +areas. For representation of a surface all cross sections are +curves. The cross sections are defined as profiles, whereas the +consecutive profiles may be derived by a transformation of the +start profile or the previous consecutive profile.

+

The spine curve shall be of type IfcCompositeCurve, +each of its segments (IfcCompositeCurveSegment) shall +correspond to the part between exactly two consecutive +cross-sections.

+ +
+NOTE: Corresponding ISO 10303 entity: sectioned spine. Please refer to ISO/DIS 10303-42-ed2:1999, p. 282 for the definition of the formal standard. The cross sections are defined in IFC as IfcProfileDef. The position coordinate systems are added. +
+
+HISTORY New entity in IFC Release 2x. +
+ +

Figure 268 illustrates an example of an IfcSectionedSpine.

+
    +
  • The SpineCurve is given by an IfcCompositeCurve with two Segments. The Segments[1] has a ParentCurve of type IfcPolyline and a Transition = CONTSAMEGRADIENT. The Segments[2] has a ParentCurve of type +IfcTrimmedCurve and a Transition = DISCONTINUOUS.
  • +
  • Each CrossSectionPosition lies at a start or end point of the Segments.
  • +
  • Each CrossSections are inserted by the CrossSectionPositions. The first two cross sections are of +type IfcRectangleProfileDef, the third is of type IfcDerivedProfileDef.
  • +
+ + + + +

Figure 268 — Sectioned spine geometry

+ + +

Figure 269 illustrates the final result of the IfcSectionedSpine. The body (shown transparently) is not fully defined by the +exchange definition.

+ + + + +

Figure 269 — Sectioned spine result

+ +

Informal propositions

+
    +
  1. none of the cross sections, after being placed by the cross section positions, shall intersect
  2. +
  3. none of the cross sections, after being placed by the cross section positions, shall lie in the same plane
  4. +
  5. the local origin of each cross section position shall lie at the beginning or end of a composite curve segment.
  6. +
+
" +5431;IfcGeometricSet;" + +

Definition from ISO/CD 10303-42:1992: This entity is intended for the transfer of models when a topological structure is not available.

+ +

The IfcGeometricSet is used for the exchange of shape representations consisting of (2D or 3D) points, curves, and/or surfaces, which do not have a topological structure (such as connected face sets or shells) and are not solid models (such as swept solids, CSG or Brep)

+ +
+NOTE: Corresponding ISO 10303-42 entity: geometric_set. The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. Please refer to ISO/IS 10303-42:1994, p. 190 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5436;IfcGeometricCurveSet;" + +

Definition from ISO/CD 10303-42:1992: A geometric curve set is a collection of two or three dimensional points and curves.

+ +

The IfcGeometricCurveSet is used for the exchange of shape representations consisting of (2D or 3D) points and curves only.

+ +
+NOTE: Corresponding ISO 10303-42 entity: geometric_set. Please refer to ISO/IS 10303-42:1994, p. 190 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x2. +
+ +
" +5442;IfcFaceBasedSurfaceModel;" + +

Definition from ISO/CD 10303-42:1992: A face based surface model is described by a set of connected face sets of dimensionality 2. The connected face sets shall not intersect except at edges and vertices, except that a face in one connected face set may overlap a face in another connected face set, provided the face boundaries are identical. There shall be at least one connected face set.

+ +

A connected face set may exist independently of a surface model.

+ +
+NOTE Corresponding STEP entity: face_based_surface_model. Please refer to ISO/IS 10303-42:1994, p. 188 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +

Informal propositions:

+
    +
  1. The connected face sets shall not overlap or intersect except at common faces, edges or vertices.
  2. +
  3. The fbsm faces have dimensionality 2.
  4. +
+ +
" +5445;IfcShellBasedSurfaceModel;" + +

Definition from ISO/CD 10303-42:1992: A shell based surface model is described by a set of open or closed shells of dimensionality 2. The shells shall not intersect except at edges and vertices. In particular, distinct faces may not intersect. A complete face of one shell may be shared with another shell. Coincident portions of shells shall both reference the same faces, edges and vertices defining the coincident region. There shall be at least one shell.

+ +

A shell may exist independently of a surface model.

+ +
+NOTE Corresponding ISO 10303-42 entity: shell_based_surface_model. Please refer to ISO/IS 10303-42:1994, p. 187 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +

Informal propositions

+
    +
  1. The dimensionality of the shell based surface model is 2.
  2. +
  3. The shells shall not overlap or intersect except at common faces, edges or vertices.
  4. +
+ +
" +5448;IfcBooleanClippingResult;" + +

A clipping result is defined as a special subtype of the general Boolean result (IfcBooleanResult). It constrains the operands and the operator of the Boolean result.

+ +

A clipping result is the Boolean difference between a solid (restricted to swept area solid) and a half space solid, whereas more than one difference operation can be applied to the Boolean result.

+ +
+NOTE The IfcBooleanClippingResult is defined as a special case of the boolean_result, as defined in ISO 10303-42:1994, p. 175. It has been added to apply further constraints to the CSG representation type. +
+
+HISTORY New entity in IFC Release 2.x. +
+ +
" +5468;IfcAxis2Placement2D;" + +

Definition from ISO/CD 10303-42:1992: The location and orientation in two dimensional space of two mutually perpendicular axes. An axis2_placement_2d is defined in terms of a point, (inherited from the placement supertype), and an axis. It can be used to locate and originate an object in two dimensional space and to define a placement coordinate system. The class includes a point which forms the origin of the placement coordinate system. A direction vector is required to complete the definition of the placement coordinate system. The reference direction defines the placement X axis direction, the placement Y axis is derived from this.

+ +

If the RefDirection attribute is not given, the placement defaults to P[1] (x-axis) as [1.,0.] and P[2] (y-axis) as [0.,1.].

+ +
+NOTE  Corresponding ISO 10303 name: axis2_placement_2d, please refer to ISO/IS 10303-42:1994, p. 28 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC Release 1.5. +
+ +

Figure 275 illustrates the definition of the IfcAxis2Placement2D within the two-dimensional coordinate system.

+ + + +

Figure 275 — Axis2 placement 2D

+ +
" +5473;IfcPlacement;" + +

Definition from ISO/CD 10303-42:1992: A placement entity defines the local environment for the definition of a geometry item. It locates the item to be defined and, in the case of the axis placement subtypes, gives its orientation.

+ +

Additional definition from ISO/WD SC4/WG12/N071 Part42.2 geometry_schema: A placement locates a geometric item with respect to the coordinate system of its geometric context.

+ +

IfcPlacement is an abstract supertype not to be directly instantiated, whereas the ISO 10303-42 entity placement can be instantiated to define a placement without orientation. The derived attribute Dim has been added, see also note at IfcGeometricRepresentationItem.

+ +
+NOTE: Corresponding ISO 10303 entity: placement. Please refer to ISO/IS 10303-42:1994, p. 27 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 1.0 +
+ +
" +5479;IfcGeometricRepresentationItem;" + +

Definition from ISO/CD 10303-43:1992: An geometric representation item is a representation item that has the additional meaning of having geometric position or orientation or both. This meaning is present by virtue of:

+
    +
  • being a Cartesian point or a direction
  • +
  • referencing directly a Cartesian point or direction
  • +
  • referencing indirectly a Cartesian point or direction
  • +
+

An indirect reference to a Cartesian point or direction means that a given geometric item references the Cartesian point or direction through one or more intervening geometry or topology items.

+ +
+EXAMPLE: Consider a circle. It gains its geometric position and orientation by virtue of a reference to axis2_placement (IfcAxis2Placement) that is turn references a cartesian_point (IfcCartesianPoint) and several directions (IfcDirection). +
+ +
+EXAMPLE: Consider a manifold brep. A manifold_solid_brep (IfcManifoldSolidBrep) is a geometric_representation_item (IfcGeometricRepresentationItem) that through several layers of topological_representation_item's (IfcTopologicalRepresentationItem) references poly loops (IfcPolyLoop). Through additional intervening entities poly loops reference cartesian_point's (IfcCartesianPoint). +
+ +

The derivation of the dimensionality of the IfcGeometricRepresentationItem is different to ISO 10303; there is a specific derived attribute at each class that defines the dimensionality, whereas ISO 10303 does it for the representation_context and requires all geometric_representation_item's to have the same dimensionality therein.

+ +

The definition of swept area solids as geometric representation items is different to ISO 10303; it is based on a set of predefined profiles (or cross sections), that is, a set of parameterized geometric primitives widely supported in the industry. Those profiles are used to create volumes through extrusion, revolution and cross section based sweep operations.

+ +
+NOTE: Corresponding ISO 10303 entity: geometric_representation_item. Please refer to ISO/IS 10303-42:1994, p. 22 for the final definition of the formal standard. The following changes have been made: It does not inherit from ISO/IS 10303-43:1994 entity representation_item. The derived attribute Dim is demoted to the appropriate subtypes. The WR1 has not been incorporated. Not all subtypes that are in ISO/IS 10303-42:1994 have been added to the current IFC Release. +
+ +
+HISTORY: New entity in IFC Release 1.5 +
+ +
" +5496;IfcRepresentationItem;" + +

Definition from ISO/CD +10303-43:1992: A representation item is an element of +product data that participates in one or more representations or +contributes to the definition of another representation item. A +representation item contributes to the definition of another +representation item when it is referenced by that representation +item.

+ +
+NOTE  Corresponding entity in ISO 10303-43:1994: representation_item. Please refer to ISO/IS 10303-43:1994, for the final definition of the formal standard. The following changes have been made: The attribute 'name' and the WR1 have not been incorporated. +
+ +

The IfcRepresentationItem is used within an IfcRepresentation (directly or indirectly through other IfcRepresentationItem's) to represent an IfcProductRepresentation. Most commonly these IfcRepresentationItem's are geometric or topological representation items, that can (but not need to) have presentation style infomation assigned.

+ +
+NOTE  The assignment of a style is only applicable +to the subtypes IfcGeometricRepresentationItem, IfcMappedItem and some selected subtypes of IfcTopologicalRepresentationItem (IfcVertexPoint, IfcEdgeCurve, IfcFaceSurface). +
+ +

In case that presentation style information is applied, it can be either applied by an IfcStyledItem, or by an assignment to an IfcPresentationLayerWithStyle. If both are present, and both style assignments include the same subtype of IfcPresentationStyle, then the style assigned by IfcStyledItem takes priority.

+ +

Figure 281 shows an instance diagram explaining the use of IfcStyledItem and IfcPresentationLayerWithStyle to apply presentation styles.

+
+EXAMPLE  The assignment of style information by a styled item and a presentation layer with style. Since the presentation styles are different, IfcCurveStyle and IfcSurfaceStyle, both are applied to the geometric representation item. +
+ + + + +

Figure 281 — Representation item style

+ +

Figure 282 shows in instance diagram explaining the override of IfcPresentationLayerWithStyle by IfcStyledItem to apply presentation styles.

+
+EXAMPLE  The assignment of style information by a styled item and a presentation layer with style. Since the presentation styles for curve style are aprovided by both, the IfcCurveStyle provided by the IfcStyledItem overrides the IfcCurveStyle provided by the IfcPresentationLayerWithStyle +
+ + + + +

Figure 282 — Representation item style override

+ +
+HISTORY  New entity in IFC Release 2x. +
+
+IFC2x3 CHANGE  The inverse attributes StyledByItem and LayerAssignments have been added. Upward compatibility for file based exchange is guaranteed. +
+ +
" +5503;IfcMappedItem;" +

Definition from ISO/CD 10303-43:1992: A mapped item is the use of an existing representation (the mapping source - mapped representation) as a representation item in a second representation.

+ +
+NOTE: A mapped item is a subtype of representation item. It enables a representation to be used as a representation item in one or more other representations. The mapped item allows for the definition of a representation using other representations.

+
+ +

The IfcMappedItem is the inserted instance of a source definition (to be compared with a +block / shared cell / macro definition). The instance is inserted by applying a Cartesian transformation operator as the MappingTarget.

+ +
+EXAMPLE  An IfcMappedItem can reuse other mapped items (ako nested blocks), doing so the IfcRepresentationMap is based on an IfcShapeRepresentation including one or more IfcMappedItem's. +
+ +
+NOTE   Corresponding ISO 10303 entity: mapped_item. Please refer to ISO/IS +10303-43:1994, for the final definition of the formal standard. The definition of mapping_target (MappingTarget) has been restricted to be of the type cartesian_transformation_operator +(IfcCartesianTransformationOperator). +
+ +
+HISTORY  New entity in IFC Release 2x. +
+ +

Informal Propositions

+
    +
  1. A mapped item shall not be self-defining by participating in the definition of the representation being mapped.
  2. +
  3. The dimensionality of the mapping source and the mapping target has to be the same, if the mapping source is a geometric representation item.
  4. +
+ +
" +5506;IfcRepresentationMap;" + +

Definition from ISO/CD 10303-43:1992: A representation map is the identification of a representation and a representation item in that representation for the purpose of mapping. The representation item defines the origin of the mapping. The representation map is used as the source of a mapping by a mapped item.

+ +
+NOTE  Corresponding ISO 10303 entity: representation_map. Please refer to ISO/IS 10303-43:1994, for the final definition of the formal standard. The following changes have been made: The mapping_origin (MappingOrigin) is constrained to be of type axis2_placement (IfcAxis2Placement).

+
+ +

An IfcRepresentationMap defines the base definition (also referred to as block, cell or macro) called MappedRepresentation within the MappingOrigin. The MappingOrigin defines the coordinate system in which the MappedRepresentation is defined.

+ +

The RepresentationMap is used through an IfcMappeditem in one or several IfcShapeRepresentation's. An Cartesian transformation operator can be applied to transform the MappedRepresentation into the placement coordinate system of the shape representation. The transformation of the representation map is restricted to be a Cartesian transformation mapping (translation, rotation, mirroring and scaling).

+ +
+NOTE  The definition of a mapping which is used to specify a new representation item comprises a representation map and a mapped item entity. Without both entities, the mapping is not fully defined. Two entities are specified to allow the same source representation to be mapped into multiple new representations. +
+ +
+HISTORY  New entity in IFC Release 2x. +
+ +
" +5511;IfcCartesianTransformationOperator;" + +

Definition from ISO/CD 10303-42:1992: A Cartesian transformation operator defines a geometric transformation composed of translation, rotation, mirroring and uniform scaling. The list of normalized vectors u defines the columns of an orthogonal matrix T. These vectors are computed, by the base axis function, from the direction attributes axis1, axis2 and, in Cartesian transformation operator 3d, axis3. If |T|= -1, the transformation includes mirroring. The local origin point A, the scale value S and the matrix T together define a transformation.

+ +

The transformation for a point with position vector P is defined by

+ +
+
+

P -> A + STP

+

The transformation for a direction d is defined by

+
+
+

d -> Td

+

The transformation for a vector with orientation d and magnitude k is + defined by

+
+
+

d -> Td, and

+

k -> Sk

+

For those entities whose attributes include an axis2 placement, the + transformation is applied, after the derivation, to the derived attributes p + defining the placement coordinate directions. For a transformed surface, the + direction of the surface normal at any point is obtained by transforming the + normal, at the corresponding point, to the original surface. For geometric + entities with attributes (such as the radius of a circle) which have the + dimensionality of length, the values will be multiplied by S.

+

For curves on surface the p curve.reference to curve will be unaffected + by any transformation. The Cartesian transformation operator shall only be + applied to geometry defined in a consistent system of units with the same units + on each axis. With all optional attributes omitted, the transformation defaults + to the identity transformation. The Cartesian transformation operator shall + only be instantiated as one of its subtypes.

+ +
+NOTE: Corresponding ISO 10303 entity: cartesian_transformation_operator, please refer to ISO/IS 10303-42:1994, p. 32 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5521;IfcCartesianTransformationOperator2D;" + +

Definition from ISO/CD 10303-42:1992: A Cartesian transformation operator 2d defines a geometric transformation in two-dimensional space composed of translation, rotation, mirroring and uniform scaling. The list of normalized vectors u defines the columns of an orthogonal matrix T. These vectors are computed from the direction attributes axis1 and axis2 by the base axis function. If |T|= -1, the transformation includes mirroring.

+ +
+NOTE: Corresponding ISO 10303 entity : cartesian_transformation_operator_2d, please refer to ISO/IS 10303-42:1994, p. 36 for the final definition of the formal standard. +
+
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5527;IfcCartesianTransformationOperator2DnonUniform;" + +

A Cartesian transformation operator 2d non uniform defines a geometric transformation in two-dimensional space composed of translation, rotation, mirroring and non uniform scaling. Non uniform scaling is given by two different scaling factors:

+
    +
  • SELF\IfcCartesianTransformationOperator.Scale: the x axis scale factor
  • +
  • Scale2: the y axis scale factor
  • +
+

If the Scale factor (at supertype IfcCartesianTransformationOperator) is omitted, it defaults to 1.0. If the Scale2 factor is omitted, it defaults to the value of Scale (the x axis scale factor).

+ +
+NOTE: The scale factor (Scl) defined at the supertype IfcCartesianTransformationOperator is used to express the calculated Scale factor (normally x axis scale factor). +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5531;IfcDirection;" + +

Definition from ISO/CD 10303-42:1992: This entity defines a general direction vector in two or three dimensional space. The actual magnitudes of the components have no effect upon the direction being defined, only the ratios X:Y:Z or X:Y are significant.

+ +
+NOTE: The components of this entity are not normalized. If a unit vector is required it should be normalized before use. +
+ +
+NOTE: Corresponding ISO 10303 entity: direction. Please refer to ISO/IS 10303-42:1994, p.26 for the final definition of the formal standard. The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). +
+ +
+HISTORY: New entity in IFC Release 1.0 +
+ +
" +5534;IfcCartesianTransformationOperator3D;" + +

Definition from ISO/CD 10303-42:1992: A Cartesian transformation operator 3d defines a geometric transformation in three-dimensional space composed of translation, rotation, mirroring and uniform scaling. The list of normalized vectors u defines the columns of an orthogonal matrix T. These vectors are computed from the direction attributes axis1, axis2 and axis3 by the base axis function. If |T|= -1, the transformation includes mirroring.

+ +
+NOTE: Corresponding ISO 10303 entity: cartesian_transformation_operator_3d, please refer to ISO/IS 10303-42:1994, p. 33 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5542;IfcCartesianTransformationOperator3DnonUniform;" + +

A Cartesian transformation operator 3d non uniform defines a geometric transformation in three-dimensional space composed of translation, rotation, mirroring and non uniform scaling. Non uniform scaling is given by three different scaling factors:

+ +
    +
  • SELF\IfcCartesianTransformationOperator.Scale: the x axis scale factor
  • +
  • Scale2: the y axis scale factor
  • +
  • Scale3: the z axis scale factor
  • +
+ +

If the Scale factor (at supertype IfcCartesianTransformationOperator) is omitted, it defaults to 1.0. If the Scale2 or the Scale3 factor is omitted, it defaults to the value of Scale (the x axis scale factor).

+ +
+NOTE: The scale factor (Scl) defined at the supertype IfcCartesianTransformationOperator is used to express the calculated Scale factor (normally x axis scale factor). +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5549;IfcCartesianPoint;" + +

Definition from ISO/CD 10303-42:1992: A point defined by its coordinates in a two or three dimensional rectangular Cartesian coordinate system, or in a two dimensional parameter space. The entity is defined in a two or three dimensional space.

+ +

The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). The WR1 was added to constrain the usage of IfcCartesianPoint in the context of IFC geometry. For the purpose of defining geometry in IFC only two and three dimensional Cartesian points are used.

+ +
+NOTE: Corresponding STEP entity: cartesian_point, please refer to ISO/IS 10303-42:1994, p. 23 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 1.0 +
+ +
" +5553;IfcPoint;" + +

Definition from ISO/CD 10303-42:1992: A point is a location in some real Cartesian coordinate space Rm, for m = 1, 2 or 3.

+ +
+NOTE: Corresponding ISO 10303 entity: point. Only the subtypes cartesian_point, point_on_curve, point_on_surface have been incorporated in the current release of IFC. Please refer to ISO/IS 10303-42:1994, p. 22 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 1.5 +
+ +
" +5557;IfcPointOnCurve;" + +

Definition from ISO/CD 10303-42:1992: A point on curve is a point which lies on a curve. The point is determined by evaluating the curve at a specific parameter value. The coordinate space dimensionality of the point is that of the basis curve.

+ +
+NOTE: Corresponding STEP entity: point_on_curve. Please refer to ISO/IS 10303-42:1994, p. 23 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in Release IFC2x Edition 2. +
+ +

Informal Propositions:

+
    +
  1. The value of the point parameter shall not be outside the parametric range of the curve.
  2. +
+ +
" +5561;IfcCurve;" + +

Definition from ISO/CD 10303-42:1992: A curve can be envisioned as the path of a point moving in its coordinate space.

+ +
+NOTE: Corresponding ISO 10303 entity: curve, only the following subtypes have been incorporated into IFC: line as IfcLine, conic as IfcConic, bounded_curve as IfcBoundedCurve. Please refer to ISO/IS 10303-42:1994, p.37 for the final definition of the formal standard. The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). +
+ +
+HISTORY: New entity in IFC Release 1.0 +
+ +

Informal proposition:

+
    +
  1. A curve shall be arcwise connected
  2. +
  3. A curve shall have an arc length greater than zero.
  4. +
+ +
" +5569;IfcBoundedCurve;" + +

Definition from ISO/CD 10303-42:1992: A bounded curve is a curve of finite arc length with identifiable end points.

+ +
+NOTE Corresponding ISO 10303 name: bounded_curve, only the following subtypes have been incorporated into IFC: polyline as IfcPolyline, trimmed_curve as IfcTrimmedCurve, composite_curve as IfcCompositeCurve. Please refer to ISO/IS 10303-42:1994, p.44 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +

Informal propositions:

+
    +
  1. A bounded curve has finite arc length.
  2. +
  3. A bounded curve has a start point and an end point.
  4. +
+ +
" +5574;IfcCompositeCurve;" +

+ Definition from ISO/CD 10303-42:1992: A composite + curve is a collection of curves joined end-to-end. The + individual segments of the curve are themselves defined as + composite curve segments. The parameterization of the + composite curve is an accumulation of the parametric ranges + of the referenced bounded curves. The first segment is + parameterized from 0 to + l1 and for i + ≤ 2, the + ith segment is + parameterized from: +

+
+

+ +

+
+

+ where lk is the parametric + length (i.e., difference between maximum and minimum + parameter values) of the curve underlying the + kth segment. +

+

+ Let T denote the parameter for the composite curve. + Then, if the ith segment is not a reparameterised + composite curve segment, T is related to the + parameter ti; ti0 + ≤ ti ≤ + ti1; for the ith segment by the + equation: +

+
+

+ if Segments[i].SameSense = + TRUE; +

+
+

+ or by the equation: +

+
+

+ if Segments[i].SameSense = + FALSE; +

+
+

+ If the segments[i] is of type reparameterised composite + curve segment, +

+
+

+ where τ is defined at + reparameterized composite curve segment (see + IfcReparameterizedCompositeCurveSegment). +

+
+

+ +

Figure 279 illustrates an example of a composite curve.

+ + + +

Figure 279 — Composite curve

+ +

Consider an IfcCompositeCurve having line segment and an arc segment. The line should be parameterized:

+
    +
  • IfcPolyline with start= 0.,0. end= 0.,1., SameSense= TRUE, parametric length = 1.
  • +
+

The arch should be parameterized:

+
    +
  • IfcTrimmedCurve with start= 180', end= 90', SameSense= FALSE, parametric length = 90.
  • +
+

Then the parameterization of the composite curve is:

+
    +
  • IfcCompositeCurve with 0. ≤ T ≤ 1. (line segment) and 1. ≤ T ≤ 91. (arc segment), parametric length = 91.
  • +
+ +
+NOTE Corresponding ISO 10303 entity: composite_curve, please refer to ISO/IS 10303-42:1994, p. 56 for the final definition of the formal standard. The WR2 is added to ensure consistent Dim at all segments. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +

+ Informal Propositions: +

+
    +
  1. The SameSense attribute of each segment + correctly specifies the senses of the component curves. + When traversed in the direction indicated by + SameSense, the segments shall join end-to-end. +
  2. +
+ +
" +5582;IfcCompositeCurveOnSurface;" + +

Definition from ISO/CD 10303-42:1992 A composite curve on surface is a collection of segments which are curves on a surface. Each segment shall lie on the basis surface.

+ +

There shall be at least positional continuity between adjacent segments. The parameterization of the composite curve is obtained from the accumulation of the parametric ranges of the segments. The first segment is parameterized from 0 to l1, and, for i ≥ 2, the ith segment is parameterized from

+ +
+ +

where lk is the parametric length (that is, the difference between maximum and minimum parameter values) of the kth curve segment.

+ +

The IfcCompositeCurveOnSurface is a collection of segments, based on p-curves. i.e. a curve which lies on the basis of a surface and is defined in the parameter space of that surface. The p-curve segment is a special type of a composite curve segment and shall only be used to bound a surface.

+ +
+NOTE Corresponding ISO 10303 entity: composite_curve_on_surface. Please refer to ISO/IS 10303-42:1994, p.64 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x4. +
+ +
" +5586;IfcBoundaryCurve;" + +

Definition from ISO/CD 10303-42:1992ÿ A boundary curve +is a type of bounded curve suitable for the definition of a +surface boundary.

+ +
NOTEÿ Corresponding ISO 10303 entity: boundary_curve. Please refer to ISO/IS 10303-42:1994, p.89 for the final definition of the formal standard. +
+ +
+HISTORYÿ New entity in IFC2x4. +
+ +
" +5589;IfcOuterBoundaryCurve;" + +

Definition from ISO/CD 10303-42:1992ÿ This is a special subtype of boundary curve which has the additional semantics of defining an outer boundary of a surface. No more than one such curve shall be included in the set of boundaries of a curve bounded surface.

+ +
+NOTEÿ Corresponding ISO 10303 entity: outer_boundary_curve. Please refer to ISO/IS 10303-42:1994, p.89 for the final definition of the formal standard. +
+ +
+HISTORYÿ New entity in IFC2x4. +
+ +
" +5590;IfcSurface;" + +

Definition from ISO/CD 10303-42:1992: A surface can be envisioned as a set of connected points in 3-dimensional space which is always locally 2-dimensional, but need not be a manifold.

+ +
+NOTE Corresponding ISO 10303 entity: surface, the following subtypes have been incorporated into IFC - elementary_surface (as IfcElementarySurface), swept_surface (as IfcSweptSurface) and bounded_surface (as IfcBoundedSurface). Please refer to ISO/IS 10303-42:1994, p. 68 for the final definition of the formal standard.

+ +
+HISTORY New class in IFC Release 1.5 +
+ +

Informal proposition:

+
    +
  1. A surface has non zero area.
  2. +
  3. A surface is arcwise connected.
  4. +
+ +" +5595;IfcElementarySurface;" + +

Definition from ISO/CD 10303-42:1992: An elementary surface (IfcElementarySurface) is a simple analytic surface with defined parametric representation.

+ +
+NOTE Corresponding ISO 10303 entity: elementary_surface. Only the subtype plane is incorporated as IfcPlane. The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). Please refer to ISO/IS 10303-42:1994, p. 69 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.5 +
+ +
" +5599;IfcPlane;" + +

Definition from ISO/CD 10303-42:1992: A plane is an unbounded surface with a constant normal. A plane is defined by a point on the plane and the normal direction to the plane. The data is to be interpreted as follows:

+ +
+
+
+C = Position.Location
+x = Position.P[1]
+y = Position.P[2]
+z = Position.P[3] => normal to plane
+
+
+

and the surface is parameterized as:

+
+
+

+
+
+

where the parametric range is -∞ < u,v < +∞. In the above parameterization the length unit for the +unit vectors x and y is derived from the context of +the plane.

+ +

The planar surface is an unbounded surface in the direction of x and y. Bounded planar surfaces are defined by using a subtype of IfcBoundedSurface with BasisSurface being a plane.

+ +
NOTE A rectangular bounded planar surface can +be defined by an IfcRectangularTrimmedSurface with +BasisSurface being the plane and U1 = left bound in +x, U2 = right bound in x, V1 = lower +bound in y, V2 = upper bound in y if viewed +into the direction of the negative normal. (assuming the +Usense and Vsense agree to the sense of the basis +surface).
+

The inherited attributes are interpreted as

+
    +
  • SELF\IfcElementarySurface.Position defines the +location and orientation of the planar surface.
  • +
  • SELF\IfcElementarySurface.Position.Location defines a +point on the planar surface.
  • +
  • SELF\IfcElementarySurface.Position.P[3] defines the +normal of the planar surface.
  • +
+ +
+NOTE Corresponding ISO 10303 entity: plane. Please refer to ISO/IS 10303-42:1994, p.69 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.5 +
+ +
" +5600;IfcCylindricalSurface;" + +

Definition from ISO/CD 10303-42:1992: A cylindrical surface is a surface at a constant distance (the radius) from a straight line. A cylindrical surface is defined by its radius and its orientation and location. The data is to be interpreted as follows:

+ +
+
+
+C = Position.Location
+x = Position.P[1]
+y = Position.P[2]
+z = Position.P[3]
+R = Radius
+
+
+

and the surface is parameterized as:

+
+
+

+
+
+

where the parametric range is -∞ < u,v < +∞ .

+

In the above parameterization the length unit for the unit +vectors z is equal to that of the radius R. +In the placement coordinate system defined above, the surface is +represented by the equation S = 0, where

+
+
+

+
+
+

The positive direction of the normal to the surface at any +point on the surface is given by

+
+
+

, or as unit normal by

+

+
+
+ +

The direction of the normal is away from the axis of the cylinder.

+ +

The cylindrical surface is a surface unbounded in the direction of z. Bounded cylindrical surfaces are defined by using a subtype of IfcBoundedSurface with BasisSurface being a cylindrical surface.

+ +
NOTE A bounded cylindrical surface can be +defined by an IfcRectangularTrimmedSurface with +BasisSurface being the cylindrical surface and U1 = +0°, U2 = 360° and V1 = lower bound in +z, V2 = upper bound in z (if the plane angle +measure is degree). A bounded cylindrical arc surface is provided +with |U1 - U2| < 360° (assuming the Usense and Vsense +agree to the sense of the basis surface).
+
NOTE A non-rectangular bounded cylindrical +surface, e.g. the surface of a round wall underneath a sloped +roof, cab be defined by an IfcCurveBoundedSurface with +IfcBoundaryCurve's, being a collection of p-curve +segments. A p-curve is curve which lies on the basis of a surface +and is defined in the parameter space of that +surface.
+ +

The inherited attributes are interpreted as

+
    +
  • SELF\IfcElementarySurface.Position defines the +location and orientation of the cylindrical surface.
  • +
  • SELF\IfcElementarySurface.Position.Location definesd a +point on the axis of the cylindrical surface.
  • +
  • SELF\IfcElementarySurface.Position.P[3] defines the +direction of the axis of the cylindrical surface.
  • +
+ +
+NOTE Corresponding ISO 10303 entity: plane. Please refer to ISO/IS 10303-42:1994, p.70 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC2x4. +
+ +
" +5602;IfcAxis2Placement3D;" + +

Definition from ISO/CD 10303-42:1992: The location and orientation in three dimensional space of three mutually perpendicular axes. An axis2_placement_3D is defined in terms of a point (inherited from placement supertype) and two (ideally orthogonal) axes. It can be used to locate and originate an object in three dimensional space and to define a placement coordinate system. The entity includes a point which forms the origin of the placement coordinate system. Two direction vectors are required to complete the definition of the placement coordinate system. The axis is the placement Z axis direction and the ref_direction is an approximation to the placement X axis direction.

+ +

If the attribute values for Axis and RefDirection +are not given, the placement defaults to P[1] (x-axis) as [1.,0.,0.], +P[2] (y-axis) as [0.,1.,0.] and P[3] (z-axis) as [0.,0.,1.].

+ +
+NOTE  Corresponding ISO 10303 name: axis2_placement_3d, please refer to ISO/IS 10303-42:1994 for the final definition of the formal standard. The WR5 is added to ensure that either both attributes Axis and RefDirection are given, or both are omitted. +
+ +
+HISTORY  New entity in IFC Release 1.5. +
+ +

Figure 276 illustrates the definition of the IfcAxis2Placement3D within the three-dimensional coordinate system.

+ + + +

Figure 276 — Axis2 placement 3D

+ +
" +5611;IfcSweptSurface;" + +

Definition from ISO/CD 10303-42:1992: A swept surface is one that is constructed by sweeping a curve along another curve.

+ +
+NOTE: Corresponding ISO 10303 entity: swept_surface. Please refer to ISO/IS 10303-42:1994, p.76 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +
" +5618;IfcSurfaceOfRevolution;" + +

Definition from ISO/CD 10303-42:1992: A surface of revolution (IfcSurfaceOfRevolution) is the surface obtained by rotating a curve one complete revolution about an axis. The data shall be interpreted as below.

+ +

The parameterization is as follows where the curve has a parameterization l(u):

+ +
+

C = AxisPosition.Location
V = AxisPosition.Z

+

+
+ +

In order to produce a single-value surface the a complete revolution, the curve shall be such that when expressed in a cylindrical coordinate system the curve shall be such that when expressed in a cylindrical coordinate system (r,φ ,z) centred at C with an axis V no two distinct parametric points on the curve shall have the same values for (r, z).

+

For a surface of revolution the parametric range is 0 < u < 360 degree. The parameterization range for v is defined by referenced curve.

+ +
+NOTE: Corresponding ISO 10303 entity: surface_of_revolution. Please refer to ISO/IS 10303-42:1994, p.76 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x. +
+ +

Informal propositions:

+
    +
  1. The surface shall not self-intersect
  2. +
  3. The swept curve shall not be coincident with the axis line for any finite part of its legth.
  4. +
+ +
" +5621;IfcAxis1Placement;" + +

Definition from ISO/CD 10303-42:1992: The direction and location in three dimensional space of a single axis. An axis1_placement is defined in terms of a locating point (inherited from placement supertype) and an axis direction: this is either the direction of axis or defaults to (0.0,0.0,1.0). The actual direction for the axis placement is given by the derived attribute z (Z).

+ +
+NOTE  Corresponding ISO 10303 name: axis1_placement, please refer to ISO/IS 10303-42:1994, p. 28 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC Release 1.5 +
+ +

Figure 274 illustrates the definition of the IfcAxis1Placement within the three-dimensional coordinate system.

+ + + +

Figure 274 — Axis1 placement

+ +
" +5626;IfcLine;" + +

Definition from ISO/CD 10303-42:1992: A line is an unbounded curve with constant tangent direction. A line is defined by a point and a direction. The positive direction of the line is in the direction of the Dir vector. The line is parameterized as follows:

+ +
+ P = Pnt
+ V = Dir
+ λ(u) = P + uV +
+

+ and the parametric range is: +

+
+ ∞ < u < ∞ +
+ +
+NOTE Corresponding ISO 10303 entity: line. Please refer to ISO/IS 10303-42:1994, p.37 for the final definition of the formal standard. The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +
" +5630;IfcVector;" + +

Definition from ISO/CD 10303-42:1992: The vector is defined in terms of the direction and magnitude of the vector. The value of the magnitude attribute defines the magnitude of the vector.

+ +
+NOTE: The magnitude of the vector can not be reliable calculated from the components of the Orientation attribute. This form of representation was selected to reduce problems with numerical instability. For example a vector of magnitude 2.0 mm and equally inclined to the coordinate axes could be represented with Orientation attribute of (1.0,1.0,1.0). +
+ +
+NOTE: Corresponding ISO 10303 entity: vector. Please refer to ISO/IS 10303-42:1994, p.27 for the final definition of the formal standard. The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). +
+ +
+HISTORY: New entity in IFC Release 1.0 +
+ +
" +5635;IfcSurfaceOfLinearExtrusion;" + +

Definition from ISO/CD 10303-42:1992: This surface is a simple swept surface or a generalized cylinder obtained by sweeping a curve in a given direction. The parameterization is as follows where the curve has a parameterization l(u):

+ +

V = ExtrusionAxis

+

+
+ +

The parameterization range for v is -¥ < v < ¥ and for u it is defined by the curve parameterization.

+ +
+NOTE: Corresponding ISO 10303 entity: surface_of_linear_extrusion. Please refer to ISO/IS 10303-42:1994, p.76 for the final definition of the formal standard. The following adaption has been made. The ExtrusionAxis and the Direction are defined as two separate attributes in correlation to the definition of the extruded_area_solid, and not as a single vector attribute. The vector is derived as ExtrusionAxis. +
+ +
+HISTORY: New entity in IFC Release 2x. +
+ +

Informal propositions:

+
    +
  1. The surface shall not self-intersect
  2. +
+ +
" +5640;IfcBoundedSurface;" + +

Definition from ISO/CD 10303-42:1992: A bounded surface is a surface of finite area with identifiable boundaries.

+ +
+NOTE Corresponding ISO 10303 name: bounded_surface. Please refer to ISO/IS 10303-42:1994, p.78 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 2x +
+ +
+IFC2x4 CHANGE Entity made abstract. +
+ +

Informal propositions:

+
    +
  1. A bounded surface has finite non-zero surface area.
  2. +
  3. A bounded surface has boundary curves.
  4. +
+ +
" +5645;IfcCurveBoundedPlane;" + +

Definition from ISO/CD 10303-42:1992: The curve bounded surface is a parametric surface with curved boundaries defined by one or more boundary curves. The bounded surface is defined to be the portion of the basis surface in the direction of N x T from any point on the boundary, where N is the surface normal and T the boundary curve tangent vector at this point. The region so defined shall be arcwise connected.

+ +

The IfcCurveBoundedPlane is a specialized bounded surface class that deals only with bounding basis plane surfaces. The definition varies from STEP as outer and inner boundaries are separated attributes and refer to IfcCurve. The only basis surface that is allowed is of type IfcPlane, and the implicit_outer attribute has not been incorporated, since only unbounded surfaces are used as basis surface.

+ +

The BasisSurface is an IfcPlane that establishes the position coordinate system by SELF\IfcElementarySurface.Position. The OuterBoundary and the InnerBoundaries (if provided) shall lie on the surface of IfcPlane. Therefore the IfcCurve's establishing the outer and inner boundaries shall be:

+ +
    +
  • either a 2D curve within the XY plane of the position coordinate sytem of IfcPlane
  • or a 3D curve with all coordinates having a z value = 0.
  • +
+ +
+NOTE Corresponding ISO 10303 entity curve_bounded_surface has been changed to meet the specific requirements of an easy representation of curve bounded planes. +
+ +
+HISTORY  New entity in IFC Release 1.5 +
+ +
+IFC2x PLATFORM CHANGE: The data type of the attribute OuterBoundary and InnerBoundaries has been changed from Ifc2DCompositeCurve to its supertype IfcCurve with upward compatibility for file based exchange. +
+ +
" +5649;IfcRectangularTrimmedSurface;" + +

Definition from ISO/CD 10303-42:1992: The trimmed surface is a simple bounded surface in which the boundaries are the constant parametric lines u1 = u1, u2 = u2, v1 = v1 and v2 = v2. All these values shall be within the parametric range of the referenced surface. Cyclic properties of the parameter range are assumed.

+ +
+NOTE 1 For example, 370 degrees is equivalent to 10 degrees, for those surfaces whose parametric form is defined using circular functions (sine and cosine). +
+ +

The rectangular trimmed surface inherits its parameterization directly from the basis surface and has parameter ranges from 0 to |u2 - u1| and 0 to|v2-v1|.

+ +
+NOTE 2 If the surface is closed in a given parametric direction, the values of u2 or v2 may require to be increased by the cyclic range. +
+ +
+NOTE Corresponding ISO 10303 name: rectangular_trimmed_surface. Please refer to ISO/IS 10303-42:1994, p.86 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 2x. +
+ +

Informal propositions:

+
    +
  1. The domain of the trimmed surface shall be within the domain of the surface being trimmed.
  2. +
+ +
" +5661;IfcCurveBoundedSurface;" + +

Definition from ISO/CD 10303-42:1992 The curve bounded surface is a parametric surface with curved boundaries defined by one or more boundary curves. One of the boundary curves may be the outer boundary; any number of inner boundaries is permissible. The region of the curve bounded surface in the basis surface is defined to be the portion of the basis surface in the direction of N x T from any point on the boundary, where N is the surface normal and T the boundary curve tangent vector at this point. The region so defined shall be arcwise connected.

+ +

The IfcCurveBoundedSurface is a parametric surface with boundaries defined by p-curves, that is, a curve which lies on the basis of a surface and is defined in the parameter space of that surface. The p-curve is a special type of a composite curve segment and shall only be used to bound a surface.

+ +

The outer boundary shall be either defined by:

+
    +
  • an IfcOuterBoundaryCurve, a closed composite curve on surface for the definition of an outer boundary, then the attribute ImplicitOuter has to be set to FALSE, or
  • +
  • by the implicit boundary of the bounded surface, e.g. the u1, u2, v1, v2 of IfcRectangularTrimmedSurface< then the attribute ImplicitOuter has to be set to TRUE. +
    Note that some surfaces, like +IfcCylindricalSurface does not have identifiable implicit +boundaries.
    +
  • +
+ +
+NOTE Corresponding STEP entity: curve_bounded_surface. Please refer to ISO/IS 10303-42:1994, p.87 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x4. +
+ +

Informal Propositions

+
    +
  1. Each curve in the set of Boundaries shall be closed.
  2. +
  3. No two curves in the set of Boundaries shall intersect.
  4. +
  5. At most one of the boundary curves may enclose any other boundary curve. If an IfcOuterBoundaryCurve is designated, only that curve may enclose any other boundary curve.
  6. +
+ +
" +5665;IfcBSplineSurface;" + +

Definition from ISO/CD 10303-42:1992: A b_spline_surface is a general form of rational or polynomial parametric surface which is represented by control points, basis functions, and possibly, weights. As with the corresponding curve entity it has some special subtypes where some of the data can be derived.

+ +
    +
  1. The symbology used here is: + + + + + + + + + + + + + + + + + + + + + + + + + +
    K1= upper_index_on_u_control_points
    K2= upper_index_on_v_control_points
    Pij= control_points
    wij= weights
    d1= u_degree
    d2= v_degree
    +
  2. +
  3. The control points are ordered as +
    P00, P01, P02, +......, PK1(K2-1), +PK1K2
    +The weights, in the case of the rational subtype, are ordered +similarly.
    +
  4. +
  5. For each parameter, s = u or v, if +k is the upper index on the control points and d is +the degree for s, the knot array is an array of (k ++ d + 2) real numbers [s-d, ...., +sk+1], such that for all indices j in +[-d, k]; sj ≤ +sj+1. This array is obtained from the +appropriate u_knots or v_knots list by repeating each multiple +knot according to the multiplicity.
    +
    +Nid, the ith +normalised B-spline basis function of degree d, is defined +on the subset [si-d, ...., +si+1] of this array.
    +
  6. +
  7. Let L denote the number of distinct values amongst the +knots in the knot list; L will be referred to as the +‘upper index on knots’. Let +mj denote the multiplicity (i.e., number +of repetitions) of the jth distinct knot value. Then: +
    +""formula""
    +All knot multiplicities except the first and the last shall be in +the range 1, ...., d; the first and last may have a +maximum value of d+1. In evaluating the basis functions, a +knot u of, e.g., multiplicity 3 is interpreted as a +sequence u, u, u, in the knot array.
    +
  8. +
  9. The surface form is used to identify specific quadric surface +types (which shall have degree two), ruled surfaces and surfaces +of revolution. As with the b-spline curve, the surface form is +informational only and the spline data takes precedence.
    +
  10. +
  11. The surface is to be interpreted as follows: In the +polynomial case the surface is given by the equation: +
    +""formula""
    +In the rational case the surface equation is: +
    +""formula""
    +
  12. +
+ +
+NOTE Corresponding ISO 10303 entity: b_spline_surface. Please refer to ISO/IS 10303-42:1994, p. 78 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x4. +
+ +
" +5679;IfcBSplineSurfaceWithKnots;" + +

Definition from ISO 10303:42:1994: This is a B-spline surface in which the knot values are explicitly given. This subtype shall be used to represent non-uniform B-spline surfaces, and may also be used for other knot types.

+ +

All knot multiplicities except the first and the last shall be in the range 1,....,d; the first and last may have a maximum value of d + 1. In evaluating the basis functions, a knot u of, e.g., multiplicity 3 is interpreted as a sequence u, u, u, in the knot array.

+ +
+NOTE Corresponding ISO 10303 entity: b_spline_surface_with_knots. Please refer to ISO/IS 10303-42:1994, p. 81 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x4. +
+ +
" +5692;IfcRationalBSplineSurfaceWithKnots;" + +

A rational B-spline surface with knots is a piecewise parametric rational surface described in terms of control points, and associated weight values.

+ +

The surface is to be interpreted as follows:

+ +
+σ +
+ +
+NOTE: The IfcRationalBSplineSurfaceWithKnots is an entity that had been adopted from ISO 10303, Industrial automation systems and integration — Product data representation and exchange, Part 42: Integrated generic resource: Geometric and topological representation. +
+ +
+NOTE: The specific subtype IfcRationalBSplineSurfaceWithKnots has been introduced to avoid the complexity of ANDOR subtype relationships in the ISO 10303-42 specification
+
+ +
+NOTE: Corresponding ISO 10303 entity: rational_b_spline_surface. Please refer to ISO/IS 10303-42:1994, p. 85 for the final definition of the formal standard. +
+ +
+HISTORY: New entity in IFC2x4. +
+ +
" +5716;IfcCompositeCurveSegment;" + +

Definition from ISO/CD 10303-42:1992: A composite curve segment is a bounded curve together with transition information which is used to construct a composite curve (IfcCompositeCurve).

+ +

The derived attribute Dim has been added (see also note at IfcGeometricRepresentationItem). The IfcCompositeCurveSegment is a subtype of IfcGeometricRepresentationItem (whereas in ISO 10303-42 composite_curve_segment is not a subtype of geometric_representation_item, the proposed 2nd edition of ISO 10303-42 however proposes the subtype relationship).

+ +
+NOTE Corresponding ISO 10303 entity: composite_curve_segment. Please refer to ISO/IS 10303-42:1994, p.57 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +
" +5724;IfcReparametrisedCompositeCurveSegment;" +

+ Definition from ISO/CD 10303-42:1992: The + reparametrised composite curve segment is a special type of + composite curve segment which provides the capability to + re-define its parametric length without changing its + geometry. +

+

+ Let l = ParamLength. +

+

+ If t0 ≤ t ≤ + t1 is the parameter range of + ParentCurve, the new parameter . for the + reparametrised composite curve segment is given by the + equation: +

+
+

+ if SameSense = TRUE; +

+
+

+ or by the equation: +

+
+

+ if SameSense = FALSE; +

+
+ +
+NOTE Corresponding STEP entity: reparametrised_composite_curve_segment. Please refer to ISO/IS 10303-42:1994, p.59 for the final definition of the formal standard. +
+
+HISTORY New class in IFC2x4 +
+ +
" +5732;IfcPolyline;" +

+ Definition from ISO/CD 10303-42:1992: A polyline + is a bounded curve of n - 1 linear segments, defined by a + list of n points, P1, P2 ... Pn. + The ith segment of the curve is parameterized as follows: +

+
+
+

+     + for 1 ≤ i ≤ n - 1 +

+
+
+

+ where i - 1 ≤ u ≤ i and + with parametric range of 0 <≤ u ≤ n - 1. +

+ +
+NOTE  Corresponding ISO 10303 entity: polyline. Please refer to ISO/IS 10303-42:1994, p. 45 for the final definition of the formal standard. +
+
+HISTORY  New class in IFC Release 1.0 +
+ +
" +5735;IfcTrimmedCurve;" + +

Definition from ISO/CD 10303-42:1992: +A trimmed curve is a bounded curve which is created by taking a selected +portion, between two identified points, of the associated basis curve. +The basis curve itself is unaltered and more than one trimmed curve may +reference the same basis curve. Trimming points for the curve may be +identified by:

+
  • parametric value
  • geometric +position
  • both of the above
  • +

At least one of these shall be specified at each +end of the +curve. The SenseAgreement makes it possible to +unambiguously define any segment of a closed curve such as a circle. +The combinations of sense and ordered end points make it possible to +define four distinct directed segments connecting two different points +on a circle or other closed curve. For this purpose cyclic properties +of the parameter range are assumed; for example, 370 degrees is +equivalent to 10 degrees.

+

The IfcTrimmedCurve has a parameterization +which is inherited from the particular basis curve reference. More +precisely the parameter s of the trimmed curve is derived from the +parameter of the basis curve as follows:

+
  • if SenseAgreement is TRUE: s += t - t1
  • if SenseAgreement +is FALSE: s += t2 - t
  • +

In the above equations t1 is +the value +given by Trim1 or the parameter value corresponding +to point 1 and t2 is the value given by Trim2 +or the parameter value corresponding to point 2. The resultant IfcTrimmedCurve +has a parameter ranging from 0 at the first trimming point to |t2 +- t1| at the second trimming point.

+

NOTE In case +of a closed curve, +it may be necessary to increment t1 or t2 by the parametric length for +consistency with the sense flag.

+
+ +
+NOTE Corresponding ISO 10303 entity: trimmed_curve; As a further IFC restriction, an IfcTrimmedCurve should only trim a IfcLine or IfcConic. Please refer to ISO/IS 10303-42:1994, p. 54 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +

Informal Propositions:

+
  1. Where both the parameter value and the Cartesian +point +exist for Trim1 and Trim2 they +shall be consistent. (i.e., the BasisCurve +evaluated at the parameter value shall coincide with the specified +point).
  2. When a Cartesian point is specified by Trim1 +or by Trim2 it shall lie on the BasisCurve.
  3. +
  4. Except the case of a closed BasisCurve +where both parameter 1 and parameter 2 exist, they shall be consistent +with the sense flag, i.e., (sense = parameter 1 < parameter 2). Or, for every open curve where both +parameter 1 and parameter 2 exist, they shall be consistent with the SenseAgreement, +i.e., SenseAgreement = (parameter 1 < +parameter 2).
  5. If both parameter 1 +and parameter 2 exist, then parameter 1 +<> parameter 2. For a +closed base curve, e.g. IfcCircle or IfcEllipse, +this also applies to the cyclic properties, as 360' is equal to 0', +parameter 1 = 360' and parameter 2 = 0' are treated as being equal and +therefore violating this proposition.
  6. When +a parameter value is specified by Trim1 +or Trim2 it shall lie within the parametric range +of the BasisCurve.
  7. +

Additional illustration from IAI:

+ + +
The +figure above shows the four arcs (dashed blue and +green lines with arrow showing different orientations) that can be +defined by the same BasisCurve (of type IfcCircle) +and the same trimming points (given by Cartesian points and parameter +values) by using different assignments to Trim1 and +Trim2 and SenseAgreement.

+Note: Since the BasisCurve is closed (type IfcCircle), +the exception of the informal proposition IP3 applies, i.e. the sense +flag is not +required to be consistent with the parameter values of Trim1 +and Trim1, so the rule (sense = parameter 1 +< parameter 2) may not be fulfilled.
+ +
" +5751;IfcBSplineCurve;" + +

Definition from ISO/CD 10303-42:1992: A B-spline curve is a piecewise parametric polynomial or rational curve described in terms of control points and basis functions. The B-spline curve has been selected as the most stable format to represent all types of polynomial or rational parametric curves. With appropriate attribute values it is capable of representing single span or spline curves of explicit polynomial, rational, Bezier or B-spline type.

+ +

Interpretation of the data is as follows:

+
    +
  1. +

    All weights shall be positive and the curve is given by

    + + + + + + + + + + + + + + + + + +
    k+1 = number of control points
    Pi= control points
    wi= weights
    d= degree
    +

    The knot array is an array of (k+d+2) real numbers + [u-d ... uk+1], such that for + all indices j in [-d,k], uj <= + uj+1. This array is obtained from the knot data list by + repeating each multiple knot according to the multiplicity. N + di, the ith normalized B-spline basis function + of degree d, is defined on the subset [ui-d, ... , + ui+1] of this array.

  2. +
  3. +

    Let L denote the number of distinct values among the + d+k+2 knots in the knot array; L will be referred to as + the 'upper index on knots'. Let mj denote the multiplicity + (number of repetitions) of the jth distinct knot. Then

    + +

    All knot multiplicities except the first and the last shall be in + the range 1 ... degree; the first and last may have a maximum value of degree + + 1. In evaluating the basis functions, a knot u of e.g. multiplicity 3 is + interpreted as a string u, u, u, in the knot array. The B-spline curve + has 3 special subtypes (Note: only 1, Bezier curve, included in this IFC + release) where the knots and knot multiplicities are derived to provide + simple default capabilities.

  4. +
  5. Logical flag is provided to indicate whether the curve self + intersects or not.
  6. +
+

Figure 277 (from ISO 10303-42) illustrates a B-spline curve.

+ + + +

Figure 277 — B-spline curve

+ +
+NOTE  Corresponding ISO 10303 entity: b_spline_curve. Please refer to ISO/IS 10303-42:1994, p. 45 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in Release IFC2x2. +
+ +
" +5761;IfcBSplineCurveWithKnots;" + +

Definition from ISO 10303:42:1994: This is the type of b-spline curve for which the knot values are explicitly given. This subtype shall be used to represent non-uniform B-spline curves and may be used for other knot types.

+ +

Let L denote the number of distinct values amongst the +d+k+2 knots in the knot list; L will be +referred to as the ‘upper index on knots’. Let +mj denote the multiplicity (i.e., number of +repetitions) of the jth distinct knot. Then:

+
+""formula""
+ +

All knot multiplicities except the first and the last shall be +in the range 1,...,d; the first and last may have a +maximum value of d + 1. In evaluating the basis functions, +a knot u of, e.g., multiplicity 3 is interpreted as a +sequence u, u, u,; in the knot array.

+ +
+NOTE Corresponding ISO 10303 entity: b_spline_curve_with_knots. Please refer to ISO/IS 10303-42:1994, p. 46 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC2x4. +
+ +
" +5769;IfcRationalBSplineCurveWithKnots;" +

A rational B-spline curve with knots is a B-spline curve +described in terms of control points and basic functions. It +describes weights in addition to the control points defined at the +supertype IfcBSplineCurve.

+ +
NOTE: The +IfcRationalBSplineCurveWithKnots is an entity that had been +adopted from ISO 10303, Industrial automation systems and +integration — Product data representation and exchange, Part +42: Integrated generic resource: Geometric and topological +representation.
+ +
NOTE: The specific subtype +IfcRationalBSplineCurveWithKnots has been introduced to +avoid the complexity of ANDOR subtype relationships in the ISO +10303-42 specification
+ +

All weights shall be positive and the curve is given by:

+ +
+

where

+ + + + + + + + + + + + + + + + + +
k+1number of control points
Picontrol points
wiweights
ddegree
+ +
+NOTE  Corresponding ISO 10303 entity: rational_b_spline_curve. Please refer to ISO/IS 10303-42:1994, p. 45 for the final definition of the formal standard. +
+ +
+HISTORY  New entity in IFC2x4. +
+ +
" +5781;IfcConic;" + +

Definition from ISO/CD 10303-42:1992: A conic (IfcConic) is a planar curve which could be produced by intersecting a plane with a cone. A conic is defined in terms of its intrinsic geometric properties rather than being described in terms of other geometry. A conic class always has a placement coordinate system defined by a two or three dimensional placement. The parametric representation is defined in terms of this placement coordinate system.

+ +
+NOTE Corresponding ISO 10303 entity: conic, only the following subtypes have been incorporated into IFC 1.0, 1.5 & 2.0: circle as IfcCircle, ellipse as IfcEllipse. The derived attribute Dim has been added at this level and was therefore demoted from the geometric_representation_item. Please refer to ISO/IS 10303-42:1994, p. 38 for the final definition of the formal standard. +
+ +
+HISTORY New class in IFC Release 1.0 +
+ +
" +5785;IfcCircle;" + +

Definition from ISO/CD 10303-42:1992: An IfcCircle is defined by a radius and the location and orientation of the circle. Interpretation of data should be as follows:

+ +
+
+
 
+C = SELF\IfcConic.Position.Location
+
x = SELF\IfcConic.Position.P[1]
+
y = SELF\IfcConic.Position.P[2]
+
z = SELF\IfcConic.Position.P[3]
+
R = Radius
+
+

and the circle is parameterized as

+
+

The parameterization range is 0 £ + u £2p (or 0 + £u £ + 360 degree). In the placement coordinate system defined above, the circle is + the equation C = 0, where

+
+

The positive sense of the circle at any point is in the tangent direction, T, to the curve at the point, where

+
+ +
+NOTE  A circular arc is defined by using the trimmed curve (IfcTrimmedCurve) entity in conjunction with the circle (IfcCircle) entity as the BasisCurve. +
+ +
+NOTE  Corresponding ISO 10303 entity: circle, please refer to ISO/IS 10303-42:1994, p. 38 for the final definition of the formal standard. +
+ +
+HISTORY  New class in IFC Release 1.0 +
+ +

Figure 278 illustrates the definition of the IfcCircle within the (in this case three-dimensional) position coordinate system.

+ + + + +

Figure 278 — Circle geometry

+ +
" +5787;IfcEllipse;" + +

Definition from ISO/CD 10303-42:1992: An ellipse (IfcEllipse) is a conic section defined by the lengths of the semi-major and semi-minor diameters and the position (center or mid point of the line joining the foci) and orientation of the curve. Interpretation of the data shall be as follows: +

+ +
+
+
C  = SELF\IfcConic.Position.Location 
+
x  = SELF\IfcConic.Position.P[1] 
+
y  = SELF\IfcConic.Position.P[2] 
+
z  = SELF\IfcConic.Position.P[3] 
+
R1 = SemiAxis1
+
R2 = SemiAxis2
+

and the ellipse is parameterized as:

+
+
+

+

The parameterization range is 0 £ + u £ 2p (or 0 + £ u £ + 360 degree). In the placement coordinate system defined above, the ellipse is + the equation C = 0, where

+
+
+

+

The positive sense of the ellipse at any point is in the tangent direction, T, to the curve at the point, where

+
+
+

+

The inherited Position.Location from IfcConic is the center of the IfcEllipse, and the inherited Position.P[1] from IfcConic the direction of the SemiAxis1.

+ +
+NOTE  Corresponding ISO 10303 entity: ellipse. Please refer to ISO/IS 10303-42:1994, p. 39 for the final definition of the formal standard. +
+ +
+HISTORY  New class in IFC Release 1.0 +
+ +

Figure 280 illustrates the definition of the IfcEllipse within the (in this case three-dimensional) position coordinate system. + + + +

Figure 280 — Ellipse geometry

+ +" +5790;IfcOffsetCurve2D;" + +

Definition from ISO/CD 10303-42:1992: An offset curve 2d (IfcOffsetCurve2d) is a curve at a constant distance from a basis curve in two-dimensional space. This entity defines a simple plane-offset curve by offsetting by distance along the normal to basis curve in the plane of basis curve. The underlying curve shall have a well-defined tangent direction at every point. In the case of a composite curve, the transition code between each segment shall be cont same gradient or cont same gradient same curvature.

+ +
+NOTE: The offset curve 2d may differ in nature from the basis curve; the offset of a non self- intersecting curve can be self-intersecting. Care should be taken to ensure that the offset to a continuous curve does not become discontinuous. +
+ +

The offset curve 2d takes its parameterization from the basis curve. The offset curve 2d is parameterized as

+ +
+

+
+ +

where T is the unit tangent vector to the basis curve C(u) at parameter value u, and d is distance. The underlying curve shall be two-dimensional.

+ +
+NOTE Corresponding ISO 10303 entity: offset_curve_2d, Please refer to ISO/IS 10303-42:1994, p.65 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 2.x +
+ +
" +5795;IfcOffsetCurve3D;" + +

Definition from ISO/CD 10303-42:1992: An offset curve 3d is a curve at a constant distance from a basis curve in three-dimensional space. The underlying curve shall have a well-defined tangent direction at every point. In the case of a composite curve the transition code between each segment shall be cont same gradient or cont same gradient same curvature. The offset curve at any point (parameter) on the basis curve is in the direction V x T where V is the fixed reference direction and T is the unit tangent to the basis curve. For the offset direction to be well defined, T shall not at any point of the curve be in the same, or opposite, direction as V.

+ +
+NOTE: The offset curve 3d may differ in nature from the basis curve; the offset of a non self- intersecting curve can be self-intersecting. Care should be taken to ensure that the offset to a continuous curve does not become discontinuous. +
+ +

The offset curve 3d takes its parameterization from the basis curve. The offset curve 3d is parameterized as

+ +
+

+
+ +

where T is the unit tangent vector to the basis curve C(u) at parameter value u, and d is distance. The underlying curve shall be three-dimensional.

+ +
+NOTE Corresponding ISO 10303 entity: offset_curve_3d, Please refer to ISO/IS 10303-42:1994, p.66 for the final definition of the formal standard. +
+ +
+HISTORY New entity in IFC Release 2.x +
+ +

Informal propositions:

+
    +
  1. At no point on the curve shall ref direction be parallel, or opposite to, the direction of the tangent vector.
  2. +
+ +
" +5801;IfcPCurve;" + +

Definition from ISO/CD 10303-42:1992: A pcurve is a curve which lies on the basis of a surface and is defined in the parameter space of that surface. The basis curve is a curve defined in the two-dimensional parametric space of a reference basis surface. Although it is defined by a curve in two dimensional space, the variables involved are u and v, which occur in the parametric representation of the referenced surface, rather than the x, y, Cartesian coordinates.

+ +

The basis curve is only defined within the parametric range of the surface.

+ +
+NOTE Corresponding ISO 10303 entity: pcurve. Please refer to ISO/IS 10303-42:1994, p.59 for the final definition of the formal standard.
The definition of IfcPCurve derivates from pcurve. The following changes have been made: The BasisCurve replaces the definition of reference_to_curve since there is no requirement of having same dimensionality within the representation context. +
+ +
+HISTORY New class in IFC2x4. +
+ +
" +5805;IfcPointOnSurface;" + +

Definition from ISO/CD 10303-42:1992: A point on surface is a point which lies on a parametric surface. The point is determined by evaluating the surface at a particular pair of parameter values.

+ +
+NOTE: Corresponding ISO 10303 entity: point_on_surface. Please refer to ISO/IS 10303-42:1994, p. 24 for the final definition of the formal standard.

+
+ +
+HISTORY: New entity in Release IFC2x Edition 2. +
+ +

Informal Propositions:

+
    +
  1. The parametric values specified for u and v shall not be outside the parametric range of the basis surface.
  2. +
+ +
" diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntityAttributes.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntityAttributes.csv new file mode 100644 index 0000000000000000000000000000000000000000..3a4180655cd447cea853909bd4cf68023c341703 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEntityAttributes.csv @@ -0,0 +1,1655 @@ +31;0;32 +31;1;33 +31;2;34 +31;3;35 +31;4;36 +31;5;37 +31;6;38 +31;7;39 +40;0;41 +40;1;42 +40;2;43 +40;3;44 +70;0;73 +70;1;74 +70;2;75 +70;3;76 +70;4;77 +79;0;80 +79;1;81 +79;2;82 +79;3;83 +79;4;84 +79;5;85 +79;6;86 +88;0;89 +88;1;90 +88;2;91 +88;3;92 +88;4;93 +88;5;94 +102;0;103 +102;1;104 +102;2;105 +102;3;106 +102;4;107 +102;5;108 +102;6;109 +102;7;110 +102;8;111 +113;0;114 +113;1;115 +113;2;116 +117;0;118 +117;1;119 +117;2;120 +117;3;121 +123;0;124 +123;1;125 +123;2;126 +123;3;127 +123;4;128 +123;5;129 +123;6;130 +123;7;131 +123;8;132 +123;9;133 +123;10;134 +123;11;135 +123;12;136 +123;13;137 +139;0;140 +139;1;141 +142;0;143 +142;1;144 +146;0;147 +146;1;148 +152;0;153 +154;0;155 +154;1;156 +157;0;158 +157;1;159 +157;2;160 +162;0;163 +174;0;175 +185;0;186 +194;0;195 +206;0;207 +210;0;211 +210;1;212 +222;0;225 +222;1;226 +222;2;227 +230;0;233 +230;1;234 +237;0;238 +249;0;250 +252;0;253 +252;1;254 +252;2;255 +252;3;256 +252;4;257 +258;0;259 +258;1;260 +258;2;261 +258;3;262 +258;4;263 +258;5;264 +258;6;265 +258;7;266 +258;8;267 +271;0;272 +271;1;273 +282;0;285 +292;0;293 +292;1;294 +292;2;295 +292;3;296 +292;4;297 +307;0;309 +310;0;311 +310;1;312 +310;2;313 +314;0;316 +314;1;317 +318;0;319 +324;0;325 +324;1;326 +324;2;327 +329;0;332 +329;1;333 +329;2;334 +329;3;335 +329;4;336 +329;5;337 +329;6;338 +339;0;340 +339;1;341 +351;0;352 +351;1;353 +354;0;355 +354;1;356 +358;0;359 +358;1;360 +358;2;361 +365;0;366 +365;1;367 +365;2;368 +365;3;369 +373;0;374 +373;1;375 +373;2;376 +373;3;377 +373;4;378 +373;5;379 +388;0;389 +388;1;390 +400;0;401 +400;1;402 +406;0;409 +406;1;410 +406;2;411 +406;3;412 +413;0;420 +421;0;422 +421;1;423 +426;0;427 +426;1;428 +431;0;432 +431;1;433 +436;0;437 +436;1;438 +440;0;441 +440;1;442 +445;0;446 +445;1;447 +450;0;451 +450;1;452 +450;2;453 +450;3;454 +459;0;463 +464;0;465 +467;0;470 +467;1;471 +467;2;472 +474;0;477 +474;1;478 +474;2;479 +474;3;480 +474;4;481 +483;0;484 +483;1;485 +486;0;487 +486;1;488 +486;2;489 +486;3;490 +494;0;495 +494;1;496 +494;2;497 +494;3;498 +501;0;506 +501;1;507 +509;0;513 +509;1;514 +509;2;515 +516;0;525 +516;1;526 +516;2;527 +516;3;528 +516;4;529 +516;5;530 +516;6;531 +516;7;532 +516;8;533 +516;9;534 +516;10;535 +516;11;536 +537;0;538 +541;0;544 +545;0;548 +549;0;556 +557;0;560 +563;0;564 +574;0;575 +590;0;591 +601;0;602 +607;0;608 +622;0;623 +622;1;624 +626;0;627 +626;1;628 +626;2;629 +630;0;631 +630;1;632 +630;2;633 +638;0;639 +638;1;640 +638;2;641 +647;0;649 +650;0;651 +655;0;656 +655;1;657 +658;0;659 +658;1;660 +661;0;663 +666;0;668 +666;1;669 +676;0;677 +676;1;678 +679;0;680 +679;1;681 +689;0;690 +693;0;694 +693;1;695 +693;2;696 +693;3;697 +693;4;698 +700;0;701 +700;1;702 +704;0;705 +704;1;706 +707;0;708 +707;1;709 +711;0;712 +711;1;713 +711;2;714 +711;3;715 +717;0;718 +719;0;720 +725;0;726 +725;1;727 +735;0;736 +735;1;737 +738;0;739 +738;1;740 +738;2;741 +742;0;743 +744;0;745 +744;1;746 +744;2;747 +744;3;748 +744;4;749 +765;0;766 +765;1;767 +770;0;771 +776;0;778 +776;1;779 +776;2;780 +782;0;789 +782;1;790 +782;2;791 +782;3;792 +782;4;793 +794;0;798 +794;1;799 +794;2;800 +794;3;801 +794;4;802 +794;5;803 +794;6;804 +805;0;809 +805;1;810 +805;2;811 +805;3;812 +815;0;818 +815;1;819 +820;0;823 +820;1;824 +825;0;826 +825;1;827 +830;0;831 +830;1;832 +845;0;852 +845;1;853 +855;0;856 +855;1;857 +862;0;863 +862;1;864 +862;2;865 +862;3;866 +862;4;867 +868;0;869 +868;1;870 +868;2;871 +868;3;872 +873;0;877 +873;1;878 +873;2;879 +881;0;882 +881;1;883 +881;2;884 +886;0;887 +892;0;893 +892;1;894 +892;2;895 +892;3;896 +897;0;898 +903;0;904 +903;1;905 +903;2;906 +907;0;908 +907;1;909 +910;0;911 +913;0;914 +913;1;915 +916;0;917 +916;1;918 +920;0;921 +920;1;922 +923;0;925 +927;0;928 +929;0;930 +943;0;944 +943;1;945 +947;0;948 +947;1;949 +951;0;955 +956;0;957 +958;0;959 +960;0;961 +966;0;967 +966;1;968 +970;0;973 +970;1;974 +970;2;975 +970;3;976 +970;4;977 +970;5;978 +985;0;986 +985;1;987 +988;0;989 +988;1;990 +991;0;992 +991;1;993 +991;2;994 +991;3;995 +1001;0;1004 +1001;1;1005 +1006;0;1007 +1006;1;1008 +1006;2;1009 +1015;0;1016 +1015;1;1017 +1015;2;1018 +1015;3;1019 +1015;4;1020 +1015;5;1021 +1015;6;1022 +1046;0;1047 +1046;1;1048 +1055;0;1056 +1055;1;1057 +1058;0;1059 +1060;0;1061 +1060;1;1062 +1125;0;1126 +1139;0;1140 +1139;1;1141 +1142;0;1152 +1161;0;1162 +1166;0;1167 +1180;0;1181 +1188;0;1189 +1197;0;1198 +1206;0;1207 +1206;1;1208 +1206;2;1209 +1224;0;1225 +1228;0;1229 +1232;0;1233 +1237;0;1238 +1237;1;1239 +1240;0;1241 +1240;1;1242 +1240;2;1243 +1240;3;1244 +1250;0;1252 +1266;0;1268 +1277;0;1279 +1299;0;1302 +1318;0;1321 +1335;0;1336 +1349;0;1350 +1371;0;1372 +1392;0;1393 +1392;1;1394 +1392;2;1395 +1392;3;1396 +1392;4;1397 +1408;0;1409 +1417;0;1418 +1424;0;1425 +1434;0;1436 +1434;1;1437 +1434;2;1438 +1434;3;1439 +1469;0;1471 +1469;1;1472 +1469;2;1473 +1469;3;1474 +1495;0;1497 +1507;0;1508 +1514;0;1515 +1526;0;1527 +1526;1;1528 +1526;2;1529 +1543;0;1544 +1543;1;1545 +1546;0;1547 +1556;0;1557 +1559;0;1560 +1562;0;1563 +1565;0;1566 +1568;0;1569 +1571;0;1572 +1574;0;1575 +1577;0;1578 +1580;0;1581 +1583;0;1584 +1586;0;1587 +1589;0;1590 +1592;0;1593 +1595;0;1596 +1598;0;1599 +1600;0;1601 +1603;0;1604 +1603;1;1605 +1606;0;1607 +1606;1;1608 +1609;0;1610 +1611;0;1612 +1621;0;1622 +1621;1;1623 +1621;2;1624 +1621;3;1625 +1621;4;1626 +1621;5;1627 +1621;6;1628 +1621;7;1629 +1621;8;1630 +1631;0;1632 +1631;1;1633 +1631;2;1634 +1631;3;1635 +1631;4;1636 +1631;5;1637 +1644;0;1645 +1657;0;1658 +1666;0;1667 +1680;0;1681 +1683;0;1684 +1683;1;1685 +1688;0;1689 +1688;1;1690 +1688;2;1691 +1688;3;1692 +1722;0;1723 +1722;1;1724 +1722;2;1725 +1722;3;1726 +1748;0;1749 +1748;1;1750 +1748;2;1751 +1748;3;1752 +1748;4;1753 +1748;5;1754 +1748;6;1755 +1748;7;1756 +1748;8;1757 +1748;9;1758 +1748;10;1759 +1748;11;1760 +1748;12;1761 +1767;0;1768 +1767;1;1769 +1767;2;1770 +1767;3;1771 +1767;4;1772 +1789;0;1790 +1789;1;1791 +1789;2;1792 +1789;3;1793 +1789;4;1794 +1817;0;1818 +1817;1;1819 +1817;2;1820 +1817;3;1821 +1817;4;1822 +1817;5;1823 +1817;6;1824 +1817;7;1825 +1817;8;1826 +1817;9;1827 +1817;10;1828 +1817;11;1829 +1834;0;1835 +1834;1;1836 +1834;2;1837 +1834;3;1838 +1834;4;1839 +1847;0;1848 +1862;0;1863 +1874;0;1875 +1886;0;1887 +1913;0;1914 +1926;0;1927 +1941;0;1942 +1944;0;1945 +1947;0;1948 +1950;0;1951 +1953;0;1954 +1956;0;1957 +1960;0;1963 +1964;0;1967 +1968;0;1970 +1968;1;1971 +1982;0;1984 +1982;1;1985 +1994;0;1996 +1994;1;1997 +1994;2;1998 +1994;3;1999 +1994;4;2000 +1994;5;2001 +2002;0;2003 +2002;1;2004 +2008;0;2009 +2008;1;2010 +2008;2;2011 +2008;3;2012 +2008;4;2013 +2021;0;2023 +2021;1;2024 +2021;2;2025 +2021;3;2026 +2021;4;2027 +2021;5;2028 +2021;6;2029 +2031;0;2032 +2031;1;2033 +2031;2;2034 +2031;3;2035 +2044;0;2045 +2044;1;2046 +2087;0;2090 +2087;1;2091 +2087;2;2092 +2093;0;2097 +2099;0;2101 +2099;1;2102 +2106;0;2107 +2121;0;2123 +2121;1;2124 +2127;0;2128 +2141;0;2142 +2145;0;2146 +2148;0;2149 +2150;0;2154 +2150;1;2155 +2156;0;2157 +2158;0;2159 +2166;0;2168 +2166;1;2169 +2166;2;2170 +2166;3;2171 +2166;4;2172 +2174;0;2176 +2174;1;2177 +2174;2;2178 +2179;0;2182 +2179;1;2183 +2179;2;2184 +2179;3;2185 +2179;4;2186 +2179;5;2187 +2179;6;2188 +2193;0;2196 +2207;0;2208 +2207;1;2209 +2207;2;2210 +2207;3;2211 +2207;4;2212 +2213;0;2214 +2213;1;2215 +2217;0;2220 +2217;1;2221 +2217;2;2222 +2223;0;2224 +2226;0;2227 +2226;1;2228 +2226;2;2229 +2226;3;2230 +2226;4;2231 +2226;5;2232 +2226;6;2233 +2226;7;2234 +2258;0;2260 +2258;1;2261 +2258;2;2262 +2258;3;2263 +2264;0;2265 +2264;1;2266 +2264;2;2267 +2269;0;2271 +2269;1;2272 +2273;0;2274 +2273;1;2275 +2273;2;2276 +2273;3;2277 +2273;4;2278 +2273;5;2279 +2284;0;2287 +2288;0;2289 +2288;1;2290 +2299;0;2301 +2299;1;2302 +2299;2;2303 +2299;3;2304 +2299;4;2305 +2299;5;2306 +2307;0;2308 +2309;0;2310 +2309;1;2311 +2309;2;2312 +2309;3;2313 +2309;4;2314 +2309;5;2315 +2316;0;2317 +2316;1;2318 +2316;2;2319 +2320;0;2322 +2320;1;2323 +2320;2;2324 +2320;3;2325 +2320;4;2326 +2320;5;2327 +2328;0;2329 +2330;0;2331 +2330;1;2332 +2330;2;2333 +2334;0;2335 +2334;1;2336 +2334;2;2337 +2342;0;2346 +2347;0;2349 +2347;1;2350 +2347;2;2351 +2347;3;2352 +2347;4;2353 +2347;5;2354 +2355;0;2356 +2366;0;2367 +2366;1;2368 +2366;2;2369 +2366;3;2370 +2366;4;2371 +2366;5;2372 +2379;0;2380 +2379;1;2381 +2379;2;2382 +2386;0;2387 +2386;1;2388 +2386;2;2389 +2390;0;2393 +2394;0;2395 +2394;1;2396 +2394;2;2397 +2394;3;2398 +2394;4;2399 +2394;5;2400 +2403;0;2406 +2415;0;2419 +2415;1;2420 +2421;0;2422 +2421;1;2423 +2421;2;2424 +2421;3;2425 +2429;0;2430 +2431;0;2432 +2431;1;2433 +2434;0;2435 +2436;0;2438 +2440;0;2442 +2440;1;2443 +2448;0;2450 +2448;1;2451 +2457;0;2458 +2460;0;2461 +2462;0;2463 +2462;1;2464 +2467;0;2468 +2478;0;2479 +2478;1;2480 +2478;2;2481 +2478;3;2482 +2478;4;2483 +2478;5;2484 +2502;0;2503 +2516;0;2517 +2516;1;2518 +2516;2;2519 +2516;3;2520 +2536;0;2539 +2536;1;2540 +2536;2;2541 +2536;3;2542 +2536;4;2543 +2536;5;2544 +2536;6;2545 +2546;0;2547 +2555;0;2556 +2564;0;2565 +2564;1;2566 +2564;2;2567 +2575;0;2576 +2575;1;2577 +2575;2;2578 +2575;3;2579 +2575;4;2580 +2590;0;2591 +2590;1;2592 +2594;0;2595 +2597;0;2598 +2597;1;2599 +2597;2;2600 +2604;0;2605 +2604;1;2606 +2604;2;2607 +2604;3;2608 +2619;0;2620 +2619;1;2621 +2619;2;2622 +2631;0;2632 +2631;1;2633 +2631;2;2634 +2638;0;2639 +2638;1;2640 +2638;2;2641 +2648;0;2649 +2648;1;2650 +2648;2;2651 +2661;0;2668 +2661;1;2669 +2661;2;2670 +2661;3;2671 +2661;4;2672 +2661;5;2673 +2661;6;2674 +2675;0;2676 +2689;0;2690 +2714;0;2715 +2722;0;2723 +2730;0;2731 +2738;0;2739 +2762;0;2769 +2762;1;2770 +2762;2;2771 +2762;3;2772 +2762;4;2773 +2774;0;2775 +2777;0;2778 +2780;0;2781 +2783;0;2784 +2786;0;2787 +2789;0;2790 +2793;0;2794 +2796;0;2797 +2807;0;2808 +2829;0;2830 +2838;0;2839 +2853;0;2854 +2870;0;2871 +2888;0;2889 +2903;0;2904 +2912;0;2913 +2925;0;2926 +2935;0;2936 +2945;0;2946 +2953;0;2954 +2964;0;2965 +2975;0;2976 +2985;0;2986 +2995;0;2996 +3005;0;3006 +3009;0;3010 +3013;0;3014 +3017;0;3018 +3021;0;3022 +3025;0;3026 +3029;0;3030 +3033;0;3034 +3037;0;3038 +3041;0;3042 +3045;0;3046 +3049;0;3050 +3053;0;3054 +3057;0;3058 +3061;0;3062 +3065;0;3066 +3069;0;3070 +3081;0;3082 +3091;0;3092 +3103;0;3104 +3113;0;3114 +3122;0;3123 +3126;0;3127 +3129;0;3130 +3132;0;3133 +3135;0;3136 +3139;0;3140 +3154;0;3155 +3162;0;3163 +3168;0;3169 +3177;0;3178 +3190;0;3191 +3203;0;3204 +3211;0;3212 +3220;0;3221 +3235;0;3236 +3247;0;3248 +3255;0;3256 +3274;0;3275 +3281;0;3282 +3292;0;3293 +3300;0;3301 +3313;0;3314 +3334;0;3335 +3347;0;3348 +3364;0;3365 +3373;0;3374 +3400;0;3401 +3410;0;3411 +3423;0;3424 +3436;0;3437 +3449;0;3450 +3458;0;3459 +3470;0;3471 +3481;0;3482 +3489;0;3490 +3493;0;3494 +3497;0;3498 +3501;0;3502 +3505;0;3506 +3509;0;3510 +3513;0;3514 +3517;0;3518 +3521;0;3522 +3525;0;3526 +3536;0;3537 +3545;0;3546 +3557;0;3558 +3561;0;3562 +3565;0;3566 +3569;0;3570 +3573;0;3574 +3577;0;3578 +3581;0;3582 +3585;0;3586 +3589;0;3590 +3593;0;3594 +3597;0;3598 +3601;0;3602 +3605;0;3606 +3609;0;3610 +3613;0;3614 +3617;0;3618 +3621;0;3622 +3625;0;3626 +3629;0;3630 +3633;0;3634 +3637;0;3638 +3640;0;3641 +3643;0;3644 +3646;0;3647 +3655;0;3656 +3659;0;3660 +3672;0;3673 +3681;0;3682 +3697;0;3698 +3708;0;3709 +3712;0;3713 +3716;0;3717 +3720;0;3721 +3724;0;3725 +3734;0;3735 +3742;0;3743 +3742;1;3744 +3742;2;3745 +3742;3;3746 +3742;4;3747 +3742;5;3748 +3742;6;3749 +3742;7;3750 +3742;8;3751 +3756;0;3757 +3756;1;3758 +3756;2;3759 +3756;3;3760 +3756;4;3761 +3756;5;3762 +3756;6;3763 +3765;0;3766 +3765;1;3767 +3765;2;3768 +3765;3;3769 +3770;0;3774 +3770;1;3775 +3770;2;3776 +3770;3;3777 +3779;0;3780 +3779;1;3781 +3779;2;3782 +3779;3;3783 +3787;0;3788 +3787;1;3789 +3787;2;3790 +3792;0;3793 +3792;1;3794 +3792;2;3795 +3792;3;3796 +3792;4;3797 +3792;5;3798 +3792;6;3799 +3792;7;3800 +3792;8;3801 +3792;9;3802 +3792;10;3803 +3792;11;3804 +3792;12;3805 +3792;13;3806 +3792;14;3807 +3792;15;3808 +3792;16;3809 +3792;17;3810 +3792;18;3811 +3792;19;3812 +3792;20;3813 +3814;0;3815 +3814;1;3816 +3814;2;3817 +3832;0;3833 +3832;1;3834 +3832;2;3835 +3836;0;3847 +3836;1;3848 +3849;0;3850 +3849;1;3851 +3877;0;3880 +3877;1;3881 +3877;2;3882 +3877;3;3883 +3877;4;3884 +3877;5;3885 +3877;6;3886 +3877;7;3887 +3877;8;3888 +3877;9;3889 +3877;10;3890 +3893;0;3894 +3893;1;3895 +3893;2;3896 +3893;3;3897 +3899;0;3900 +3899;1;3901 +3899;2;3902 +3937;0;3938 +3937;1;3939 +3940;0;3942 +3940;1;3943 +3945;0;3946 +3954;0;3955 +3954;1;3956 +3957;0;3959 +3957;1;3960 +3957;2;3961 +3957;3;3962 +3957;4;3963 +3957;5;3964 +3957;6;3965 +3957;7;3966 +3957;8;3967 +3973;0;3974 +3973;1;3975 +3973;2;3976 +3973;3;3977 +3973;4;3978 +3979;0;3980 +3979;1;3981 +3979;2;3982 +3989;0;3990 +3989;1;3991 +3989;2;3992 +3989;3;3993 +3989;4;3994 +3989;5;3995 +3989;6;3996 +3989;7;3997 +3989;8;3998 +3989;9;3999 +4005;0;4008 +4005;1;4009 +4005;2;4010 +4005;3;4011 +4005;4;4012 +4005;5;4013 +4005;6;4014 +4005;7;4015 +4005;8;4016 +4017;0;4018 +4017;1;4019 +4020;0;4021 +4022;0;4023 +4024;0;4025 +4024;1;4026 +4041;0;4043 +4041;1;4044 +4041;2;4045 +4041;3;4046 +4041;4;4047 +4041;5;4048 +4041;6;4049 +4041;7;4050 +4041;8;4051 +4041;9;4052 +4041;10;4053 +4041;11;4054 +4041;12;4055 +4041;13;4056 +4041;14;4057 +4041;15;4058 +4041;16;4059 +4060;0;4066 +4060;1;4067 +4060;2;4068 +4069;0;4070 +4069;1;4071 +4079;0;4080 +4079;1;4081 +4079;2;4082 +4079;3;4083 +4079;4;4084 +4079;5;4085 +4079;6;4086 +4079;7;4087 +4079;8;4088 +4079;9;4089 +4079;10;4090 +4079;11;4091 +4079;12;4092 +4079;13;4093 +4079;14;4094 +4095;0;4096 +4095;1;4097 +4095;2;4098 +4095;3;4099 +4100;0;4101 +4100;1;4102 +4100;2;4103 +4104;0;4105 +4104;1;4106 +4104;2;4107 +4104;3;4108 +4104;4;4109 +4104;5;4110 +4104;6;4111 +4104;7;4112 +4128;0;4129 +4128;1;4130 +4131;0;4132 +4139;0;4141 +4139;1;4142 +4143;0;4144 +4143;1;4145 +4143;2;4146 +4150;0;4151 +4150;1;4152 +4156;0;4157 +4156;1;4158 +4163;0;4164 +4163;1;4165 +4169;0;4170 +4169;1;4171 +4169;2;4172 +4169;3;4173 +4169;4;4174 +4169;5;4175 +4169;6;4176 +4179;0;4180 +4179;1;4181 +4182;0;4183 +4182;1;4184 +4185;0;4188 +4185;1;4189 +4190;0;4191 +4190;1;4192 +4199;0;4200 +4199;1;4201 +4199;2;4202 +4199;3;4203 +4199;4;4204 +4199;5;4205 +4206;0;4214 +4206;1;4215 +4206;2;4216 +4217;0;4219 +4217;1;4220 +4217;2;4221 +4217;3;4222 +4217;4;4223 +4217;5;4224 +4217;6;4225 +4217;7;4226 +4227;0;4228 +4227;1;4229 +4234;0;4235 +4234;1;4236 +4234;2;4237 +4234;3;4238 +4239;0;4240 +4239;1;4241 +4239;2;4242 +4239;3;4243 +4244;0;4246 +4244;1;4247 +4244;2;4248 +4244;3;4249 +4244;4;4250 +4244;5;4251 +4244;6;4252 +4253;0;4254 +4255;0;4256 +4255;1;4257 +4255;2;4258 +4259;0;4260 +4259;1;4261 +4259;2;4262 +4259;3;4263 +4259;4;4264 +4259;5;4265 +4266;0;4267 +4266;1;4268 +4266;2;4269 +4270;0;4272 +4270;1;4273 +4270;2;4274 +4275;0;4276 +4277;0;4278 +4277;1;4279 +4280;0;4281 +4280;1;4282 +4280;2;4283 +4280;3;4284 +4280;4;4285 +4286;0;4289 +4290;0;4292 +4290;1;4293 +4290;2;4294 +4295;0;4296 +4295;1;4297 +4304;0;4305 +4367;0;4368 +4367;1;4369 +4367;2;4370 +4367;3;4371 +4374;0;4375 +4374;1;4376 +4377;0;4381 +4377;1;4382 +4384;0;4385 +4384;1;4386 +4388;0;4390 +4388;1;4391 +4388;2;4392 +4393;0;4394 +4395;0;4396 +4395;1;4397 +4567;0;4568 +4567;1;4569 +4567;2;4570 +4619;0;4620 +4619;1;4621 +4619;2;4622 +4619;3;4623 +4619;4;4624 +4619;5;4625 +4619;6;4626 +4709;0;4710 +4711;0;4712 +4719;0;4720 +4719;1;4721 +4719;2;4722 +4719;3;4723 +4719;4;4724 +4728;0;4729 +4728;1;4730 +4728;2;4731 +4733;0;4739 +4740;0;4741 +4740;1;4742 +4740;2;4743 +4746;0;4747 +4746;1;4748 +4756;0;4757 +4756;1;4758 +4756;2;4759 +4756;3;4760 +4756;4;4761 +4769;0;4770 +4769;1;4771 +4769;2;4772 +4769;3;4773 +4769;4;4774 +4769;5;4775 +4769;6;4776 +4783;0;4784 +4793;0;4794 +4793;1;4795 +4793;2;4796 +4797;0;4799 +4800;0;4801 +4804;0;4805 +4806;0;4807 +4806;1;4808 +4806;2;4809 +4814;0;4815 +4825;0;4826 +4829;0;4830 +4829;1;4831 +4847;0;4849 +4850;0;4851 +4850;1;4852 +4850;2;4853 +4850;3;4854 +4850;4;4855 +4850;5;4856 +4850;6;4857 +4850;7;4858 +4879;0;4880 +4879;1;4881 +4879;2;4882 +4879;3;4883 +4884;0;4885 +4886;0;4890 +4886;1;4891 +4886;2;4892 +4886;3;4893 +4886;4;4894 +4886;5;4895 +4886;6;4896 +4897;0;4898 +4897;1;4899 +4897;2;4900 +4897;3;4901 +4907;0;4908 +4911;0;4912 +4911;1;4913 +4916;0;4917 +4916;1;4918 +4925;0;4926 +4925;1;4927 +4928;0;4929 +4928;1;4930 +4932;0;4933 +4932;1;4934 +4932;2;4935 +4941;0;4943 +4941;1;4944 +4941;2;4945 +4946;0;4947 +4946;1;4948 +4949;0;4950 +4949;1;4951 +4957;0;4960 +4961;0;4962 +4961;1;4963 +4964;0;4965 +4964;1;4966 +4967;0;4968 +4969;0;4970 +4969;1;4971 +4981;0;4986 +4981;1;4987 +4981;2;4988 +4981;3;4989 +4991;0;4992 +4993;0;4995 +4993;1;4996 +4993;2;4997 +4993;3;4998 +4993;4;4999 +5000;0;5001 +5000;1;5002 +5000;2;5003 +5000;3;5004 +5005;0;5006 +5005;1;5007 +5005;2;5008 +5005;3;5009 +5005;4;5010 +5005;5;5011 +5027;0;5028 +5027;1;5029 +5035;0;5036 +5035;1;5037 +5035;2;5038 +5039;0;5041 +5039;1;5042 +5039;2;5043 +5039;3;5044 +5046;0;5047 +5046;1;5048 +5046;2;5049 +5046;3;5050 +5056;0;5067 +5068;0;5074 +5068;1;5075 +5068;2;5076 +5068;3;5077 +5078;0;5080 +5083;0;5084 +5085;0;5087 +5091;0;5092 +5096;0;5097 +5096;1;5098 +5101;0;5103 +5101;1;5104 +5101;2;5105 +5107;0;5108 +5112;0;5113 +5112;1;5114 +5112;2;5115 +5112;3;5116 +5117;0;5119 +5117;1;5120 +5117;2;5121 +5117;3;5122 +5117;4;5123 +5127;0;5128 +5127;1;5129 +5127;2;5130 +5131;0;5132 +5131;1;5133 +5131;2;5134 +5131;3;5135 +5131;4;5136 +5131;5;5137 +5139;0;5140 +5139;1;5141 +5139;2;5142 +5139;3;5143 +5139;4;5144 +5139;5;5145 +5139;6;5146 +5149;0;5150 +5149;1;5151 +5149;2;5152 +5149;3;5153 +5149;4;5154 +5158;0;5159 +5158;1;5160 +5158;2;5161 +5158;3;5162 +5158;4;5163 +5158;5;5164 +5166;0;5167 +5166;1;5168 +5166;2;5169 +5166;3;5170 +5166;4;5171 +5166;5;5172 +5166;6;5173 +5166;7;5174 +5166;8;5175 +5178;0;5180 +5181;0;5182 +5184;0;5185 +5184;1;5186 +5187;0;5190 +5187;1;5191 +5192;0;5193 +5192;1;5194 +5192;2;5195 +5199;0;5200 +5202;0;5203 +5202;1;5204 +5202;2;5205 +5202;3;5206 +5207;0;5208 +5207;1;5209 +5207;2;5210 +5207;3;5211 +5207;4;5212 +5207;5;5213 +5217;0;5218 +5217;1;5219 +5217;2;5220 +5224;0;5225 +5224;1;5226 +5224;2;5227 +5224;3;5228 +5224;4;5229 +5224;5;5230 +5243;0;5244 +5243;1;5245 +5243;2;5246 +5243;3;5247 +5253;0;5254 +5253;1;5255 +5253;2;5256 +5253;3;5257 +5253;4;5258 +5253;5;5259 +5253;6;5260 +5253;7;5261 +5275;0;5276 +5275;1;5277 +5275;2;5278 +5275;3;5279 +5275;4;5280 +5275;5;5281 +5284;0;5285 +5284;1;5286 +5284;2;5287 +5288;0;5289 +5288;1;5290 +5288;2;5291 +5288;3;5292 +5295;0;5297 +5295;1;5298 +5295;2;5299 +5295;3;5300 +5304;0;5307 +5304;1;5308 +5304;2;5309 +5310;0;5311 +5313;0;5314 +5313;1;5315 +5313;2;5316 +5313;3;5317 +5313;4;5318 +5319;0;5320 +5319;1;5321 +5324;0;5329 +5330;0;5333 +5336;0;5337 +5341;0;5342 +5344;0;5349 +5344;1;5350 +5352;0;5354 +5352;1;5355 +5357;0;5358 +5360;0;5362 +5360;1;5363 +5360;2;5364 +5367;0;5368 +5370;0;5371 +5370;1;5372 +5370;2;5373 +5370;3;5374 +5375;0;5376 +5375;1;5377 +5375;2;5378 +5375;3;5379 +5380;0;5381 +5385;0;5391 +5385;1;5392 +5393;0;5394 +5393;1;5395 +5393;2;5396 +5397;0;5398 +5397;1;5399 +5397;2;5400 +5401;0;5402 +5401;1;5403 +5404;0;5405 +5404;1;5406 +5407;0;5408 +5409;0;5411 +5409;1;5412 +5409;2;5413 +5409;3;5414 +5409;4;5415 +5419;0;5420 +5423;0;5424 +5423;1;5425 +5423;2;5426 +5423;3;5427 +5431;0;5433 +5431;1;5434 +5442;0;5443 +5442;1;5444 +5445;0;5446 +5445;1;5447 +5468;0;5469 +5468;1;5470 +5473;0;5477 +5473;1;5478 +5496;0;5501 +5496;1;5502 +5503;0;5504 +5503;1;5505 +5506;0;5507 +5506;1;5508 +5506;2;5509 +5511;0;5514 +5511;1;5515 +5511;2;5516 +5511;3;5517 +5511;4;5518 +5511;5;5519 +5521;0;5523 +5527;0;5528 +5527;1;5529 +5531;0;5532 +5531;1;5533 +5534;0;5536 +5534;1;5537 +5542;0;5543 +5542;1;5544 +5542;2;5545 +5542;3;5546 +5549;0;5550 +5549;1;5551 +5557;0;5558 +5557;1;5559 +5557;2;5560 +5561;0;5568 +5574;0;5576 +5574;1;5577 +5574;2;5578 +5574;3;5579 +5582;0;5584 +5590;0;5594 +5595;0;5598 +5600;0;5601 +5602;0;5603 +5602;1;5604 +5602;2;5605 +5611;0;5614 +5611;1;5615 +5618;0;5619 +5618;1;5620 +5621;0;5622 +5621;1;5623 +5626;0;5627 +5626;1;5628 +5630;0;5631 +5630;1;5632 +5630;2;5633 +5635;0;5636 +5635;1;5637 +5635;2;5638 +5645;0;5646 +5645;1;5647 +5645;2;5648 +5649;0;5650 +5649;1;5651 +5649;2;5652 +5649;3;5653 +5649;4;5654 +5649;5;5655 +5649;6;5656 +5661;0;5662 +5661;1;5663 +5661;2;5664 +5665;0;5667 +5665;1;5668 +5665;2;5669 +5665;3;5671 +5665;4;5672 +5665;5;5673 +5665;6;5674 +5665;7;5675 +5665;8;5677 +5665;9;5678 +5679;0;5681 +5679;1;5682 +5679;2;5683 +5679;3;5684 +5679;4;5685 +5679;5;5686 +5679;6;5687 +5692;0;5693 +5692;1;5695 +5716;0;5718 +5716;1;5719 +5716;2;5720 +5716;3;5721 +5716;4;5722 +5724;0;5725 +5732;0;5733 +5735;0;5736 +5735;1;5737 +5735;2;5738 +5735;3;5739 +5735;4;5740 +5751;0;5753 +5751;1;5754 +5751;2;5755 +5751;3;5756 +5751;4;5757 +5751;5;5758 +5751;6;5759 +5761;0;5763 +5761;1;5764 +5761;2;5765 +5761;3;5766 +5769;0;5770 +5769;1;5771 +5781;0;5784 +5785;0;5786 +5787;0;5788 +5787;1;5789 +5790;0;5791 +5790;1;5792 +5790;2;5793 +5795;0;5796 +5795;1;5797 +5795;2;5798 +5795;3;5799 +5801;0;5802 +5801;1;5803 +5805;0;5806 +5805;1;5807 +5805;2;5808 +5805;3;5809 diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEnumeration.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEnumeration.csv new file mode 100644 index 0000000000000000000000000000000000000000..36c8403fd5fb419eb6496715e29d3f16d78011f6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocEnumeration.csv @@ -0,0 +1,5951 @@ +46;IfcRoleEnum;" +

Definition: Roles which may be played by an actor.

+ +
+HISTORY This type has changes after IFC Release 2.0. Spelling of COMMISSIONINGENGINEER fixed in IFC 2x4. +
+ +

ENUMERATION

+
    +
  • SUPPLIER
  • +
  • MANUFACTURER
  • +
  • CONTRACTOR
  • +
  • SUBCONTRACTOR
  • +
  • ARCHITECT
  • +
  • STRUCTURALENGINEER
  • +
  • COSTENGINEER
  • +
  • CLIENT
  • +
  • BUILDINGOWNER
  • +
  • BUILDINGOPERATOR
  • +
  • MECHANICALENGINEER
  • +
  • ELECTRICALENGINEER
  • +
  • PROJECTMANAGER
  • +
  • FACILITIESMANAGER
  • +
  • CIVILENGINEER
  • +
  • COMMISSIONINGENGINEER
  • +
  • ENGINEER
  • +
  • OWNER
  • +
  • CONSULTANT
  • +
  • CONSTRUCTIONMANAGER
  • +
  • FIELDCONSTRUCTIONMANAGER
  • +
  • RESELLER
  • +
  • USERDEFINED User defined value to be provided.
  • +
+ +
" +96;IfcAddressTypeEnum;" +

Definition from IAI: Identifies the logical location of the address. + +

HISTORY New type in IFC Release 2x. + +
+ +

ENUMERATION

+
    +
  • OFFICE An office address.
  • +
  • SITE A site address.
  • +
  • HOME A home address.
  • +
  • DISTRIBUTIONPOINT A postal distribution point address.
  • +
  • USERDEFINED A user defined address type to be provided.
  • +
+
" +149;IfcPerformanceHistoryTypeEnum;" + +

This enumeration is used to identify the primary purpose of performance history. The IfcPerformanceHistoryTypeEnum contains the following:

+
    +
  • USERDEFINED: User-defined.
  • +
  • NOTDEFINED: Undefined.
  • +
+ +
+HISTORY: New enumeration in IFC2x4 +
+ +
" +165;IfcPileTypeEnum;" + +

Definition from IAI: Enumeration defining the pile type.

+ +
HISTORY New type in IFC Release 2x2
+IFC 2x4 change:  Items BORED, DRIVEN, JETGROUTING added
+ +
    +
  • BORED A bore pile.
  • +
  • DRIVEN A rammed, vibrated, or otherwise driven pile.
  • +
  • JETGROUTING An injected pile-like construction.
  • +
  • COHESION A cohesion pile.
  • +
  • FRICTION A friction pile.
  • +
  • SUPPORT A support pile.
  • +
  • USERDEFINED The type of pile function is user defined.
  • +
  • NOTDEFINED The type of pile function is not defined.
  • +
+ +
" +177;IfcFootingTypeEnum;" + +

Definition from IAI: Enumeration defining the generic footing type.

+ +
HISTORY New type in IFC Release 2x2
+IFC 2x4 change:  Item CAISSON_FOUNDATION added
+ +

ENUMERATION

+
    +
  • CAISSON_FOUNDATION A foundation construction type used in underwater construction.
  • +
  • FOOTING_BEAM Footing elements that are in bending and are supported clear of the ground. They will normally span between piers, piles or pile caps. They are distinguished from beams in the building superstructure since they will normally require a lower grade of finish. They are distinguished from STRIP_FOOTING since they are clear of the ground surface and hence require support to the lower face while the concrete is curing.
  • +
  • PAD_FOOTING An element that transfers the load of a single column (possibly two) to the ground.
  • +
  • PILE_CAP An element that transfers the load from a column or group of columns to a pier or pile or group of piers or piles.
  • +
  • STRIP_FOOTING A linear element that transfers loads into the ground from either a continuous element, such as a wall, or from a series of elements, such as columns.
  • +
  • USERDEFINED Special types of footings which meet specific local requirements.
  • +
  • NOTDEFINED The type of footing is not defined.
  • +
+ +
" +188;IfcSurfaceFeatureTypeEnum;" + +

Definition from IAI: This enumeration indicates the type of a surface feature.

+ +
HISTORY New type in IFC 2x4.
+ +

ENUMERATION

+
    +
  • MARK A point, line, cross, or other mark, applied for example for easier adjustment of elements during assembly.
  • +
  • TAG A name tag, which allows to identify an element during production, delivery and assembly. May be manufactured in different ways, e.g. by printing or punching the tracking code onto the element or by attaching an actual tag.
  • +
  • TREATMENT A subtractive surface feature, e.g. grinding, or an additive surface feature, e.g. coating, or an impregnating treatment, or a series of any of these kinds of treatments.
  • +
  • USERDEFINED A user-defined type of surface feature.
  • +
  • NOTDEFINED An undefined type of surface feature.
  • +
+ +
" +197;IfcVoidingFeatureTypeEnum;" + +

Definition from IAI: This enumeration qualifies a voiding feature regarding its shape and configuration relative to the voided element.

+ +
HISTORY New type in IFC 2x4.
+ +

ENUMERATION

+
    +
  • CUTOUT An internal cutout (creating an opening) or external cutout (creating a recess) of arbitrary shape. The edges between cutting planes may be overcut or undercut, i.e. rounded.
  • +
  • NOTCH An external cutout of with a mostly rectangular cutting profile. The edges between cutting planes may be overcut or undercut, i.e. rounded.
  • +
  • HOLE A circular or slotted or threaded hole, typically but not necessarily of smaller dimension than what would be considered a cutout.
  • +
  • MITER A skewed plane end cut, removing material across the entire profile of the voided element.
  • +
  • CHAMFER A skewed plane end cut, removing material only across a part of the profile of the voided element.
  • +
  • EDGE A shape modification along an edge of the element with the edge length as the predominant dimension of the feature, and feature profile dimensions which are typically much smaller than the edge length. Can for example be a chamfer edge (differentiated from a chamfer by its ratio of dimensions and thus usually manufactured differently), rounded edge (a convex edge feature), or fillet edge (a concave edge feature).
  • +
  • USERDEFINED A user-defined type of voiding feature.
  • +
  • NOTDEFINED An undefined type of voiding feature.
  • +
+ +
" +215;IfcPileConstructionEnum;" +

Definition from IAI: Enumeration defining the construction type + for piles. The type is mainly based on how the piles are used and manufactured. + Some material information is mixed in because this affects the way the piles + are used.

+
+

HISTORY New type in IFC Release 2x2 +

+

ENUMERATION

+
    +
  • CAST_IN_PLACE Piles and piers that are excavated and poured in + place.
  • +
  • COMPOSITE Piles that are a mix of components, such as a steel + outer casing which is driven into the ground with a cast-in-place concrete + core.
  • +
  • PRECAST_CONCRETE Piles that are entirely of precast concrete + (possibly with some steel or other fixtures).
  • +
  • PREFAB_STEEL Prefabricated piles made entirely out of steel. + It will also include steel sheet piles where these are not part of another + construction element.
  • +
  • USERDEFINED Special types of pile construction which meet + specific local requirements.
  • +
  • NOTDEFINED The type of pile construction is not defined.
  • + +
+
" +240;IfcReinforcingElementTypeEnum; +383;IfcCurveInterpolationEnum;" + +

IfcCurveInterpolationEnum specifies the possible methods +for the interpolation of property values given as a curve.

+ +
+HISTORY  New type in IFC2x4. +
+ +

Enumeration

+
    +
  • LINEAR: Indicates that values between the defined +values are to be found by linear interpolation.
  • +
  • LOG_LINEAR: Indicates that values between the defined +values are to be found by linear interpolation of the natural +logarithm (base e) of the values.
  • +
  • LOG_LOG: Indicates that values between the defined +values are to be found by linear interpolation of the Briggs' +logarithm (base 10) of the values.
  • +
  • NOTDEFINED: No interpolation information is +provided
  • +
+ +
" +566;IfcSpaceTypeEnum;" +

Definition from IAI: This enumeration defines the +available generic types for IfcSpace and +IfcSpaceType.

+
HISTORY New enumeration +in IFC2x3.
+IFC2x4 CHANGE The enumerators +INTERNAL and EXTERNAL have been added for upward compatibility to +replace InteriorOrExteriorSpace +usage.
+

Enumeration

+
    +
  • SPACE Any space not falling into another category.
    +
      +
    • NOTE For classification of spaces according to its +function that is often determined by national classification +systems use IfcClassificationReference via the +relationship IfcRelAssociatesClassification.
    • +
    +
  • +
  • PARKING A space dedication for use as a parking spot +for vehicles, including access, such as a parking aisle
  • +
  • GFA Gross Floor Area - a specific kind of space for +each building story that includes all net area and construction +area (also the external envelop). Provision of such a specific +space is often required by regulations.
  • +
  • INTERNAL
    +
      +
    • NOTE the use is deprecated and +only provided for backward compatibility +purposes.
    • +
    +
  • +
  • EXTERNAL
    +
      +
    • NOTE the use is deprecated and +only provided for backward compatibility +purposes.
    • +
    +
  • +
+
" +577;IfcSpatialZoneTypeEnum;" +

Definition from IAI: This enumeration defines the range +of different types of spatial zones that can further specify an +IfcSpatialZoneTypeEnum.

+
HISTORY New enumeration +in IFC Release 2x Edition 4.
+

Enumeration

+
    +
  • CONSTRUCTION: the spatial zone is used +to represent a construction zone for the production process
  • +
  • FIRESAFETY: the spatial zone is used to +represent a fire safety zone, or fire compartment
  • +
  • LIGHTING: the spatial zone is used to +represent a lighting zone, e.g. a daylight zone, or a artificial +lighting zone
  • +
  • OCCUPANCY: the spatial zone is used to +represent a zone of particular occupancy
  • +
  • SECURITY: the spatial zone is used to +represent a zone for security planning and maintainance +work.
  • +
  • THERMAL: the spatial zone is used to +represent a thermal zone
  • +
  • USERDEFINED: user defined type spatial +zone
  • +
  • NOTDEFINED: undefined type spatial +zone
  • +
+
" +593;IfcTransportElementTypeEnum;" +

Definition from IAI: This enumeration is used to +identify primary transport element types. The +IfcTransportElementTypeEnum contains the following:

+
    +
  • ELEVATOR: Elevator or lift being a transport device to +move people of good vertically.
  • +
  • ESCALATOR: Escalator being a transport device to move +people. It consists of individual linked steps that move up and +down on tracks while keeping the threads horizontal.
  • +
  • MOVINGWALKWAY: Moving walkway being a transport device +to move people horizontally or on an incline. It is a slow +conveyor belt that transports people.
  • +
  • CRANEWAY: A crane way system, normally including the +crane rails, fasteners and the crane. It is primarily used to +move heavy goods in a factory or other industry buildings.
  • +
  • LIFTINGGEAR: A device used for lifting or lowering +heavy goods. It may be manually operated or electrically or +pneumatically driven.
  • +
+
+
HISTORY  New enumeration +in IFC Release 2x.
+IFC2x4 CHANGE  New enumerators +CRANEWAY and LIFTINGGEAR added in +IFC2x4.
+
+
" +604;IfcGeographicElementTypeEnum; +610;IfcElementAssemblyTypeEnum;" +

+ Definition from IAI: An enumeration defining the + basic configuration types for element assemblies. +

+
+

+ HISTORY New enumeration type + in Release IFC2x Edition 2. +

+
+

Enumeration

+
    +
  • ACCESSORY_ASSEMBLY: Assembled accessories or components
  • +
  • ARCH: A curved structure
  • +
  • BEAM_GRID: Interconnected beams, located in one (typically horizontal) plane
  • +
  • BRACED_FRAME: A rigid frame with additional bracing members
  • +
  • GIRDER: A beam-like superstructure
  • +
  • REINFORCEMENT_UNIT: Assembled reinforcement elements
  • +
  • RIGID_FRAME: A structure built up of beams, columns, etc. with moment-resisting joints
  • +
  • SLAB_FIELD: Slabs, laid out in one plane
  • +
  • TRUSS: A structure built up of members with (quasi) pinned joints
  • +
  • USERDEFINED: User-defined element assembly
  • +
  • NOTDEFINED: Undefined element assembly
  • +
+
" +652;IfcProjectionElementTypeEnum;" +

Definition from IAI: An enumeration defining the basic +types for projection elements.

+
+

HISTORY New enumeration type in +IFC2x4.

+
+

Enumeration

+
    +
  • USERDEFINED: User-defined projection +element
  • +
  • NOTDEFINED: Undefined projection +element
  • +
+
" +671;IfcOpeningElementTypeEnum;" +

Definition from IAI: An enumeration defining the basic +types for opening elements.

+
+

HISTORY New enumeration type in +IFC2x4.

+
+

Enumeration

+
    +
  • OPENING: An opening as subtraction +feature that cuts through the element it voids. It thereby +creates a hole. An opening in addiion have a particular meaning +for either providing a void for doors or windows, or an opening +to permit flow of air and passing of light,
  • +
  • RECESS: A opening as subtraction +feature that does not cut through the element it voids. It +creates a niche or similar voiding pattern.
  • +
  • USERDEFINED: User-defined opening +element
  • +
  • NOTDEFINED: Undefined opening +element
  • +
+
" +684;IfcAssemblyPlaceEnum;" +

+ Definition from IAI: Enumeration defining where the + assembly is intended to take place, either in a factory or + on the building site. +

+
+

+ HISTORY New enumeration in + Release IFC2x Edition 2. +

+
+

+ Enumeration +

+
    +
  • SITE - this assembly is assembled at site +
  • +
  • FACTORY - this assembly is assembled in a factory +
  • +
+
" +728;IfcExternalSpatialElementTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of external spatial elements.

+

Enumeration:

+
    +
  • EXTERNAL - External air space around the building.
  • +
  • EXTERNAL_EARTH - External volume covered by earth around the +building.
  • +
  • EXTERNAL_WATER - External volume covered with water around +the building.
  • +
  • EXTERNAL_FIRE - Space occupied by a neightboring +building.
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
+
HISTORY New enumeration +in IFC2x4.
+
" +750;IfcElementCompositionEnum;" +

+ Definition from IAI: Enumeration that provides an + indication, whether the spatial structure element or proxy + represents a: +

+
    +
  • COMPLEX - a group or aggregation of similar elements +
  • +
  • ELEMENT - a (undivided) element itself +
  • +
  • PARTIAL - a subelement or part +
  • +
+
+ HISTORY New enumeration in + IFC Release 2.x +
+
" +754;IfcPhysicalOrVirtualEnum;" +

+ Definition from IAI: This enumeration defines the + different types of space boundaries in terms of its + physical manifestation. A space boundary can either be + physically dividing or can be a virtual divider. +

+

+ Enumeration: +

+ + + + + + + + + + + + + +
+ PHYSICAL + + The space boundary is provided physically, i.e. by an + physical element. +
+ VIRTUAL + + The space boundary is provided virtually, i.e. by a + logical divider that has no physical manifestation. +
+ NOTDEFINED + + No information available. +
+
+ HISTORY: New enumeration in + IFC Release 2.0 +
+
" +758;IfcInternalOrExternalEnum;" +

Definition from IAI: This enumeration defines the +different types of space boundaries in terms of either being +inside the building or outside the building.

+

Enumeration:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
INTERNAL
+IfcSpaceBoundaryThe space boundary faces a physical +or virtual element where there is an internal space on the other +side.
EXTERNAL
+IfcSpaceBoundaryThe space boundary faces a physical +or virtual element where there is an external space on the other +side (i.e. air). Or it is the space boundary of that external +space against the building.
EXTERNAL_EARTH
+IfcSpaceBoundaryThe space boundary faces a physical +or virtual element where there is earth (or terrain) on the other +side. Or it is the space boundary of that earth (or terrain +object) external space against the building.
EXTERNAL_WATER
+IfcSpaceBoundaryThe space boundary faces a physical +or virtual element where there is water (water component of +terrain) on the other side. Or it is the space boundary of that +object representing water external space against the +building.
EXTERNAL_FIRE
+IfcSpaceBoundaryThe space boundary faces a physical +or virtual element where there is another building on the other +side. Or it is the space boundary of that other neighbor building +against the building in question.
NOTDEFINED
No information available.
+
HISTORY: New enumeration +in IFC Release 2.0
+IFC2x4 CHANGE: Enumeration no longer +applicable to IfcSpace. The following enumerators are +added: EXTERNAL_EARTH, EXTERNAL_WATER, +EXTERNAL_FIRE.
+
" +931;IfcObjectTypeEnum;" + +

This enumeration defines the applicable object categories, that is, the subtypes at the 2nd level of the IFC inheritance tree. Attached to an object, it indicates to which subtype of IfcObject the entity referencing it would otherwise comply with.

+ +
+HISTORY New entity in IFC Release 1.0, has been renamed from IfcProxyEnum in IFC 2x. +
+ +
" +1012;IfcComplexPropertyTemplateTypeEnum;" + +

This enumeration defines the subtype of instances of IfcComplexProperty or IfcPhysicalComplexQuantity that may be created and defined by an IfcComplexPropertyTemplate.

+ +
+HISTORY New enumeration in IFC2x4. +
+ +

Enumeration

+
    +
  • P_COMPLEX: the properties defined by this IfcComplexPropertyTemplate are of type IfcComplexProperty.
  • +
  • Q_COMPLEX: the properties defined by this IfcComplexPropertyTemplate are of type IfcPhysicalComplexQuantity.
  • +
+
" +1023;IfcSimplePropertyTemplateTypeEnum;" + +

This enumeration defines the correct subtype of instances of IfcSimpleProperty or IfcPhysicalSimpleQuantity that are created and are assigned to this IfcSimplePropertyTemplate. It also determines how the attributes of IfcPropertyTemplate, PrimaryUnit, SecondaryUnit, PrimaryDataType, SecondaryDataType, should be used.

+ +
+HISTORY New enumeration in IFC2x4. +
+ +

Enumeration

+
    +
  • P_SINGLEVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertySingleValue.
  • +
  • P_ENUMERATEDVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertyEnumeratedValue.
  • +
  • P_BOUNDEDVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertyBoundedValue.
  • +
  • P_LISTVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertyListValue.
  • +
  • P_TABLEVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertyTableValue.
  • +
  • P_REFERENCEVALUE: the properties defined by this IfcPropertyTemplate are of type IfcPropertyReferenceValue.
  • +
  • Q_LENGTH: the properties defined by this IfcPropertyTemplate are of type IfcQuantityLength.
  • +
  • Q_AREA: the properties defined by this IfcPropertyTemplate are of type IfcQuantityArea.
  • +
  • Q_VOLUME: the properties defined by this IfcPropertyTemplate are of type IfcQuantityVolume.
  • +
  • Q_COUNT: the properties defined by this IfcPropertyTemplate are of type IfcQuantityCount.
  • +
  • Q_WEIGHT: the properties defined by this IfcPropertyTemplate are of type IfcQuantityWeight.
  • +
  • Q_TIME: the properties defined by this IfcPropertyTemplate are of type IfcQuantityTime.
  • +
+ +
" +1036;IfcPropertySetTemplateTypeEnum;" + +

This enumeration defines the general +applicability of instances of IfcPropertySet, or +IfcElementQuantity defined by this +IfcPropertySetTemplate, to subtypes of +IfcObjectDefinition.

+ +
+HISTORY New enumeration in IFC2x4. +
+ +

Enumeration

+
    +
  • PSET_TYPEDRIVENONLY: the property sets +defined by this IfcPropertySetTemplate can only be assigned +to subtypes of IfcTypeObject.
  • +
  • PSET_TYPEDRIVENOVERRIDE: the property +sets defined by this IfcPropertySetTemplate can be assigned +to subtypes of IfcTypeObject and can be overridden by a +property set with same name at subtypes of IfcObject.
  • +
  • PSET_OCCURRENCEDRIVEN: the property sets +defined by this IfcPropertySetTemplate can only be assigned +to subtypes of IfcObject.
  • +
  • PSET_PERFORMANCEDRIVEN: the property sets +defined by this IfcPropertySetTemplate can only be assigned +to IfcPerformanceHistory,
  • +
  • QTO_TYPEDRIVENONLY: the element quantity +defined by this IfcPropertySetTemplate can only be assigned +to subtypes of IfcTypeObject.
  • +
  • QTO_TYPEDRIVENOVERRIDE: the element +quantity defined by this IfcPropertySetTemplate can be +assigned to subtypes of IfcTypeObject and can be overridden +by an element quantity with same name at subtypes of +IfcObject.
  • +
  • QTO_OCCURRENCEDRIVEN: the element +quantity defined by this IfcPropertySetTemplate can only be +assigned to subtypes of IfcObject.
  • +
  • NOTDEFINED: No +restriction provided, the property sets defined by this +IfcPropertySetTemplate can be assigned to any entity, if not +otherwise restricted by the ApplicableEntity attribute.
  • +
+ +
" +1063;IfcFlowDirectionEnum;" +

This enumeration defines the flow direction at a port as either a SOURCE, SINK, or SOURCEANDSINK. For solids, liquids, or gas, the direction is the physical flow direction. For electric power (circuits containing hot, neutral, ground), the direction is from the origination of power (from a distribution board to protective devices to switches to fixtures). For communication signals, the direction originates from where the signal is shaped, such as a sensor. For communicaton networks, the direction originates from the up-level network host, such as a router (having SOURCE ports) hosting multiple computers (having SINK ports).

+
    +
  • SOURCE: A flow source, where a substance flows out of the connection.
  • +
  • SINK: A flow sink, where a substance flows into the connection.
  • +
  • SOURCEANDSINK: Both a source and sink, where a substance flows both into and out of the connection simultaneously.
  • +
  • NOTDEFINED: Undefined flow direction.
  • +
+ +
+HISTORY: New enumeration in IFC R2.0
+
+
" +1068;IfcDistributionSystemEnum;" +

This enumeration identifies different types of distribution systems.

+ +
+ + HISTORY: New enumeration in IFC R2x4
+
+
+ +

Valid enumerations for pipes and related elements include:

+
    +
  • CHEMICAL: Arbitrary chemical further qualified by property set, such as for medical or industrial use.
  • +
  • CHILLEDWATER: Nonpotable chilled water, such as circulated through an evaporator.
  • +
  • COMPRESSEDAIR: Compressed air system.
  • +
  • CONDENSERWATER: Nonpotable water, such as circulated through a condensor.
  • +
  • DOMESTICCOLDWATER: Unheated potable water distribution system.
  • +
  • DOMESTICHOTWATER: Heated potable water distribution system.
  • +
  • DRAINAGE: Drainage collection system.
  • +
  • FIREPROTECTION: Fire protection sprinkler system.
  • +
  • GAS: Methane distribution system.
  • +
  • HAZARDOUS: Hazardous material or fluid collection system.
  • +
  • HEATING: Heated water distribution system.
  • +
  • OIL: Oil distribution system.
  • +
  • RAINWATER: Rainwater resulting from precipitation which directly falls on a parcel.
  • +
  • REFRIGERATION: Refrigerant distribution system for purposes of fulfilling all or parts of a refrigeration cycle.
  • +
  • SEWAGE: Sewage collection system.
  • +
  • STORMWATER: Stormwater resulting from precipitation which runs off or travels over the ground surface.
  • +
  • VACUUM: Vacuum distribution system.
  • +
  • VENT: Vent system for wastewater piping systems.
  • +
  • WASTE: Waste collection system.
  • +
+ +

Valid enumerations for ducts and related elements include:

+
    +
  • AIRCONDITIONING: Conditioned air distribution system for purposes of maintaining a temperature range within one or more spaces.
  • +
  • EXHAUST: Exhaust air collection system for removing stale or noxious air from one or more spaces.
  • +
  • VENTILATION: Ventilation air distribution system involved in either the exchange of air to the outside as well as circulation of air within a building.
  • +
+ +

Valid enumerations for cables and related elements include:

+
    +
  • AUDIOVISUAL: A transport of a single media source, having audio and/or video streams.
  • +
  • CONTROL: A transport or network dedicated to control system usage.
  • +
  • DATA: A network having general-purpose usage.
  • +
  • EARTHING: A path for equipotential bonding, conducting current to the ground.
  • +
  • ELECTRICAL: A circuit for delivering electrical power.
  • +
  • ELECTROACCOUSTIC: An amplified audio signal such as for loudspeakers.
  • +
  • LIGHTING: A circuit dedicated for lighting, such as a fixture having sockets for lamps.
  • +
  • LIGHTNINGPROTECTION: A path for conducting lightning current to the ground.
  • +
  • POWERGENERATION: A path for power generation.
  • +
  • SECURITY: A transport or network dedicated to security system usage.
  • +
  • SIGNAL: A raw analog signal, such as modulated data or measurements from sensors.
  • +
  • TELEPHONE: A transport or network dedicated to telephone system usage.
  • +
  • TV: A transport of multiple media sources (e.g. analog cable, satellite, over-the-air).
  • +
+ +
" +1128;IfcDistributionChamberElementTypeEnum;" +

This enumeration identifies different types of distribution chambers.

+ +

Valid enumerations are:

+
    + +
  • FORMEDDUCT: Space formed in the ground for the passage of pipes, cables, ducts.
  • +
  • INSPECTIONCHAMBER: Chamber constructed on a drain, sewer or pipeline with a removable cover that permits visble inspection.
  • +
  • INSPECTIONPIT: Recess or chamber formed to permit access for inspection of substructure and services.
  • +
  • MANHOLE: Chamber constructed on a drain, sewer or pipeline with a removable cover that permits the entry of a person.
  • +
  • METERCHAMBER: Chamber that houses a meter(s).
  • +
  • SUMP: Recessed or small chamber into which liquid is drained to facilitate its collection for removal.
  • +
  • TRENCH: Excavated chamber, the length of which typically exceeds the width.
  • +
  • VALVECHAMBER: Chamber that houses a valve(s).
  • +
  • USERDEFINED: User-defined chamber type.
  • +
  • NOTDEFINED: Undefined chamber type.
  • + +
+ +
+HISTORY: New enumeration in IFC R2x2
+
+
" +1183;IfcBuildingElementPartTypeEnum;" +

Definition from IAI: This enumeration defines the different types of building element parts:

+
    +
  • INSULATION: The part provides thermal insulation, for example as insulation layer between wall panels in sandwich walls or as infill in stud walls.
  • +
  • PRECASTPANEL: The part is a precast panel, usually as an internal or external layer in a sandwich wall panel.
  • +
  • USERDEFINED: User-defined accessory
  • +
  • NOTDEFINED: Undefined accessory
  • +
+
+HISTORY  New Enumeration in IFC 2x4. +
+
" +1191;IfcDiscreteAccessoryTypeEnum;" +

Definition from IAI: This enumeration defines the different types of discrete accessories:

+
    +
  • ANCHORPLATE: An accessory consisting of a steel plate, shear stud connectors or welded-on rebar which is embedded into the surface of a concrete element so that other elements can be welded or bolted onto it later.
  • +
  • BRACKET: An L-shaped or similarly shaped accessory attached in a corner between elements to hold them together or to carry a secondary element.
  • +
  • SHOE: A column shoe or a beam shoe (beam hanger) used to support or secure an element.
  • +
  • USERDEFINED: User-defined accessory
  • +
  • NOTDEFINED: Undefined accessory
  • +
+
+HISTORY  New Enumeration in IFC 2x4. +
+
" +1200;IfcFastenerTypeEnum;" +

Definition from IAI: This enumeration defines the different types of fasteners, except for mechanical fasteners:

+
    +
  • GLUE: A fastening connection where glue is used to join together elements.
  • +
  • MORTAR: A composition of mineralic or other materials used to fill jointing gaps and possibly fulfilling a load carrying role.
  • +
  • WELD: A weld seam between parts of metallic material or other suitable materials.
  • +
  • USERDEFINED: User-defined fastener
  • +
  • NOTDEFINED: Undefined fastener
  • +
+
+HISTORY  New Enumeration in IFC 2x4. +
+
" +1211;IfcMechanicalFastenerTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of mechanical fasteners:

+
    +
  • ANCHORBOLT: A special bolt which is anchored into conrete, stone, or brickwork.
  • +
  • BOLT: A threaded cylindrical rod that engages with a similarly threaded hole in a nut or any other part to form a fastener. The mechanical fastener often also includes one or more washers and one or more nuts.
  • +
  • DOWEL: A cylindrical rod that is driven into holes of the connected pieces.
  • +
  • NAIL: A thin pointed piece of metal that is hammered into materials as a fastener.
  • +
  • NAILPLATE: A piece of sheet metal with punched points that overlaps the connected pieces and is pressed into their material.
  • +
  • RIVET: A fastening part having a head at one end and the other end being hammered flat after being passed through holes in the pieces that are fastened together.
  • +
  • SCREW: A fastener with a tapered threaded shank and a slotted head.
  • +
  • SHEARCONNECTOR: A ring connector that is accepted by ring keyways in the connected pieces; or a toothed circular or square connector that is pressed into the connected pieces.
  • +
  • STAPLE: A doubly pointed piece of metal that is hammered into materials as a fastener.
  • +
  • STUDSHEARCONNECTOR: Stud shear connectors are cylindrical fastening parts with a head on one side. On the other side they are welded on steel members for the use in composite steel and concrete structures.
  • +
  • USERDEFINED: User-defined mechanical fastener
  • +
  • NOTDEFINED: Undefined mechanical fastener
  • +
+
+HISTORY  New Enumeration in IFC 2x4. +
+
" +1245;IfcConnectionTypeEnum;" + +

This enumeration defines the different ways how path based elements (such as IfcWallStandardCase) can connect, as shown in Figure 65.

+ +
HISTORY New type in IFC Release 2.0
+ + +
+ + + + + + + + + + + + + +
+

L-Shape Connection

+
    +
  • RelatingConnectionType: AtStart
  • +
  • RelatedConnectionType: AtStart
  • +
+

L-Shape Connection

+
    +
  • RelatingConnectionType: AtEnd
  • +
  • RelatedConnectionType: AtStart
  • +
+

T-Shape Connection

+
    +
  • RelatingConnectionType: AtPath
  • +
  • RelatedConnectionType: AtStart
  • +
+

Figure 65 — Connection types

+
+ +
" +1257;IfcBeamTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of linear elements an IfcBeamType object +can fulfill:

+
    +
  • BEAM: A standard beam usually used horizontally.
  • +
  • JOIST: A beam used to support a floor or ceiling.
  • +
  • HOLLOWCORE: A wide often prestressed beam with a +hollow-core profile that usually serves as a slab component.
  • +
  • LINTEL: A beam or horizontal piece of material over an +opening (e.g. door, window).
  • +
  • SPANDREL: A tall beam placed on the facade of a +building. One tall side is usually finished to provide the +exterior of the building. Can be used to support joists or slab +elements on its interior side.
  • +
  • +
    NOTE  They are also referred to as ""spandrel +panels"", which are parts of a facade and sometimes have +supporting consoles for floor slabs +integrated.
    +
  • +
  • T_BEAM: A beam that forms part of a slab construction +and acts together with the slab which its carries. Such beams are +often of T-shape (therefore the English name), but may have other +shapes as well, e.g. an L-Shape or an Inverted-T-Shape.
  • +
  • +
    NOTE  In order to distinguish beams by shape, +the assigned IfcProfileDef subtypes provide the shape type +and, if using a subtype of +IfcParameterizedProfileDef, also the shape +parameterization.
    +
  • +
  • USERDEFINED: User-defined linear beam element.
  • +
  • NOTDEFINED: Undefined linear beam element
  • +
+
HISTORY  New Enumeration +in Release IFC2x Edition 2.
+IFC2x4 CHANGE  The enumerators +HOLLOWCORE and SPANDREL have been +added.
+
" +1273;IfcColumnTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of linear elements an IfcColumnType object +can fulfill:

+
    +
  • COLUMN: A standard column element usually used +vertically.
  • +
  • USERDEFINED: User-defined linear element.
  • +
  • NOTDEFINED: Undefined linear element
  • +
+
NOTE: This enumeration has been mainly +introduced to allow further detailing of the type information in +future releases of IFC.
+
HISTORY New Enumeration +in Release IFC2x Edition 2.
+
" +1284;IfcMemberTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of linear elements an IfcMemberType object +can fulfill:

+
    +
  • BRACE: A linear element (usually sloped) often used +for bracing of a girder or truss.
  • +
  • CHORD: Upper or lower longitudinal member of a truss, +used horizontally or sloped.
  • +
  • COLLAR: A linear element (usually used horizontally) +within a roof structure to connect rafters and posts.
  • +
  • MEMBER: A linear element within a girder or truss with +no further meaning.
  • +
  • MULLION: A linear element within a curtain wall system +to connect two (or more) panels.
  • +
  • PLATE: A linear continuous horizontal element in wall +framing, e.g. a head piece or a sole plate.
  • +
  • +
    NOTE  This head piece or sole plate shall not +be mixed up with planar elements, such as sheets and panels, that +are handled as IfcPlate (and +IfcPlateType).
    +
  • +
  • POST: A linear member (usually used vertically) within +a roof structure to support purlins.
  • +
  • PURLIN: A linear element (usually used horizontally) +within a roof structure to support rafters
  • +
  • RAFTER: A linear elements used to support roof slabs +or roof covering, usually used with slope.
  • +
  • STRINGER: A linear element used to support stair or +ramp flights, usually used with slope.
  • +
  • STRUT: A linear element often used within a girder or +truss.
  • +
  • STUD: Vertical element in wall framing.
  • +
  • USERDEFINED: User-defined linear element.
  • +
  • NOTDEFINED: Undefined linear element
  • +
+
HISTORY: New +Enumeration in Release IFC2x Edition 2.
+
IFC2x Edition 2 +Addendum 1 CHANGE  The additional identifiers CHORD, PLATE, STUD +are added.
+IFC2x Edition 3 CHANGE  The additional identifier MULLION has +been added.
+
" +1309;IfcWallTypeEnum;" +

Definition from IAI: This enumeration defines the +different types of walls an IfcWallType object can +fulfill:

+
    +
  • STANDARD: A standard wall, extruded vertically with a +constant thickness along the wall path.
  • +
  • POLYGONAL: A polygonal wall, extruded vertically, +where the wall thickness varies along the wall path.
  • +
  • SHEAR: A wall having a non-rectangular cross section +along the wall path. +
      +
    • NOTE The potentially misleading term shall not impose +a particular resistance against shear forces, but a particular +shape.
    • +
    +
  • +
  • ELEMENTEDWALL: A stud wall framed with studs and faced +with sheatings, sidings, wallboard, or plasterwork.
  • +
  • PLUMBINGWALL: A pier, or enclosure, or encasement, +normally used to enclose plumbing in sanitary rooms.
  • +
  • MOVABLE: A movable wall that is either movable, e.g. a +folding wall, or a sliding wall, or can be easily removed as a +removable partitioning or mounting wall. Movable walls do +normally not define space boundaries and often belong to the +furnishing system.
  • +
  • USERDEFINED: User-defined wall element.
  • +
  • NOTDEFINED: Undefined wall element
  • +
+
HISTORY  New +Enumeration in Release IFC2x Edition 2.
+
IFC2x2 ADDENDUM CHANGE  +The enumerator POLYGON has been changed to +POLYGONAL.
+IFC2x3 CHANGE  The enumerators +ELEMENTEDWALL and PLUMBINGWALL have been +added.
+IFC2x4 CHANGE  New enumerator +MOVABLE has been added.
+
" +1328;IfcSlabTypeEnum;" +

+ Definition from IAI: This enumeration defines the + available predefined types of a slab. The + IfcSlabTypeEnum can be used for slab occurrences, + IfcSlab, and slab types, IfcSlabType. A + special property set definition may be provided for each + predefined type. +

+
+

+ HISTORY  New type in IFC + Release 2.0 +

+
+ + + + + + + + + + + + + + + + + + + +
+ Floor + + The slab is used to represent a floor slab.
+
+ Roof + + The slab is used to represent a roof slab (either + flat or sloped).
+
+ Landing + + The slab is used to represent a landing within a + stair or ramp.
+
+ BaseSlab + + The slab is used to represent a floor slab against + the ground (and thereby being a part of the + foundation). Another name is mat foundation.
+
+ IFC2x3 CHANGE +  new enumerator added. +
+
+
" +1340;IfcRampTypeEnum;" + +

This enumeration defines the basic configuration of the ramp type in terms of the number and shape of ramp flights, as shown in Figure 67. The type also distinguished turns by landings. In addition the subdivision of the straight and changing direction ramps is included. The ramp configurations are given for ramps without and with one and two landings.

+ +

Ramps which are subdivided into more than two landings have to be defined by the geometry only. Also ramps with non-regular shapes have to be defined by the geometry only. The type of such ramps is USERDEFINED.

+ +
HISTORY New Enumeration in IFC Release 2.0.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
StraightRunRampA ramp - which is a sloping + floor, walk, or roadway - connecting two levels. The straight ramp consists of + one straight flight without turns or winders.
TwoStraightRunRampA straight ramp consisting of + two straight flights without turns but with one landing.
QuarterTurnRampA ramp making a 90° turn, + consisting of two straight flights connected by a quarterspace landing. The + direction of the turn is determined by the walking line.
TwoQuarterTurnRampA ramp making a 180° + turn, consisting of three straight flights connected by two quarterspace + landings. The direction of the turn is determined by the walking line.
HalfTurnRampA ramp making a 180° + turn, consisting of two straight flights connected by a halfspace landing. The + orientation of the turn is determined by the walking line.
SpiralRampA ramp constructed around a + circular or elliptical well without newels and landings.
UserDefinedFree form ramp (user defined + operation type) 
NotDefined  
+

Figure 67 — Ramp types

+ +
" +1354;IfcStairTypeEnum;" + +

This enumeration defines the basic configuration of the stair type in terms of the number of stair flights and the number of landings, as illustrated in Figure 69. The type also distinguished turns by windings or by landings. In addition the subdivision of the straight and changing direction stairs is included. The stair configurations are given for stairs without and with one, two or three landings.

+ +

Stairs which are subdivided into more than three landings have to be defined by the geometry only. Also stairs with non-regular shapes have to be defined by the geometry only. The type of such stairs is OTHEROPERATION.

+ +
HISTORY New Enumeration in IFC Release 2.0.
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
StraightRunStair
A stair extending from + one level to another without turns or winders. The stair consists of one + straight flight.
TwoStraightRunStair
A straight stair + consisting of two straight flights without turns but with one landing.
QuarterWindingStair
A stair consisting of one + flight with a quarter winder, which is making a 90° turn. The direction of + the turn is determined by the walking line.
QuarterTurnStair
A stair making a 90° + turn, consisting of two straight flights connected by a quarterspace landing. + The direction of the turn is determined by the walking line.
HalfWindingStair
A stair consisting of one + flight with one half winder, which makes a 180° turn. The orientation of + the turn is determined by the walking line.
HalfTurnStairA stair making a 180° + turn, consisting of two straight flights connected by a halfspace landing. The + orientation of the turn is determined by the walking line.
TwoQuarterWindingStairA stair consisting of one + flight with two quarter winders, which make a 90° turn. The stair makes a + 180° turn. The direction of the turns is determined by the walking + line.
TwoQuarterTurnStairA stair making a 180° + turn, consisting of three straight flights connected by two quarterspace + landings. The direction of the turns is determined by the walking line.
ThreeQuarterWindingStairA stair consisting of one + flight with three quarter winders, which make a 90° turn. The stair makes a + 270° turn. The direction of the turns is determined by the walking + line.
ThreeQuarterTurnStairA stair making a 270° + turn, consisting of four straight flights connected by three quarterspace + landings. The direction of the turns is determined by the walking line.
SpiralStair
A stair constructed with + winders around a circular newel often without landings. Depending on outer + boundary it can be either a circular, elliptical or rectangular spiral stair. + The orientation of the winding stairs is determined by the walking line.
DoubleReturnStair
A stair having one + straight flight to a wide quarterspace landing, and two side flights from that + landing into opposite directions. The stair is making a 90° turn. The + direction of traffic is determined by the walking line.
CurvedRunStairA stair extending from one + level to another without turns or winders. The stair is consisting of one + curved flight.
TwoCurvedRunStairA curved stair consisting of + two curved flights without turns but with one landing.
OtherOperationFree form stair (user defined + operation type) 
NotDefined  
+ +

Figure 69 — Stair types

+ + +
" +1376;IfcRoofTypeEnum;" + +

This enumeration defines the basic configuration of the roof in terms of the different roof shapes, as illustrated in Figure 68.

+ +

Roofs which are subdivided into more than these basic shapes have to be defined by the geometry only. Also roofs with non-regular shapes (free form roof) have to be defined by the geometry only. The type of such roofs is FREEFORM.

+ +
HISTORY New Enumeration in IFC Release 2x.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
FLAT_ROOFA roof having no slope, or + one with only a slight pitch so as to drain rainwater.
SHED_ROOFA roof having a single + slope.
GABLE_ROOFA roof sloping downward in + two parts from a central ridge, so as to form a gable at each end.
HIP_ROOFA roof having sloping ends + and sides meeting at an inclined projecting angle.
HIPPED_GABLE_ROOFA roof having a hipped end + truncating a gable.
GAMBREL_ROOFA ridged roof divided on each + side into a shallower slope above a steeper one.
MANSARD_ROOFA roof having on each side a + steeper lower part and a shallower upper part.
BARREL_ROOFA roof or ceiling having a + semicylindrical form.
RAINBOW_ROOFA gable roof in the form of a + broad Gothic arch, with gently sloping convex surfaces.
BUTTERFLY_ROOFA roof having two slopes, + each descending inward from the eaves.
PAVILION_ROOFA pyramidal hip roof.
DOME_ROOFA hemispherical hip + roof.
FREEFORMFree form roof  
NOTDEFINEDNo specification given 
+

Figure 68 — Roof types

+ +
" +1400;IfcStairFlightTypeEnum;" +

Definition from IAI: This enumeration defines the different types + of stair flights an IfcStairFlightType object can fulfill:

+
    +
  • STRAIGHT: A stair flight with a straight walking line.
  • +
  • WINDER: A stair flight with a straight walking line.
  • +
  • SPIRAL: A stair flight with a circular or elliptic walking + line.
  • +
  • CURVED: A stair flight with a curved walking line.
  • +
  • FREEFORM: A stair flight with a free form walking line (and + outer boundaries).
  • +
  • USERDEFINED: User-defined stair flight .
  • +
  • NOTDEFINED: Undefined stair flight .
  • +
+
HISTORY: New Enumeration in + Release IFC2x Edition 2.
+
" +1412;IfcRampFlightTypeEnum;" +

Definition from IAI: This enumeration defines the different types + of linear elements an IfcRampFlightType object can fulfill:

+
    +
  • STRAIGHT: A ramp flight with a straight walking line.
  • +
  • SPIRAL: A ramp flight with a circular or elliptic walking + line.
  • +
  • USERDEFINED: User-defined ramp flight.
  • +
  • NOTDEFINED: Undefined ramp flight.
  • +
+
HISTORY: New Enumeration in + Release IFC2x Edition 2.
+
" +1421;IfcCurtainWallTypeEnum;" +

Definition from IAI: Enumeration defining +the valid types of curtain wall that can be predefined using the +enumeration values.

+
HISTORY  +New Enumeration in Release IFC2x Edition 3
+
NOTE  Currently there +are no specific enumerators defined, the IfcCurtainWallTypeEnum +has +been added for future extensions.
+
" +1428;IfcRailingTypeEnum;" +

Definition from IAI: Enumeration defining the valid types of + railings that can be predefined using the enumeration values.

+
HISTORY: New Enumeration in IFC + Release 2.0
+

Enumeration

+
    +
  • HANDRAIL: A type of railing designed to serve as an optional + structural support for loads applied by human occupants (at hand height). + Generally located adjacent to ramps and stairs. Generally floor or wall + mounted.
  • +
  • GUARDRAIL: A type of railing designed to guard human occupants + from falling off a stair, ramp or landing where there is a vertical drop at the + edge of such floors/landings.
  • +
  • BALUSTRADE: Similar to the definitions of a guardrail except + the location is at the edge of a floor, rather then a stair or ramp. Examples + are balustrates at roof-tops or balconies.
  • +
  • USERDEFINED: User-defined railing element, a term to identify + the user type is given by the attribute IfcRailing.ObjectType.
  • +
  • NOTDEFINED: Undefined railing element, no type information + available.
  • +
+
" +1442;IfcDoorTypeEnum;" +

Definition from IAI: This enumeration defines the +different predefined types of an IfcDoorType object can +fulfill:

+
    +
  • DOOR: A standard door usually within a wall opening, +as a door panel in a curtain wall, or as a ""free standing"" +door.
  • +
  • GATE: A gate is a point of entry to a property usually +within an opening in a fence. Or as a ""free standing"" gate.
  • +
  • TRAPDOOR: A special door that lies horizonally in a +slab opening. Often used for accessing cellar or attic.
  • +
  • USERDEFINED: User-defined linear beam element.
  • +
  • NOTDEFINED: Undefined linear beam element
  • +
+
HISTORY  New Enumeration +in IFC2x4.
+
" +1448;IfcDoorTypeOperationEnum;" + +

This enumeration defines the basic ways to describe how doors operate, as shown in Figure 66. It combines the partitioning of the door into a single or multiple door panels and the operation types of that panels.

+ +

In the most common case of swinging doors the IfcDoorTypeOperationEnum defined the hinge side (left hing or right hung) and the opening direction (opening to the left, opening to the right). Whether the door opens inwards or outwards is determined by the local coordinate system of the IfcDoor, or IfcDoorStandardCase.

+ +
NOTE There are different definitions in various countries on what a left opening or left hung or left swing door is (same for right). Therefore the IFC definition terms may derivate from the local standard and may need to be mapped appropriately.
+ +
HISTORY  New Enumeration in IFC2x4.
+ +
IFC2x4 CHANGE The new IfcDoorTypeOperationEnum replaces the use of IfcDoorStyleOperationEnum that is deprecated from IFC2x4 onwards.
+ + + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigures 
+

SINGLE_SWING_LEFT

+
Door with one panel that opens +(swings) to the left. The hinges are on the left side as viewed +in the direction of the positive y-axis.
+
Note: Direction of swing (whether in or out) +is determined at the IfcDoor or +IfcDoorStandardCase.
+
+
+""single
+

SINGLE_SWING_RIGHT

+
Door with one panel that opens +(swings) to the right. The hinges are on the right side as viewed +in the direction of the positive y-axis.
+
Note: Direction of swing (whether in or out) +is determined at the IfcDoor or +IfcDoorStandardCase.
+
+""single
+

DOUBLE_DOOR_
+SINGLE_SWING

+
Door with two panels, one opens +(swings) to the left the other opens (swings) to the right.
+
Note: Direction of swing (whether in or out) +is determined at the IfcDoor or +IfcDoorStandardCase. 
+
+""double
+

DOUBLE_SWING_LEFT

+
Door with one panel that swings in +both directions and to the left in the main trafic direction. +Also called double acting door.
+
Note: Direction of main swing (whether in or +out) is determined at the IfcDoor or +IfcDoorStandardCase. 
+
+""double
+

DOUBLE_SWING_RIGHT

+
Door with one panel that swings in +both directions and to the right in the main trafic direction. +Also called double acting door.
+
Note: Direction of main swing (whether in or +out) is determined at the IfcDoor or +IfcDoorStandardCase.
+
+""double
+

DOUBLE_DOOR_
+DOUBLE_SWING

+
Door with two panels, one swings in +both directions and to the right in the main trafic direction the +other swings also in both directions and to the left in the main +trafic direction.
+
Note: Direction of main swing (whether in or +out) is determined at the IfcDoor or +IfcDoorStandardCase.
+
+""double
+

DOUBLE_DOOR_
+SINGLE_SWING_
+OPPOSITE_LEFT

+
Door with two panels that both open +to the left, one panel swings in one direction and the other +panel swings in the opposite direction.
+
Note: Direction of main swing (whether in or +out) is determined at the IfcDoor or +IfcDoorStandardCase.
+
  
DOUBLE_DOOR_
+SINGLE_SWING_
+OPPOSITE_RIGHT
Door with two panels that both open +to the right, one panel swings in one direction and the other +panel swings in the opposite direction.
+
Note: Direction of main swing (whether in or +out) is determined at the IfcDoor or +IfcDoorStandardCase.
+
  
+

SLIDING_TO_LEFT

+
Door with one panel that is sliding +to the left.+""sliding
+

SLIDING_TO_RIGHT

+
Door with one panel that is sliding +to the right.+""sliding
+

DOUBLE_DOOR_SLIDING

+
Door with two panels, one is sliding +to the left the other is sliding to the right.+""double
+

FOLDING_TO_LEFT

+
Door with one panel that is folding +to the left.+""folding
FOLDING_TO_RIGHTDoor with one panel that is folding +to the right.+""folding
+

DOUBLE_DOOR_FOLDING

+
Door with two panels, one is folding +to the left the other is folding to the right.+""double
+

REVOLVING

+
An entrance door consisting of four +leaves set in a form of a cross and revolving around a central +vertical axis (the four panels are described by a single +IfcDoor panel property).  
+

ROLLINGUP

+
Door that opens by rolling up.
+
Note: Whether it rolls up to the inside or +outside is determined at the IfcDoor.
+
SWING_FIXED_LEFTDoor with one panel that opens +(swings) to the left and one fixed panel. The hinges of the +swinging panel are on the left side as viewed in the direction of +the positive y-axis.
+
Note: Direction of swing (whether in or out) +is determined at the IfcDoor or or +IfcDoorStandardCase.
+IFC2x4 CHANGE This is a new +enumerator compared with previous +IfcDoorStyleOperationEnum.
+
+""swinging
SWING_FIXED_RIGHTDoor with one panel that opens +(swings) to the right and one fixed panel. The hinges of the +swinging panel are on the right side as viewed in the direction +of the positive y-axis.
+
Note: Direction of swing (whether in or out) +is determined at the IfcDoor or or +IfcDoorStandardCase.
+IFC2x4 CHANGE This is a new +enumerator compared with previous +IfcDoorStyleOperationEnum.
+
+""swinging+""swinging
USERDEFINEDUser defined operation type  
NOTDEFINEDA door with a not defined operation +type is considered as a door with a lining, but no panels. It is +thereby always open.
 
+ +

Figure 66 — Door operations

+ +

NOTE

+
    +
  1. Figures are shown in the ground view.
  2. +
  3. Figures (symbolic representation) depend on the national +building code.
  4. +
  5. These figures are only shown as illustrations, the actual +representation in the ground view might differ.
  6. +
  7. Open to the outside is declared as open into the direction of +the positive y-axis, determined by the ObjectPlacement at +IfcDoor
  8. +
  9. The location of the panel relative to the wall thickness is +defined by the ObjectPlacement at IfcDoor, and the +IfcDoorLiningProperties.LiningOffset parameter.
  10. +
+
" +1477;IfcWindowTypeEnum;" +

Definition from IAI: This enumeration defines the +different predefined types of an IfcWindowType object can +fulfill:

+
    +
  • WINDOW: A standard window usually within a wall +opening, as a window panel in a curtain wall, or as a ""free +standing"" window.
  • +
  • SKYLIGHT: A window within a sloped building element, +usually a roof slab.
  • +
  • LIGHTDOME: A special window that lies horizonally in a +roof slab opening.
  • +
  • USERDEFINED: User-defined window element.
  • +
  • NOTDEFINED: Undefined window element
  • +
+
HISTORY  New Enumeration +in IFC2x4.
+
" +1483;IfcWindowTypePartitioningEnum;" + +

This enumeration defines the basic configuration of the window type in terms of the number of window panels and the subdivision of the total window as shown in Figure 70. The window configurations are given for windows with one, two or three panels (including fixed panels).

+ +

Windows which are subdivided into more than three panels have to be defined by the geometry only. The type of such windows is USERDEFINED.

+ +
HISTORY  New Enumeration in IFC2x4.
+
NOTE The new IfcWindowTypePartitioningEnum replaces the use of +IfcWindowStyleOperationEnum that is deprecated from IFC2x4 onwards.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
SinglePanelWindow with one +panel.
+DoublePanelVerticalWindow with two panels. +The configuration of the panels is vertically.
+DoublePanelHorizontalWindow with two panels. +The configuration of the panels is horizontally.
+TriplePanelVerticalWindow with three +panels. The configuration of the panels is vertically.
+TriplePanelHorizontalWindow with three +panels. The configuration of the panels is horizontally.
TriplePanelBottomWindow with three +panels. The configuration of two panels is vertically and the +third one is horizontally at the bottom.
TriplePanelTopWindow with three +panels. The configuration of two panels is vertically and the +third one is horizontally at the top.
TriplePanelLeftWindow with three +panels. The configuration of two panels is horizontally and the +third one is vertically at the left hand side.
TriplePanelRightWindow with three +panels. The configuration of two panels is horizontally and the +third one is vertically at the right hand side.
UserDefineduser defined operation +type 
NotDefined  
+

Figure 70 — Window partitioning

+ +

NOTE

+
    +
  1. The way how each panel operates is defined at the +IfcWindowPanelProperties.OperationType.
  2. +
  3. The reference from the window panel to the location of that +panel in the window style configuration is handled by the +IfcWindowPanelProperties.PanelPosition.
  4. +
  5. The figures are shown as elevations in the XZ plane of the +local placement of the window, looking into the direction of the +positive Y axis.
  6. +
  7. These figures are only shown as illustrations
  8. +
+
" +1502;IfcPlateTypeEnum;" +

Definition from IAI: This enumeration +defines the different types of planar elements an IfcPlateType +object can fulfill:

+
    +
  • CURTAIN_PANEL: A planar element within a +curtain wall, often consisting of a frame with fixed glazing.
  • +
  • SHEET: A planar, flat and thin element, +comes usually as metal sheet, and is often used as an additonal part +within an assembly.
  • +
  • USERDEFINED: User-defined linear element.
  • +
  • NOTDEFINED: Undefined linear element
  • +
+
+HISTORY  New Enumeration in Release IFC2x Edition 2.
+
IFC2x +Edition 3 +CHANGE  The additional identifiers CURTAIN_PANEL, SHEET have +been +added.
+
" +1511;IfcChimneyTypeEnum;" +

+ Definition from IAI: Enumeration defining the valid + types of chimneys that can be predefined using the + enumeration values. +

+
+ HISTORY  New Enumeration in + Release IFC2x4 +
+
+ NOTE  Currently there are no specific enumerators + defined, the IfcChimneyTypeEnum has been added + for future extensions. +
+
" +1519;IfcBuildingElementProxyTypeEnum;" +

+ Definition from IAI: This enumeration defines the + available generic types for IfcBuildingElementProxyType. +

+
+ HISTORY  New enumeration + in Release IFC2x Edition 3. +
+

+ Enumeration +

+
    +
  • USERDEFINED +
  • +
  • NOTDEFINED +
  • +
+
" +1532;IfcCoveringTypeEnum;" +

Definition from IAI: This enumeration defines the range +of different types of covering that can further specify an +IfcCovering or an IfcCoveringType.

+
HISTORY New enumeration +in IFC Release 1.0
+IFC2x4 CHANGE The following +enumerators of the IfcCoveringTypeEnum have been +deprecated INSULATION, SLEEVING and +WRAPPING.
+

Enumeration

+
    +
  • CEILING: the covering is used to +represent a ceiling
  • +
  • FLOORING: the covering is used to +represent a flooring
  • +
  • CLADDING: the covering is used to +represent a cladding
  • +
  • ROOFING: the covering is used to +represent a roof
    +
  • +
  • INSULATION: the covering is used to +insulate an element for thermal or acoustic purposes.
    +IFC2x4 NOTE The use of this +enumerator is deprecated.
  • +
  • MEMBRANE: an impervious layer that +could be used for e.g. roof covering (below tiling - that may be +known as sarking etc.) or as a damp proof course membrane
    +IFC2x4 NOTE The use of this +enumerator is deprecated.
  • +
  • SLEEVING: the covering is used to +isolate a distribution element from a space in which it is +contained.
    +IFC2x4 NOTE The use of this +enumerator is deprecated.
  • +
  • WRAPPING: the covering is used for +wrapping particularly of distribution elements using tape.
    +IFC2x4 NOTE The use of this +enumerator is deprecated.
    +
  • +
  • USERDEFINED: user defined type of +covering
  • +
  • NOTDEFINED: undefined type of +covering
  • +
+
" +1550;IfcShadingDeviceTypeEnum;" +

Definition from IAI: Enumeration defining the valid +types of shading devices that can be predefined using the +enumeration values.

+
    +
  • JALOUSIE
  • +
  • SHUTTER
  • +
  • AWNING
  • +
+
HISTORY  New Enumeration +in Release IFC2x4
+
" +1613;IfcBuildingSystemTypeEnum;" +

Definition from IAI: This enumeration identifies +different types of distribution systems.

+
HISTORY New enumeration +in IFC2x4.
+

Valid enumerations for building systems include:

+
    +
  • FENESTRATION: System of doors, windows, and other +fillings in opening in a building envelop that are designed to +permit the passage of air or light,
  • +
  • SHADING: System of shading elements (external or +internal) that permits the limitation or control of impact of +natural sun light,
  • +
  • TRANSPORT: System of all transport elements in a +building that enables the transport of people or goods.
  • +
+
" +1638;IfcInventoryTypeEnum;" +

IfcInventoryTypeEnum defines the types of inventory that can be defined.

+
HISTORY: New Enumeration in IFC Release 2.0
+

Enumeration:

+
    +
  • ASSETINVENTORY: A collection of asset instances of type IfcAsset
  • +
  • SPACEINVENTORY: A collection of space instances of type IfcSpace
  • +
  • FURNITUREINVENTORY: A collection of furniture instances of type IfcFurnishingElement
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1647;IfcOccupantTypeEnum;" +

IfcOccupantTypeEnum defines the types of occupant from which the type required can be selected.

+
HISTORY: New Enumeration in IFC Release 2.0 Modified in IFC 2x2
+

Enumeration:

+
    +
  • ASSIGNEE: Actor receiving the assignment of a property agreement from an assignor
  • +
  • ASSIGNOR: Actor assigning a property agreement to an assignor
  • +
  • LESSEE: Actor receiving the lease of a property from a lessor
  • +
  • LESSOR: Actor leasing a property to a lessee
  • +
  • LETTINGAGENT: Actor participating in a property agreement on behalf of an owner, lessor or assignor
  • +
  • OWNER: Actor that owns a property
  • +
  • TENANT: Actor renting the use of a property fro a period of time
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1661;IfcSystemFurnitureElementTypeEnum;" +

IfcSystemFurnitureTypeEnum defines the types of system furniture from which the type required can be selected.

+
HISTORY: New Enumeration in IFC 2x4
+

Enumeration:

+
    +
  • PANEL: Vertical panel used to divide work spaces.
  • +
  • WORKSURFACE: Workstation countertop.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1670;IfcFurnitureTypeEnum;" +

IfcFurnitureTypeEnum defines the types of furniture from which the type required can be selected.

+
HISTORY: New Enumeration in IFC 2x4.
+

Enumeration:

+
    +
  • CHAIR: Furniture for seating a single person.
  • +
  • TABLE: Furniture with a countertop for multiple people.
  • +
  • DESK: Furniture with a countertop and optional drawers for a single person.
  • +
  • BED: Furniture for sleeping.
  • +
  • FILECABINET: Furniture with sliding drawers for storing files.
  • +
  • SHELF: Furniture for storing books or other items.
  • +
  • SOFA: Furniture for seating multiple people.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1693;IfcDoorStyleOperationEnum;" +

This enumeration defines the basic ways to describe how doors operate as shown in Figure 167.

+
HISTORY  New Enumeration in Release IFC2x.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
+

SINGLE_SWING_LEFT

+
Door with one +panel that opens (swings) to the +left. The hinges are on the left side as viewed in the direction of the +positive y-axis.
+
Note: Direction of swing (whether +in or out) +is determined at the IfcDoor.
+
+
+
+

SINGLE_SWING_RIGHT

+
Door with one +panel that opens (swings) to the +right. The hinges are on the right side as viewed in the direction of +the positive y-axis.
+
Note: Direction of swing (whether +in or out) +is determined at the IfcDoor.
+

+
+
+

DOUBLE_DOOR_
+SINGLE_SWING

+
Door with two +panels, one opens (swings) to the +left the other opens (swings) to the right.
+
Note: Direction of swing (whether +in or out) +is determined at the IfcDoor. 
+

+
+
+

DOUBLE_SWING_LEFT

+
Door with one +panel that swings in both +directions and to the left in the main trafic direction. Also called +double acting door.
+
Note: Direction of main swing +(whether in or +out) is determined at the IfcDoor. 
+

+
+
+

DOUBLE_SWING_RIGHT

+
Door with one +panel that swings in both +directions and to the right in the main trafic direction. Also called +double acting door.
+
Note: Direction of main swing +(whether in or +out) is determined at the IfcDoor.
+

+
+
+

DOUBLE_DOOR_
+DOUBLE_SWING

+
Door with two +panels, one swings in both +directions and to the right in the main trafic direction the other +swings also in both directions and to the left in the main trafic +direction.
+
Note: Direction of main swing +(whether in or +out) is determined at the IfcDoor.
+

+
+
+

DOUBLE_DOOR_
+SINGLE_SWING_
+OPPOSITE_LEFT

+
Door with two +panels that both open to the left, +one panel swings in one direction and the other panel swings in the +opposite direction.
+
Note: Direction of main swing +(whether in or +out) is determined at the IfcDoor.
+

+
+
DOUBLE_DOOR_
+SINGLE_SWING_
+OPPOSITE_RIGHT
Door with two +panels that both open to the right, +one panel swings in one direction and the other panel swings in the +opposite direction.
+
Note: Direction of main swing +(whether in or +out) is determined at the IfcDoor.
+
+
+

SLIDING_TO_LEFT

+
Door with one +panel that is sliding to the left.
+

SLIDING_TO_RIGHT

+
Door with one +panel that is sliding to the right.
+

DOUBLE_DOOR_SLIDING

+
Door with two +panels, one is sliding to the left +the other is sliding to the right.
+

FOLDING_TO_LEFT

+
Door with one +panel that is folding to the left.
FOLDING_TO_RIGHTDoor with one +panel that is folding to the right.
+

DOUBLE_DOOR_FOLDING

+
Door with two +panels, one is folding to the left +the other is folding to the right.
+

REVOLVING

+
An entrance door +consisting of four leaves set in +a form of a cross and revolving around a central vertical axis (the +four panels are described by a single IfcDoor panel +property).
+

ROLLINGUP

+
Door that opens +by rolling up.
+
Note: Whether it rolls up to the +inside or +outside is determined at the IfcDoor.
+
+
+
USERDEFINEDUser defined +operation type 
NOTDEFINEDA door with a +not defined operation type is +considered as a door with a lining, but no panels. It is thereby always +open. 
+
+

Figure 167 — Door style operations

+ +

NOTE

+
    +
  1. Figures are shown in the ground view.
  2. +
  3. Figures (symbolic representation) depend on the national +building +code.
  4. +
  5. These figures are only shown as illustrations, the actual +representation in the ground view might differ.
  6. +
  7. Open to the outside is declared as open into the direction +of the +positive y-axis, determined by the ObjectPlacement +at IfcDoor
  8. +
  9. The location of the panel relative to the wall thickness is +defined by the ObjectPlacement at IfcDoor, +and the IfcDoorLiningProperties.LiningOffset +parameter.
  10. +
+ +
" +1712;IfcDoorStyleConstructionEnum;" +

+ Definition from IAI: This enumeration defines the + basic types of construction of doors. The construction type + relates to the main material (or material combination) used + for making the door. +

+
+ HISTORY New Enumeration in + IFC Release 2x . +
+
" +1727;IfcWindowStyleConstructionEnum;" +

+ Definition from IAI: This enumeration defines the + basic types of construction of windows. The construction + type relates to the main material (or material combination) + used for making the window. +

+
+ HISTORY New Enumeration in + IFC Release 2x . +
+
" +1736;IfcWindowStyleOperationEnum;" +

This enumeration defines the basic + configuration of the window type in terms of the number of window panels and + the subdivision of the total window. The window configurations are given for + windows with one, two or three panels (including fixed panels) as shown in Figure 171.

+

Windows which are subdivided into more than three panels have to be + defined by the geometry only. The type of such windows is USERDEFINED.

+
HISTORY New Enumeration in IFC Release 2.0.
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
SinglePanelWindow with one + panel.
DoublePanelVerticalWindow with two panels. The + configuration of the panels is vertically.
DoublePanelHorizontalWindow with two panels. The + configuration of the panels is horizontally.
TriplePanelVerticalWindow with three panels. The + configuration of the panels is vertically.
TriplePanelHorizontal Window with three panels. The + configuration of the panels is horizontally.
TriplePanelBottomWindow with three panels. The + configuration of two panels is vertically and the third one is horizontally at + the bottom.
TriplePanelTopWindow with three panels. The + configuration of two panels is vertically and the third one is horizontally at + the top.
TriplePanelLeftWindow with three panels. The + configuration of two panels is horizontally and the third one is vertically at + the left hand side.
TriplePanelRightWindow with three panels. The + configuration of two panels is horizontally and the third one is vertically at + the right hand side.
UserDefineduser defined operation + type 
NotDefined  
+

Figure 171 — Window style operations

+ +

NOTE

+
    +
  1. The way how each panel operates is defined at the + IfcWindowPanelProperties.OperationType.
  2. +
  3. The reference from the window panel to the location of that panel in + the window style configuration is handled by the + IfcWindowPanelProperties.PanelPosition.
  4. +
  5. The figures are shown as elevations in the XZ plane of the local + placement of the window, looking into the direction of the positive Y + axis.
  6. +
  7. These figures are only shown as illustrations
  8. +
+
" +1774;IfcDoorPanelOperationEnum;" +

This enumeration defines the basic ways how individual door panels operate as shown in Figure 164.

+
HISTORY New Enumeration in IFC Release 2.0.
+
IFC2x4 CHANGE Enumerator FIXEDPANELadded.
+ + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Swinging
DoubleActing
Sliding
Folding
Revolving
Rollingup
FixedPanel +
NOTE Enumerator added in IFC2x4.
+
UserDefined 
NotDefined 
+ +

Figure 164 — Door operations

+ + +

The opening direction of the door panels is given by the local +placement of the IfcDoor. The positive y-axis determines +the direction as shown in Figure 165.

+ + + +
+""panel

Figure 165 — Door panel operations

+ +
+NOTE Figures (symbolic representation) depend on the national building code. These figures are only shown as illustrations +
+ + + +
" +1784;IfcDoorPanelPositionEnum;" +

Definition: This enumeration defines the basic ways to describe the location of a door panel within a door lining.

+ +
+HISTORY New Enumeration in IFC Release 2.x +
+ +

Figure 166 shows the designation of a door panel with PanelPosition = LEFT and a door panel with PanelPosition = RIGHT within a door style with OperationType = DOUBLE_DOOR_SINGLE_SWING. The position is given as shown in the XZ plane of the local placement, looking into the direction of the positive Y axis.

+ + + + +

Figure 166 — Door panel positions

+ +
" +1795;IfcWindowPanelOperationEnum;" + +

This enumeration defines the basic ways to describe how window panels operate, as shown in Figure 168.

+ +
+HISTORY New Enumeration in IFC Release 2.0 +
+ + + +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
EnumeratorDescriptionFigure
SideHungRightHandpanel that opens to the right + when viewed from the outside 
SideHungLeftHandpanel that opens to the left + when viewed from the outside 
TiltAndTurnRightHandpanel that opens to the right + and is bottom hung 
TiltAndTurnLeftHandpanel that opens to the left + and is bottom hung 
TopHungpanel is top hung 
BottomHungpanel is bottom hung 
PivotHorizontalpanel is swinging + horizontally (hinges are in the middle) 
PivotVerticalpanel is swinging vertically + (hinges are in the middle) 
SlidingHorizontalpanel is sliding horizontally +  
SlidingVerticalpanel is sliding + vertically 
RemovableCasementpanel is removable 
FixedCasementpanel is fixed 
OtherOperationuser defined operation type 
NotDefined  
+

Figure 168 — Window panel operations

+ +

The opening direction of the window panels is given by the local placement of the IfcWindow. The positive y-axis determines the direction as shown in Figure 169.

+

NOTE

+
    +
  1. Figures are shown as viewed from the outside (in direction of the + positive y-axis).
  2. +
  3. Figures (symbolic representation) depend on the national building + code
  4. +
  5. These figures are only shown as illustrations
  6. +
+ + + +
+

Figure 169 — Window panel directions

+ +
" +1810;IfcWindowPanelPositionEnum;" +

This enumeration defines the basic configuration of the window type in terms of the location of window panels. The window configurations are given for windows with one, two or three panels (including fixed panels) as shown in Figure 170. It corresponds to the OperationType of the IfcWindowStyle definition, which references the IfcWindowPanelProperties.

+ +

Windows which are subdivided into more than three panels have to be defined by the geometry only. The type of such windows is given by an IfcWindowStyle.OperationType = USERDEFINED or NOTDEFINED (see IfcWindowStyleOperationEnum for details).

+ +
+HISTORY New Enumeration in IFC Release 2.0. +
+ + +

Figure 170 — Window panel positions

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Enumerator from IfcWindowStyleOperationEnumUse of enumerators from IfcWindowPanelPositionEnumFigure
DoublePanelVerticalfirst + IfcWindowPanelProperties with PanelPosition = LEFT
second + IfcWindowPanelProperties with PanelPosition = RIGHT
DoublePanelHorizontalfirst + IfcWindowPanelProperties with PanelPosition = TOP
second + IfcWindowPanelProperties with PanelPosition = BOTTOM
TriplePanelVerticalfirst + IfcWindowPanelProperties with PanelPosition = LEFTsecond + IfcWindowPanelProperties with PanelPosition = MIDDLE
third + IfcWindowPanelProperties with PanelPosition = RIGHT
TriplePanelHorizontal first + IfcWindowPanelProperties with PanelPosition = TOP
second + IfcWindowPanelProperties with PanelPosition = MIDDLE
third + IfcWindowPanelProperties with PanelPosition = BOTTOM
TriplePanelBottomfirst + IfcWindowPanelProperties with PanelPosition = LEFT
second + IfcWindowPanelProperties with PanelPosition = RIGHT
third + IfcWindowPanelProperties with PanelPosition = BOTTOM
TriplePanelTopfirst + IfcWindowPanelProperties with PanelPosition = TOP
second + IfcWindowPanelProperties with PanelPosition = LEFT
third + IfcWindowPanelProperties with PanelPosition = RIGHT
TriplePanelLeftfirst + IfcWindowPanelProperties with PanelPosition = LEFT
second + IfcWindowPanelProperties with PanelPosition = TOP
third + IfcWindowPanelProperties with PanelPosition = BOTTOM
TriplePanelRightfirst + IfcWindowPanelProperties with PanelPosition = TOP
second + IfcWindowPanelProperties with PanelPosition = BOTTOM
third + IfcWindowPanelProperties with PanelPosition = RIGHT
+
+ +

NOTE

+
    +
  1. The figures are shown as elevations in the XZ plane of the local + placement of the window, looking into the direction of the positive Y + axis.
  2. +
  3. These figures are only shown as illustrations.
  4. +
+
" +1840;IfcPermeableCoveringOperationEnum;" +

Definition: Enumeration defining the valid types of permeable coverings.

+ +

Enumeration:

+ + + + + + + + + + + + + + + + + + + + + +
GRILL protective screen of metal bars or wires
LOUVER set of fixed or movable strips of wood, metal, etc. arranged to let + air in while keeping light or rain out
SCREEN upright, fixed or movable, sometimes folding framework used for + protection against heat, light, access or similar
USERDEFINED user defined permeable covering type
NOTDEFINED no information available
+
+HISTORY: New Enumeration in IFC Release 2.0 +
+ +
" +1851;IfcFlowInstrumentTypeEnum;" +

The IfcFlowInstrumentTypeEnum defines the range of different types of flow instrument that can be specified.

+
+

HISTORY: New type in IFC + 2x2

+

Enumeration

+ +
    +
  • PRESSUREGAUGE: A device that reads and displays a pressure value at a point or the pressure difference between two points.
  • +
  • THERMOMETER: A device that reads and displays a temperature value at a point.
  • +
  • AMMETER: A device that reads and displays the current flow in a circuit.
  • +
  • FREQUENCYMETER: A device that reads and displays the electrical frequency of an alternating current circuit.
  • +
  • PHASEANGLEMETER: A device that reads and displays the phase angle of a phase in a polyphase electrical circuit.
  • +
  • POWERFACTORMETER: A device that reads and displays the power factor of an electrical circuit.
  • +
  • VOLTMETER_PEAK: A device that reads and displays the peak voltage in an electrical circuit.
  • +
  • VOLTMETER_RMS: A device that reads and displays the RMS (mean) voltage in an electrical circuit.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+ +
" +1866;IfcActuatorTypeEnum;" +

The IfcActuatorTypeEnum defines the range of different types of actuator that can be specified.

+
+

HISTORY: New type in IFC + R2.0

+

Enumeration

+
    +
  • ELECTRICACTUATOR: A device that electrically actuates a control element.
  • +
  • PNEUMATICACTUATOR<: A device that pneumatically actuates a control element
  • +
  • HYDRAULICACTUATOR: A device that electrically actuates a control element.
  • +
  • HANDOPERATEDACTUATOR: A device that manually actuates a control element.
  • +
  • THERMOSTATICACTUATOR: A device that thermostatically actuates a control element.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+

See property set of actuator common attributes for specification of + properties for hand operated actuators.

+
" +1878;IfcControllerTypeEnum;" +

The IfcControllerTypeEnum defines the range of different types of controller that can be specified.

+ +
+

HISTORY: New type in IFC R2.0
+ Documentation extended in IFC 2x4. PROPORTIONALINTEGRAL and PROPORTIONALINTEGRALDERIVATIVE values deleted (property set enumeration now used). MULTIPOSITION added.

+
+ +

Enumeration

+ +
    +
  • FLOATING: Output increases or decreases at a constant or accelerating rate.
  • +
  • MULTIPOSITION: Output is discrete value, can be one of three or more values.
  • +
  • PROGRAMMABLE: Output is programmable such as Discrete Digital Control (DDC).
  • +
  • PROPORTIONAL: Output is proportional to the control error and optionally time integral and derivative.
  • +
  • TWOPOSITION: Output can be either on or off
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+ +
" +1890;IfcSensorTypeEnum;" +

The IfcSensorTypeEnum defines the range of different types of sensor that can be specified.

+
+

HISTORY: New type in IFC R2.0. Added missing enumerations in IFC2x4

+
+

Enumeration

+
    +
  • CONDUCTANCESENSOR: A device that senses or detects electrical conductance.
  • +
  • CONTACTSENSOR: A device that senses or detects contact, such as for detecting if a door is closed.
  • +
  • FIRESENSOR: A device that senses or detects fire.
  • +
  • FLOWSENSOR: A device that senses or detects flow in a fluid.
  • +
  • GASSENSOR: A device that senses or detects gas concentration.
  • +
  • HEATSENSOR: A device that senses or detects heat.
  • +
  • IONCONCENTRATIONSENSOR: A device that senses or detects ion concentration, such as for water hardness.
  • +
  • LEVELSENSOR: A device that senses or detects fill level, such as for a tank.
  • +
  • HUMIDITYSENSOR: A device that senses or detects humidity.
  • +
  • LIGHTSENSOR: A device that senses or detects light.
  • +
  • MOISTURESENSOR: A device that senses or detects moisture.
  • +
  • MOVEMENTSENSOR: A device that senses or detects movement.
  • +
  • PHSENSOR: A device that senses or detects acidity.
  • +
  • PRESSURESENSOR: A device that senses or detects pressure.
  • +
  • RADIATIONSENSOR: A device that senses or detects electromagnetic radiation.
  • +
  • RADIOACTIVITYSENSOR: A device that senses or detects atomic decay.
  • +
  • SMOKESENSOR: A device that senses or detects smoke.
  • +
  • SOUNDSENSOR: A device that senses or detects sound.
  • +
  • TEMPERATURESENSOR: A device that senses or detects temperature.
  • +
  • WINDSENSOR: A device that senses or detects airflow speed and direction.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1917;IfcAlarmTypeEnum;" +

The IfcAlarmTypeEnum defines the range of different types of alarm that can be specified.

+
+

HISTORY: New type in IFC 2x2

+
+

Enumeration

+
    +
  • BELL: An audible alarm.
  • +
  • BREAKGLASSBUTTON: An alarm activation mechanism in which a protective glass has to be broken to enable a button to be pressed.
  • +
  • LIGHT: A visual alarm.
  • +
  • MANUALPULLBOX: An alarm activation mechanism in which activation is achieved by a pulling action.
  • +
  • SIREN: An audible alarm.
  • +
  • WHISTLE: An audible alarm.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1930;IfcUnitaryControlElementTypeEnum;" +

The IfcUnitaryControlElementTypeEnum defines the range of different types and/or functions of unitary control elements possible.

+
+

HISTORY: New type in IFC 2x4.

+
+

Enumeration

+
    +
  • ALARMPANEL: A control element at which alarms are annunciated.
  • +
  • CONTROLPANEL: A control element at which devices that control or monitor the operation of a site, building or part of a building are located.
  • +
  • GASDETECTORPANEL: A control element at which the detection of gas is annunciated.
  • +
  • INDICATORPANEL: A control element at which equipment operational status, condition, safety state or other required parameters are indicated.
  • +
  • MIMICPANEL: A control element at which information that is available elsewhere is repeated or 'mimicked'.
  • +
  • HUMIDISTAT: A control element that senses and regulates the humidity of a system or space so that the humidity is maintained near a desired setpoint.
  • +
  • THERMOSTAT: A control element that senses and regulates the temperature of an element, system or space so that the temperature is maintained near a desired setpoint.
  • +
  • WEATHERSTATION: A control element that senses multiple climate properties such as temperature, humidity, pressure, wind, and rain.
  • +
  • USERDEFINED: User-defined type.
  • +
  • NOTDEFINED: Undefined type.
  • +
+
" +1974;IfcStructuralCurveMemberTypeEnum;" +

Definition from IAI: This type definition shall be used to + + distinguish between different types of structural 'curve' members, such as + + cables. The IfcStructuralCurveTypeEnum type is referenced by the entity + + IfcStructuralCurveMember.

+ +
    +
  • RIGID_JOINED_MEMBER: A member with capacity to carry transverse and axial loads, i.e. a beam. Its actual joints may be rigid or pinned. Typically used in rigid frames.
  • +
  • PIN_JOINED_MEMBER: A member with capacity to carry axial loads only, i.e. a link. Typically used in trusses.
  • +
  • CABLE: A tension member which is able to carry transverse loads only under large deflection.
  • +
  • TENSION_MEMBER: A member without compressional stiffness.
  • +
  • COMPRESSION_MEMBER: A member without tensional stiffness.
  • +
  • USERDEFINED: A specially defined member.
  • +
  • NOTDEFINED: A member without further categorization.
  • +
+ +
HISTORY New type in IFC 2x2.
+IFC 2x4 change: Renamed from IfcStructuralCurveTypeEnum.
+ +
" +1988;IfcStructuralSurfaceMemberTypeEnum;" +

Definition from IAI: This type definition shall be used to + + distinguish between different types of structural surface members, such as the + + typical mechanical function of walls, slabs and shells.

+ +
    +
  • BENDING_ELEMENT: A member with capacity to carry out-of-plane loads, i.e. a plate.
  • +
  • MEMBRANE_ELEMENT: A member with capacity to carry in-plane loads, for example a shear wall.
  • +
  • SHELL: A member with capacity to carry in-plane and out-of-plane loads, i.e. a combination of bending element and membrane element.
  • +
  • USERDEFINED: A specially defined member.
  • +
  • NOTDEFINED: A member without further categorization.
  • +
+ +
HISTORY New type in IFC 2x2.
+IFC 2x4 change: Renamed from IfcStructuralSurfaceTypeEnum.
+ +
" +2015;IfcAnalysisModelTypeEnum;" +

Definition from IAI: This type definition is used to distinguish + between different types of structural analysis models. The analysis models are + differentiated by their dimensionality.

+
+

HISTORY: New type in Release IFC2x + Edition 2.

+
" +2037;IfcAnalysisTheoryTypeEnum;" +

Definition from IAI: This type definition is used to distinguish + between different types of structural analysis methods, i.e. first order + theory, second order theory (small deformations), third order theory (large + deformations) and the full nonlinear theory (geometric nonlinearity together with other nonlinearities, e.g. plasticity).

+
+

HISTORY: New type in Release IFC2x + Edition 2.

+
" +2047;IfcLoadGroupTypeEnum;" + +

Definition from IAI: This type definition is used to distinguish between different levels +of load grouping. It allows to differentiate between load groups, load cases, and load combinations. +Normally, these enumeration types shall be used in the following context:

+ +
    +
  • LOAD_GROUP groups instances of subtypes of IfcStructuralAction. It shall be used as a + container for loads grouped together for specific purposes, e.g. loads which are part of a + special load pattern.
  • +
  • LOAD_CASE groups LOAD_GROUPs and instances of subtypes of IfcStructuralAction. + It should be used as a container for loads with the same origin.
  • +
  • LOAD_COMBINATION_GROUP is an intermediate level between LOAD_CASE and LOAD_COMBINATION. + The purpose of this level is to provide a factor with which one or more LOAD_CASEs occur in a + LOAD_COMBINATION. This factor cannot be specified directly at the load case if the load case + is meant to occur in more than one combination with different factors.
    + This intermediate level is obsolete. Instead,
  • +
  • LOAD_COMBINATION is used to group load cases which act together into a load combination.
  • +
  • USERDEFINED: A grouping level which does not follow the standard hierarchy of load group types.
  • +
  • NOTDEFINED: The grouping level is not yet known.
  • +
+ +
HISTORY: New type in IFC 2x2.
+ +
IFC 2x4 change: Obsolete item LOAD_COMBINATION_GROUP removed. Load cases are directly assigned to load combinations with different factors for each load case—load combination pair by means of IfcRelAssignsToGroupByFactor.
+ +
" +2053;IfcActionTypeEnum;" +

Definition from IAI: This enumeration type is used to distinguish + between possible action types at a high level. It can be used for an automated + definition of load combinations and for dimensioning. The contained items and + their acronyms are adopted from the Eurocode standard.

+
+

HISTORY: New type in Release IFC2x + Edition 2.

+
" +2059;IfcActionSourceTypeEnum;" +

Definition from IAI:This enumeration type contains possible + action sources.

+
+

HISTORY: New type in Release IFC2x + Edition 2.

+
" +2108;IfcStructuralCurveActivityTypeEnum;" + +

Definition from IAI: Enumeration defining the distribution of load values in a curve action or reaction.

+ +
HISTORY New type in IFC 2x4
+ +

ENUMERATION

+ +
    +
  • CONST The load has a constant value over its entire extent.
  • +
  • LINEAR The load value is linearly distributed over the load's extent.
  • +
  • POLYGONAL The load consists of several consecutive linear sections.
  • +
  • EQUIDISTANT The load consists of n consecutive sections of same length and is specified by n+1 load samples. The interpolation type over the segments is not defined by this distribution type but may be qualified in IfcObject.ObjectType based on additional agreements.
  • +
  • SINUS The load value is distributed as a sinus half wave.
  • +
  • PARABOLA The load value is distributed as a half wave described by a symmetric quadratic parabola.
  • +
  • DISCRETE The load is specified as a series of discrete load points.
  • +
  • USERDEFINED The load distribution is user-defined.
  • +
  • NOTDEFINED The load distribution is undefined.
  • +
+ +
" +2118;IfcProjectedOrTrueLengthEnum;" + +

This enumeration type is needed for load definition and is only considered if the load values are given as global actions and if they define linear or planar loads (that is, one- or two-dimensionally distributed loads).

+

Figure 234 illustrates the interpretation of a load definition depending on the enumeration types IfcGlobalOrLocalEnum and IfcProjectedOrTrueLengthEnum.

+ +
HISTORY  New type in IFC2x2.
+ + + +

Figure 234 — Projected or true length

+ +
" +2129;IfcStructuralSurfaceActivityTypeEnum;" + +

Definition from IAI: Enumeration defining the distribution of load values in a surface action or reaction.

+ +
HISTORY New type in IFC 2x4
+ +

ENUMERATION

+
    +
  • CONST The load has a constant value over its entire extent.
  • +
  • BILINEAR The load value is bilinearly distributed over the load's extent.
  • +
  • DISCRETE The load is specified as a series of discrete load points.
  • +
  • ISOCONTOUR The load is specified by a series of iso-curves (level sets), i.e. curves at which the load value is constant. These curves run perpendicularly to the load gradient.
  • +
  • USERDEFINED The load distribution is user-defined.
  • +
  • NOTDEFINED The load distribution is undefined.
  • +
+ +
" +2237;IfcGeometricProjectionEnum;" + +

IfcGeometricProjectionEnum defines the various representation types that can be semantically distinguished. Often different levels of detail of the shape representation are controlled by the representation type. +

+
    +
  • GRAPH_VIEW: +Geometric display representation that shows an abstract, often 1D +element representation, e.g. representing a wall by its axis line.
  • +
  • SKETCH_VIEW: +Geometric display representation that shows an abstract, often 2D +element representation, e.g. representing a wall by its two foot print +edges, surpressing any inner layer representation.
  • +
  • MODEL_VIEW: +Geometric display representation that shows a full 3D element +representation, e.g. representing a wall by its volumetric body.
  • +
  • PLAN_VIEW: +Geometric display representation that shows a full 2D element +representation, the level of detail often depends on the target scale, +e.g. representing a wall by its two foot print edges and the edges of +all inner layers. The projection is shown in ground view as seen from +above.
  • +
  • REFLECTED_PLAN_VIEW: +Geometric display representation that shows a full 2D element +representation, the level of detail often depends on the target scale, +e.g. representing a wall by its two foot print edges and the edges of +all inner layers. The projection is shown in ground view as seen from +below.
  • +
  • SECTION_VIEW: +Geometric display representation that shows a full 2D element +representation, the level of detail often depends on the target scale, +e.g. representing a wall by its two inner/outer edges and the edges of +all inner layers, if the element is cut by the section line.
  • +
  • ELEVATION_VIEW: +Geometric display representation that shows a full 2D element +representation, the level of detail often depends on the target scale, +e.g. representing a wall by its bounding edges if the element is within +an elevation view.
  • +
  • USERDEFINED: +A user defined specification is given by the value of the UserDefinedTargetView +attribute.
  • +
  • NOTDEFINED: +No specification given.
  • +
+
+HISTORY: New Type in Release IFC2x2. +
+ +
" +2252;IfcGlobalOrLocalEnum;" + +

This enumeration type defines if the local object coordinate system or the global world coordinate system for the project is used to describe the measure values of entities which have a reference to this type.

+ +
+NOTE  The world coordinate system is given by the IfcGeometricRepresentationContext.WorldCoordinateSystem +and is unique within the project. The local (or object) coordinate system is given by IfcProduct.ObjectPlacement and is used by all IfcRepresentation's within the IfcProduct.Representation.

+
+ +
+HISTORY: New type in IFC2x2. +
+ +
" +2487;IfcTaskTypeEnum;" +

The IfcTaskTypeEnum defines the range of different types of task that can be specified.

+
+HISTORY  New type in IFC2x4 +
+

Enumeration:

+ +
  • ATTENDANCE: Attendance or waiting on other things happening
  • +
  • CONSTRUCTION: Constructing or building something
  • +
  • DEMOLITION: Demolishing or breaking down something
  • +
  • DISMANTLE: Taking something apart carefully so that it can be recycled or reused
  • +
  • DISPOSAL: Disposing or getting rid of something
  • +
  • INSTALLATION: Installing something (equivalent to construction but more commonly used for engineering tasks)
  • +
  • LOGISTIC: Transporation or delivery of something
  • +
  • MAINTENANCE: Keeping something in good working order
  • +
  • MOVE: Moving things from one place to another
  • +
  • OPERATION: A procedure undertaken to start up the operation an artifact
  • +
  • REMOVAL: Removal of an item from use and taking it from its place of use
  • +
  • RENOVATION: Bringing something to an 'as-new' state
  • +
    + +
    " +2506;IfcProcedureTypeEnum;" +

    The IfcProcedureTypeEnum defines the range of different types of procedure that can be specified.

    +
    +HISTORY: New type in IFC2x2 +
    +

    Enumeration:

    + +
  • ADVICE_CAUTION: A caution that should be taken note of as a procedure or when carrying out a procedure
  • +
  • ADVICE_NOTE: Additional information or advice that should be taken note of as a procedure or when carrying out a procedure
  • +
  • ADVICE_WARNING: A warning of potential danger that should be taken note of as a procedure or when carrying out a procedure
  • +
  • CALIBRATION: A procedure undertaken to calibrate an artifact
  • +
  • SHUTDOWN: A procedure undertaken to shutdown the operation an artifact
  • +
  • STARTUP: A procedure undertaken to start up the operation an artifact
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2523;IfcEventTypeEnum;" +

    The IfcEventTypeEnum defines the range of different types of event that can be specified.

    +
    +HISTORY  New type in IFC2x4 +
    +

    Enumeration:

    + +
  • STARTEVENT: An initiating event of a process
  • +
  • ENDEVENT: A terminating event of a process
  • +
  • INTERMEDIATEEVENT: An event that occurs at an intermediate stage of a process
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2529;IfcEventTriggerTypeEnum;" +

    The IfcEventTriggerTypeEnum defines the range of different types of event trigger that can be specified.

    +
    +HISTORY: New type in IFC2x4 +
    +

    + Enumeration: The definition of event trigger types has been adopted from the Business Process Modeling Notation (BPMN), which is also used in the Information Delivery Manual (IDM) for defining business processes. More detailed information about the use of event trigger types can be found in these specifications. +

    + +
  • EVENTRULE: An event trigger that is a rule or constraint
  • +
  • EVENTMESSAGE: An event trigger that is a message or set of information
  • +
  • EVENTTIME: An event trigger that is at, or occurs after, a particular point in or period of time
  • +
  • EVENTCOMPLEX: An event trigger that is a complex combination of things
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2549;IfcWorkPlanTypeEnum;" +

    An IfcWorkPlanTypeEnum is an enumeration data type that specifies the types of work plan from which the relevant control can be selected.

    +
    +HISTORY  Introduced in IFC2x4. Derived from IfcWorkControlTypeEnum that was introduced in IFC Release 2.0. +
    +

    + Enumeration: +

    + +
  • ACTUAL: A control in which actual items undertaken are indicated.
  • +
  • BASELINE: A control that is a baseline from which changes that are made later can be recognized.
  • +
  • PLANNED: A control showing planned items.
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2558;IfcWorkScheduleTypeEnum;" +

    An IfcWorkScheduleTypeEnum is an enumeration data type that specifies the types of work schedule from which the relevant control can be selected.

    +
    +HISTORY  Introduced in IFC2x4. Derived from IfcWorkControlTypeEnum that was introduced in IFC Release 2.0. +
    +

    Enumeration:

    + +
  • ACTUAL: A control in which actual items undertaken are indicated
  • +
  • BASELINE: A control that is a baseline from which changes that are made later can be recognized
  • +
  • PLANNED: A control showing planned items
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2569;IfcWorkCalendarTypeEnum;" +

    An IfcWorkCalendarTypeEnum is an enumeration data type that specifies the types of work calendar from which the relevant control can be selected. If given it should help to identify base calendars.

    +
    +HISTORY: Introduced in IFC2x4. +
    +

    Enumeration:

    + +
  • FIRSTSHIFT: Belongs to the first shift
  • +
  • SECONDSHIFT: Belongs to the second shift
  • +
  • THIRDSHIFT: Belongs to the third shift
  • +
  • USERDEFINED
  • +
  • NOTDEFINED
  • +
    + +
    " +2583;IfcSequenceEnum;" +

    + IfcSequenceEnum is an + enumeration that defines the different ways in which a + time lag is applied to a sequence between two processes. +

    +
    + HISTORY  New entity in IFC 1.0 +
    +
    " +2609;IfcCostScheduleTypeEnum;" +

    An IfcCostScheduleTypeEnum is a list of the available types of cost schedule from which that required may be selected.

    +
    HISTORY: New type in IFC 2x2
    +

    Enumeration

    +
      +
    • BUDGET: An allocation of money for a particular purpose.
    • +
    • COSTPLAN: An assessment of the amount of money needing to be expended for a defined purpose based on incomplete information about the goods and services required for a construction or installation.
    • +
    • ESTIMATE: An assessment of the amount of money needing to be expended for a defined purpose based on actual information about the goods and services required for a construction or installation.
    • +
    • TENDER: An offer to provide goods and services.
    • +
    • PRICEDBILLOFQUANTITIES: A complete listing of all work items forming construction or installation works in which costs have been allocated to work items.
    • +
    • UNPRICEDBILLOFQUANTITIES: A complete listing of all work items forming construction or installation works in which costs have not yet been allocated to work items.
    • +
    • SCHEDULEOFRATES: A listing of each type of goods forming construction or installation works with the cost of purchase, construction/installation, overheads and profit assigned so that additional items of that type can be costed.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2623;IfcProjectOrderTypeEnum;" +

    An IfcProjectOrderTypeEnum is a list of the types of project order that may be identified.

    +
    HISTORY: New type in IFC 2x2
    +

    Enumeration

    +
      +
    • CHANGEORDER: An instruction to make a change to a product or work being undertaken and a description of the work that is to be performed.
    • +
    • MAINTENANCEWORKORDER: An instruction to carry out maintenance work and a description of the work that is to be performed.
    • +
    • MOVEORDER: An instruction to move persons and artefacts and a description of the move locations, objects to be moved, etc.
    • +
    • PURCHASEORDER: An instruction to purchase goods and/or services and a description of the goods and/or services to be purchased that is to be performed.
    • +
    • WORKORDER: A general instruction to carry out work and a description of the work to be done. Note the difference between a work order generally and a maintenance work order.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2635;IfcCostItemTypeEnum;" +

    An IfcCostItemTypeEnum is a list of the available types of cost items.

    +
    HISTORY: New type in IFC2x4
    +

    Enumeration

    +
      +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2642;IfcPermitTypeEnum;" +

    IfcPermitTypeEnum defines the types of permits that can be granted.

    +
    HISTORY: New Enumeration in IFC2x4.
    +

    Enumeration:

    +
      +
    • ACCESS: Enables access to an identified area.
    • +
    • BUILDING: Enables work to proceed by getting regulatory permissions.
    • +
    • WORK: Enables work to be carried out in an identified area.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2652;IfcActionRequestTypeEnum;" +

    IfcActionRequestTypeEnum defines the types of sources through which a request can be made.

    +
    HISTORY: New Enumeration in IFC2x4.
    +

    Enumeration:

    +
      +
    • EMAIL: Request was made through email.
    • +
    • FAX: Request was made through facsimile.
    • +
    • PHONE: Request was made verbally over a telephone.
    • +
    • POST: Request was made through postal mail.
    • +
    • VERBAL: Request was made verbally in person.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2678;IfcConstructionEquipmentResourceTypeEnum;" + +

    This enumeration is used to identify the primary purpose of a construction equipment resource. It is limited to the most common equipment used in construction. The IfcConstructionEquipmentResourceTypeEnum contains the following:

    +
      +
    • DEMOLISHING: Removal or destruction of building elements.
    • +
    • EARTHMOVING: Excavating, filling, or contouring earth.
    • +
    • ERECTING: Lifting, positioning, and placing elements.
    • +
    • HEATING: Temporary heat to support construction.
    • +
    • LIGHTING: Temporary lighting to support construction.
    • +
    • PAVING: Asphalt or concrete roads or walkways.
    • +
    • PUMPING: Installing materials through pumps.
    • +
    • TRANSPORTING: Transporting products or materials.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4 +
    + +
    " +2692;IfcLaborResourceTypeEnum;" +

    This enumeration is used to identify the primary purpose of a labor resource, and is limited to high-level categories based upon common skillsets. The IfcLaborResourceTypeEnum contains the following:

    +
      +
    • ADMINISTRATION: Coordination of work.
    • +
    • CARPENTRY: Rough carpentry including framing.
    • +
    • CLEANING: Removal of dust and debris.
    • +
    • DRYWALL: Gypsum wallboard placement and taping.
    • +
    • ELECTRIC: Electrical fixtures, equipment, and cables.
    • +
    • FINISHING: Finish carpentry including custom cabinetry.
    • +
    • FLOORING: Carpet, tile, terazzo, wood, or other flooring.
    • +
    • HVAC: Heating and ventilation fixtures, equipment, and ducts.
    • +
    • GENERAL: General labor not requiring specific skill.
    • +
    • LANDSCAPING: Grass, plants, trees, or irrigation.
    • +
    • MASONRY: Laying bricks or blocks with mortar.
    • +
    • PAINTING: Applying decorative coatings or coverings.
    • +
    • PAVING: Asphalt or concrete roads and walkways.
    • +
    • PLUMBING: Plumbing fixtures, equipment, and pipes.
    • +
    • ROOFING: Membranes, shingles, tile, or other roofing.
    • +
    • SITEGRADING: Excavating, filling, or contouring earth.
    • +
    • STEELWORK: Erecting and attaching steel elements.
    • +
    • SURVEYING: Determining positions, distances, and angles.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4 +
    + +
    " +2717;IfcCrewResourceTypeEnum;" +

    This enumeration is used to identify the primary purpose of a crew resource. The IfcCrewResourceTypeEnum contains the following:

    +
      +
    • OFFICE: A composition of resources performing administration work in an office.
    • +
    • SITE: A composition of resources performing production work on a construction site.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4 +
    + +
    " +2725;IfcSubContractResourceTypeEnum;" +

    This enumeration is used to identify the primary purpose of a subcontract resource. The IfcSubContractResourceTypeEnum contains the following:

    +
      +
    • PURCHASE: Furnishing or supplying products.
    • +
    • WORK: Performing work onsite.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4 +
    + +
    " +2733;IfcConstructionProductResourceTypeEnum;" +

    This enumeration is used to identify the primary purpose of a construction product resource. It describes use of products created for construction, and excludes products of the finished building model. The IfcConstructionProductsResourceTypeEnum contains the following:

    +
      +
    • ASSEMBLY: Construction of assemblies for use as input to the building model or other assemblies.
    • +
    • FORMWORK: Construction or placement of forms for placing materials such as concrete.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4
    +
    + +
    " +2741;IfcConstructionMaterialResourceTypeEnum;" +

    This enumeration is used to identify the primary purpose of a construction material resource. It is limited to the most common raw materials used in construction and excludes materials commonly sold as finished products. The IfcConstructionMaterialResourceTypeEnum contains the following:

    +
      +
    • AGGREGATES: Construction aggregate including sand, gravel, and crushed stone.
    • +
    • CONCRETE: Cast-in-place concrete.
    • +
    • DRYWALL: Wall board, including gypsum board.
    • +
    • FUEL: Fuel for running equipment.
    • +
    • GYPSUM: Any gypsum material.
    • +
    • MASONRY: Masonry including brick, stone, concrete block, glass block, and tile.
    • +
    • METAL: Any metallic material.
    • +
    • PLASTIC: Any plastic material.
    • +
    • WOOD: Any wood material.
    • +
    • USERDEFINED: User-defined resource.
    • +
    • NOTDEFINED: Undefined resource.
    • +
    + +
    +HISTORY: New enumeration in IFC2x4 +
    + +
    " +2753;IfcResourceConsumptionEnum;" + +

    The IfcResourceConsumptionEnum indicates how a construction resource is consumed during its use. The IfcResourceConsumptionEnum contains the following:

    +
      +
    • CONSUMED: Resource is production-based and is immediately consumed at the start of its usage.
    • +
    • PARTIALLYCONSUMED: Resource is production-based and is consumed over its usage.
    • +
    • NOTCONSUMED: Resource is production-based and is not consumed during its usage.
    • +
    • OCCUPIED: Resource is duration-based and is immediately consumed at the start of its usage.
    • +
    • PARTIALLYOCCUPIED: Resource is duration-based and is consumed over its usage.
    • +
    • NOTOCCUPIED: Resource is duration-based and is not consumed during its usage.
    • +
    • USERDEFINED: User-defined consumption; custom property sets must indicate usage.
    • +
    • NOTDEFINED: Undefined consumption.
    • +
    +

    + +
    +HISTORY: New Enumeration in IFC Release 2.0. +
    + +
    " +2799;IfcOutletTypeEnum;" +

    The IfcOutletTypeEnum defines the range of different types of outlet that can be specified.

    +
    +

    HISTORY: New type in IFC 2x. Telephone and Data outlets added in IFC 2x4 +

    +

    Enumeration

    +
      +
    • AUDIOVISUALOUTLET: An outlet used for an audio or visual device.
    • +
    • COMMUNICATIONSOUTLET: An outlet used for connecting communications equipment.
    • +
    • POWEROUTLET: An outlet used for connecting electrical devices requiring power.
    • +
    • DATAOUTLET: An outlet used for connecting data communications equipment.
    • +
    • TELEPHONEOUTLET: An outlet used for connecting telephone communications equipment.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2810;IfcElectricApplianceTypeEnum;" +

    The IfcElectricApplianceTypeEnum defines the range of different types of electrical appliance that can be specified.

    +
    +

    HISTORY: New type in IFC R2.0. + Renamed from IfcElectricalApplianceTypeEnum if IFC 2x2.
    IFC 2x2 Addendum 1: + Missing enumeration values added (ELECTRICHEATER, TUMBLEDRYER and + WATERHEATER)
    + IFC 2x4: ELECTRICHEATER changed to FREESTANDINGELECTRICHEATER and noted as being for occasional use. RADIANTHEATER removed as part of general 'heater consolidation'. WATERHEATER, DIRECTWATERHEATER and INDIRECTWATERHEATER rationalized to FREESTANDINGWATERHEATER. WATERCOOLER changed to FREESTANDINGWATERCOOLER. +
    COMPUTER, FACSIMILE (FAX), PRINTER, SCANNER, TELEPHONE, TV (TELEVISION) moved to IfcAudioVisualApplianceTypeEnum and IfcCommunicationsApplianceTypeEnum. KITCHENMACHINE added.

    + +
    +

    Enumeration

    +
      +
    • DISHWASHER: An appliance that has the primary function of washing dishes.
    • +
    • ELECTRICCOOKER: An electrical appliance that has the primary function of cooking food (including oven, hob, grill).
    • +
    • FREESTANDINGELECTRICHEATER: An electrical appliance that is used occasionally to provide heat. A freestanding electric heater is a 'plugged' appliance whose load may be removed from an electric circuit.
    • +
    • FREESTANDINGFAN: An electrical appliance that is used occasionally to provide ventilation. A freestanding fan is a 'plugged' appliance whose load may be removed from an electric circuit.
    • +
    • FREESTANDINGWATERHEATER: A small, local electrical appliance for heating water. A freestanding water heater is a 'plugged' appliance whose load may be removed from an electric circuit.
    • +
    • FREESTANDINGWATERCOOLER: A small, local electrical appliance for cooling water. A freestanding water cooler is a 'plugged' appliance whose load may be removed from an electric circuit.
    • +
    • FREEZER: An electrical appliance that has the primary function of storing food at temperatures below the freezing point of water.
    • +
    • FRIDGE_FREEZER: An electrical appliance that combines the functions of a freezer and a refrigerator through the provision of separate compartments.
    • +
    • KITCHENMACHINE: A specialized appliance used in commercial kitchens such as a mixer.
    • +
    • HANDDRYER: An electrical appliance that has the primary function of drying hands.
    • +
    • MICROWAVE: An electrical appliance that has the primary function of cooking food using microwaves.
    • +
    • PHOTOCOPIER: A machine that has the primary function of reproduction of printed matter.
    • +
    • REFRIGERATOR: An electrical appliance that has the primary function of storing food at low temperature but above the freezing point of water.
    • +
    • TUMBLEDRYER: An electrical appliance that has the primary function of drying clothes.
    • +
    • VENDINGMACHINE: An appliance that stores and vends goods including food, drink and goods of various types.
    • +
    • WASHINGMACHINE: An appliance that has the primary function of washing clothes.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2832;IfcLightFixtureTypeEnum;" +

    The IfcLightFixtureTypeEnum defines the range of different types of light fixture available.

    + +
    +

    HISTORY: New type in IFC 2x Edition 2
    IFC 2x4: SECURITYLIGHTING added

    +
    + +

    Enumeration

    + +
      +
    • POINTSOURCE: A light fixture that is considered to have negligible area and that emit light with approximately equal intensity in all directions. A light fixture containing a tungsten, halogen or similar bulb is an example of a point source.
    • +
    • DIRECTIONSOURCE: A light fixture that is considered to have a length or surface area from which it emits light in a direction. A light fixture containing one or more fluorescent lamps is an example of a direction source.
    • +
    • SECURITYLIGHTING: A light fixture having specific purpose of directing occupants in an emergency, such as an illuminated exit sign or emergency flood light.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2841;IfcLampTypeEnum;" +

    The IfcLampTypeEnum defines the range of different types of lamp available.

    +
    +

    HISTORY: New type in IFC 2x2 Addendum + 1

    +

    Enumeration

    +
      +
    • COMPACTFLUORESCENT: A fluorescent lamp having a compact form factor produced by shaping the tube.
    • +
    • FLUORESCENT: A typically tubular discharge lamp in which most of the light is emitted by one or several layers of phosphors excited by ultraviolet radiation from the discharge.
    • +
    • HALOGEN: an incandescent lamp in which a tungsten filament is sealed into a compact transport envelope filled with an inert gas and a small amount of halogen such as iodine or bromine.
    • +
    • HIGHPRESSUREMERCURY: A discharge lamp in which most of the light is emitted by exciting mercury at high pressure.
    • +
    • HIGHPRESSURESODIUM: A discharge lamp in which most of the light is emitted by exciting sodium at high pressure.
    • +
    • LED: a solid state lamp that uses light-emitting diodes as the source of light.
    • +
    • METALHALIDE: A discharge lamp in which most of the light is emitted by exciting a metal halide.
    • +
    • OLED: a solid state lamp that uses light-emitting diodes as the source of light whose emissive electroluminescent layer is composed of a film of organic compounds.
    • +
    • TUNGSTENFILAMENT: A lamp that emits light by passing an electrical current through a tungsten wire filament in a near vacuum.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2856;IfcAudioVisualApplianceTypeEnum;" + +

    Defines the range of different types of audio-video devices that can be specified.

    +
    HISTORY: New enumeration in IFC2x4
    + +
      +
    • AMPLIFIER: A device that receives an audio signal and amplifies it to play through speakers.
    • +
    • CAMERA: A device that records images, either as a still photograph or as moving images known as videos or movies. Note that a camera may operate with light from the visible spectrum or from other parts of the electromagnetic spectrum such as infrared or ultraviolet.
    • +
    • DISPLAY: An electronic device that represents information in visual form such as a flat-panel display or television.
    • +
    • MICROPHONE: An acoustic-to-electric transducer or sensor that converts sound into an electrical signal. Microphones types in use include electromagnetic induction (dynamic microphones), capacitance change (condenser microphones) or piezoelectric generation to produce the signal from mechanical vibration.
    • +
    • PLAYER: A device that plays audio and/or video content directly or to another device, having fixed or removable storage media.
    • +
    • PROJECTOR: An apparatus for projecting a picture on a screen. Whether the device is an overhead, slide projector, or a film projector, it is usually referred to as simply a projector.
    • +
    • RECEIVER: A device that receives audio and/or video signals, switches sources, and amplifies signals to play through speakers.
    • +
    • SPEAKER: A loudspeaker, speaker, or speaker system is an electroacoustical transducer that converts an electrical signal to sound.
    • +
    • SWITCHER: A device that receives audio and/or video signals, switches sources, and transmits signals to downstream devices.
    • +
    • TELEPHONE: A telecommunications device that is used to transmit and receive sound, and optionally video.
    • +
    • TUNER: An electronic receiver that detects, demodulates, and amplifies transmitted signals.
    • +
    + +
    " +2873;IfcCommunicationsApplianceTypeEnum;" + +

    Defines the range of different types of communications appliance that can be specified.

    + +
    HISTORY: New enumeration in IFC2x4
    + +
      +
    • ANTENNA: A transducer designed to transmit or receive electromagnetic waves.
    • +
    • COMPUTER: A desktop, laptop, PDA or other type of computer that can be moved from one place to another and connected to an electrical supply via a plugged outlet.
    • +
    • FAX: A machine that has the primary function of transmitting a facsimile copy of printed matter using a telephone line.
    • +
    • GATEWAY: A gateway connects multiple network segments with different protocols at all layers (layers 1-7) of the OSI model
    • +
    • MODEM: A modem (from modulator-demodulator) is a device that modulates an analog carrier signal to encode digital information, and also demodulates such a carrier signal to decode the transmitted information
    • +
    • NETWORKAPPLIANCE: A network appliance performs a dedicated function such as firewall protection, content filtering, load balancing, or equipment management.
    • +
    • NETWORKBRIDGE: A network bridge connects multiple network segments at the data link layer (layer 2) of the OSI model, and the term layer 2 switch is very often used interchangeably with bridge
    • +
    • NETWORKHUB: A network hub connects multiple network segments at the physical layer (layer 1) of the OSI model.
    • +
    • PRINTER: A machine that has the primary function of printing text and/or graphics onto paper or other media.
    • +
    • REPEATER: A repeater is an electronic device that receives a signal and retransmits it at a higher level and/or higher power, or onto the other side of an obstruction, so that the signal can cover longer distances without degradation.
    • +
    • ROUTER: A router is a networking device whose software and hardware are usually tailored to the tasks of routing and forwarding information. For example, on the Internet, information is directed to various paths by routers.
    • +
    • SCANNER: A machine that has the primary function of scanning the content of printed matter and converting it to digital format that can be stored in a computer.
    • +
    + +
    " +2891;IfcSwitchingDeviceTypeEnum;" +

    The IfcSwitchingDeviceTypeEnum defines the range of different types of switch that can be specified.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • CONTACTOR: An electrical device used to control the flow of power in a circuit on or off.
    • +
    • DIMMERSWITCH: A dimmer switch has variable positions, and may adjust electrical power or other setting (according to the switched port type).
    • +
    • EMERGENCYSTOP: An emergency stop device acts to remove as quickly as possible any danger that may have arisen unexpectedly.
    • +
    • KEYPAD: A set of buttons or switches, each potentially applicable to a different device.
    • +
    • MOMENTARYSWITCH: A momentary switch has no position, and may trigger some action to occur.
    • +
    • SELECTORSWITCH: A selector switch has multiple positions, and may switch connectivity or other setting.
    • +
    • STARTER: A starter is a switch which in the closed position controls the application of power to an electrical device.
    • +
    • SWITCHDISCONNECTOR: A switch disconnector is a switch which in the open position satisfies the isolating requirements specified for a disconnector.
    • +
    • SELECTORSWITCH: A selector switch has multiple positions, and may change the source or level of power or other setting (according to the switched port type).
    • +
    • TOGGLESWITCH: A toggle switch has two positions, and may enable or isolate electrical power or other setting (according to the switched port type).
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2906;IfcElectricTimeControlTypeEnum;" +

    The IfcElectricTimeControlTypeEnum defines the range of types of electrical time control available.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • TIMECLOCK: A control that causes action to occur at set times.
    • +
    • TIMEDELAY: A control that causes action to occur following a set duration.
    • +
    • RELAY: Electromagnetically operated contactor for making or breaking a control circuit.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2915;IfcProtectiveDeviceTypeEnum;" +

    The IfcProtectiveDeviceTypeEnum specifically defines the range of different breaker unit types that can be used in conjunction with protective device. Types may also be used as a reference to a complete protective device in circumstances where tripping units are not separately identified (typically expected to be the case during earlier stages of design).

    + +

    HISTORY: New type in IFC 2x2. Modified definition and usage in IFC 2x4

    + +

    Enumeration

    + +
      +
    • FUSEDISCONNECTOR: A device that will electrically open the circuit after a period of prolonged, abnormal current flow.
    • +
    • CIRCUITBREAKER: A mechanical switching device capable of making, carrying, and breaking currents under normal circuit conditions and also making, carrying for a specified time and breaking, current under specified abnormal circuit conditions such as those of short circuit.
    • +
    • EARTHINGSWITCH: A safety device used to open or close a circuit when there is no current. Used to isolate a part of a circuit, a machine, a part of an overhead line or an underground line so that maintenance can be safely conducted.
    • +
    • EARTHLEAKAGECIRCUITBREAKER: A device that opens, closes, or isolates a circuit and has short circuit protection but no overload protection. It attempts to break the circuit when there is a leakage of current from phase to earth, by measuring voltage on the earth conductor.
    • +
    • RESIDUALCURRENTCIRCUITBREAKER: A device that opens, closes, or isolates a circuit and has short circuit and overload protection. It attempts to break the circuit when there is a difference in current between any two phases. May also be referred to as 'Ground Fault Interupter (GFI)' or 'Ground Fault Circuit Interuptor (GFCI)'
    • +
    • RESIDUALCURRENTSWITCH: A device that opens, closes or isolates a circuit and has no short circuit or overload protection. May also be identified as a 'ground fault switch'.
    • +
    • VARISTOR: A high voltage surge protection device.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2928;IfcElectricDistributionBoardTypeEnum;" +

    The IfcElectricDistributionBoardTypeEnum defines the range of different types and/or functions of electric distribution board possible.

    +

    HISTORY: New type in IFC 2x4. Replaces IfcElectricDistributionPointTypeEnum

    +

    Enumeration

    +
      +
    • CONSUMERUNIT: A distribution point on the incoming electrical supply, typically in domestic premises, at which protective devices are located.
    • +
    • DISTRIBUTIONBOARD: A distribution point at which connections are made for distribution of electrical circuits usually through protective devices.
    • +
    • MOTORCONTROLCENTRE: A distribution point at which starting and control devices for major plant items are located.
    • +
    • SWITCHBOARD: A distribution point at which switching devices are located.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2938;IfcCableCarrierFittingTypeEnum;" +

    The IfcCableCarrierFittingTypeEnum defines the range of different types of cable carrier fitting that can be specified.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • BEND: A fitting that changes the route of the cable carrier.
    • +
    • CROSS: A fitting at which two branches are taken from the main route of the cable carrier simultaneously.
    • +
    • REDUCER: A fitting that changes the physical size of the main route of the cable carrier.
    • +
    • TEE: A fitting at which a branch is taken from the main route of the cable carrier.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2948;IfcJunctionBoxTypeEnum;" +

    The IfcJunctionBoxTypeEnum defines the range of types of junction boxes available.

    +

    HISTORY: New type in IFC 2x2. Values added in IFC 2x4.

    +
      +
    • POWER: Contains cables, outlets, and/or switches for electrical power.
    • +
    • DATA: Contains cables, outlets, and/or switches for communications use.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2956;IfcCableFittingTypeEnum;" +

    The IfcCableFittingTypeEnum defines the range of different types of cable fitting that can be specified.

    +

    HISTORY: New type in IFC 2x4

    +

    Enumeration

    +
      +
    • CONNECTOR: A fitting that joins two cable segments of the same connector type (though potentially different gender).
    • +
    • ENTRY: A fitting that begins a cable segment at a non-electrical element such as a grounding clamp attached to a pipe.
    • +
    • EXIT: A fitting that ends a cable segment at a non-electrical element such as a grounding clamp attached to a pipe or to the ground.
    • +
    • JUNCTION: A fitting that joins three or more segments of arbitrary connector types for signal splitting or multiplexing.
    • +
    • TRANSITION: A fitting that joins two cable segments of different connector types.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2967;IfcElectricFlowStorageDeviceTypeEnum;" +

    The IfcElectricFlowStorageDeviceTypeEnum defines the range of different types of electrical flow storage device available.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • BATTERY: A device for storing energy in chemical form so that it can be released as electrical energy.
    • +
    • CAPACITORBANK: A device that stores electrical energy when an external power supply is present using the electrical property of capacitance
    • +
    • HARMONICFILTER: A device that constantly injects currents that precisely correspond to the harmonic components drawn by the load.
    • +
    • UPS: A device that provides a time limited alternative source of power supply in the event of failure of the main supply.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2978;IfcCableSegmentTypeEnum;" +

    The IfcCableSegmentTypeEnum defines the range of different types of cable segment that can be specified.

    +
    +

    HISTORY: New type in IFC + 2x2. Core and busbar segment added in IFC 2x4.

    +

    Enumeration

    +
      +
    • BUSBARSEGMENT: Electrical conductor that makes a common connection between several electrical circuits. Properties of a busbar are the same as those of a cable segment and are captured by the cable segment property set.
    • +
    • CABLESEGMENT: Cable with a specific purpose to lead electric current within a circuit or any other electric construction. Includes all types of electric cables, mainly several core segments or conductor segments wrapped together.
    • +
    • CONDUCTORSEGMENT: A single linear element within a cable or an exposed wire (such as for grounding) with the specific purpose to lead electric current, data, or a telecommunications signal.
    • +
    • CORESEGMENT: A self contained element of a cable that comprises one or more conductors and sheathing.The core of one lead is normally single wired or multiwired which are intertwined.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2988;IfcCableCarrierSegmentTypeEnum;" +

    The IfcCableCarrierSegmentTypeEnum defines the range of different types of cable carrier segment that can be specified.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • CABLELADDERSEGMENT: An open carrier segment on which cables are carried on a ladder structure.
    • +
    • CABLETRAYSEGMENT: A (typically) open carrier segment onto which cables are laid.
    • +
    • CABLETRUNKINGSEGMENT: An enclosed carrier segment with one or more compartments into which cables are placed.
    • +
    • CONDUITSEGMENT: An enclosed tubular carrier segment through which cables are pulled.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +2998;IfcProtectiveDeviceTrippingUnitTypeEnum;" +

    Defines the range of different tripping unit types that can be used in conjunction with a protective device.

    +
    HISTORY: New enumeration in IFC2x4
    + +
      +
    • ELECTRONIC: A tripping unit activated by electronic action.
    • +
    • ELECTROMAGNETIC: A tripping unit activated by electromagnetic action.
    • +
    • RESIDUALCURRENT: A tripping unit activated by residual current detection.
    • +
    • THERMAL: A tripping unit activated by thermal action.
    • +
    + +
    " +3073;IfcTransformerTypeEnum;" +

    The IfcTransformerTypeEnum defines the range of different types of transformer that can be specified.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • CURRENT: A transformer that changes the current between circuits.
    • +
    • FREQUENCY: A transformer that changes the frequency between circuits.
    • +
    • INVERTER: A transformer that converts from direct current (DC) to alternating current (AC).
    • +
    • RECTIFIER: A transformer that converts from alternating current (AC) to direct current (DC).
    • +
    • VOLTAGE: A transformer that changes the voltage between circuits.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3085;IfcElectricGeneratorTypeEnum;" +

    The IfcElectricGeneratorTypeEnum defines the range of types of electric generators available.

    +

    HISTORY: New type in IFC 2x2. Values added in IFC 2x4.

    + +

    Enumeration

    +
      +
    • CHP: Combined heat and power supply, used not only as a source of electric energy but also as a heating source for the building. It may therefore be not only part of an electrical system but also of a heating system.
    • +
    • ENGINEGENERATOR: Electrical generator with a fuel-driven engine, for example a diesel-driven emergency power supply.
    • +
    • STANDALONE: Electrical generator which does not include its source of kinetic energy, that is, a motor, engine, or turbine is modeled by a separate object.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    + +
    " +3095;IfcElectricMotorTypeEnum;" +

    The IfcElectricMotorTypeEnum defines the range of different types of electric motor that can be specified.

    +

    HISTORY: New type in IFC 2x2

    +

    Enumeration

    +
      +
    • DC: A motor using either generated or rectified D.C. power.
    • +
    • INDUCTION: An alternating current motor in which the primary winding on one member (usually the stator) is connected to the power source and a secondary winding or a squirrel-cage secondary winding on the other member (usually the rotor) carries the induced current. There is no physical electrical connection to the secondary winding, its current is induced.
    • +
    • POLYPHASE: A two or three-phase induction motor in which the windings, one for each phase, are evenly divided by the same number of electrical degrees.
    • +
    • RELUCTANCESYNCHRONOUS: A synchronous motor with a special rotor design which directly lines the rotor up with the rotating magnetic field of the stator, allowing for no slip under load.
    • +
    • SYNCHRONOUS: A motor that operates at a constant speed up to full load. The rotor speed is equal to the speed of the rotating magnetic field of the stator; there is no slip.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3107;IfcMotorConnectionTypeEnum;" +

    The IfcMotorConnectionTypeEnum defines the range of different types of motor connection that can be specified.

    +

    HISTORY: New type in IFC 2x.

    +

    Enumeration

    +
      +
    • BELTDRIVE: An indirect connection made through the medium of a shaped, flexible continuous loop.
    • +
    • COUPLING: An indirect connection made through the medium of the viscosity of a fluid.
    • +
    • DIRECTDRIVE: A direct, physical connection made between the motor and the driven device.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3117;IfcSolarDeviceTypeEnum;" +

    The IfcSolarDeviceTypeEnum defines the range of types of solar devices available.

    +

    HISTORY: New type in IFC 2x4.

    + +

    Enumeration

    +
      +
    • SOLARCOLLECTOR: A device that converts solar radiation into thermal energy (heating water, etc.).
    • +
    • SOLARPANEL: A device that converts solar radiation into electric current.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    + +
    " +3142;IfcAirToAirHeatRecoveryTypeEnum;" +

    Defines general types of pumps. + The IfcPumpTypeEnum contains the following:

    +
      +
    • FIXEDPLATECOUNTERFLOWEXCHANGER: Heat exchanger with moving parts and alternate layers of plates, separated and sealed from the exhaust and supply air stream passages with primary air enters at secondary air outlet location and exits at secondary air inlet location.
    • +
    • FIXEDPLATECROSSFLOWEXCHANGER: Heat exchanger with moving parts and alternate layers of plates, separated and sealed from the exhaust and supply air stream passages with secondary air flow in the direction perpendicular to primary air flow.
    • +
    • FIXEDPLATEPARALLELFLOWEXCHANGER: Heat exchanger with moving parts and alternate layers of plates, separated and sealed from the exhaust and supply air stream passages with primary air enters at secondary air inlet location and exits at secondary air outlet location.
    • +
    • ROTARYWHEEL: A heat wheel with a revolving cylinder filled with an air-permeable medium having a large internal surface area.
    • +
    • RUNAROUNDCOILLOOP: A typical coil energy recovery loop places extended surface, finned tube water coils in the supply and exhaust airstreams of a building.
    • +
    • HEATPIPE: A passive energy recovery device with a heat pipe divided into evaporator and condenser sections.
    • +
    • TWINTOWERENTHALPYRECOVERYLOOPS: An air-to-liquid, liquid-to-air enthalpy recovery system with a sorbent liquid circulates continuously between supply and exhaust airstreams, alternately contacting both airstreams directly in contactor towers.
    • +
    • THERMOSIPHONSEALEDTUBEHEATEXCHANGERS: Sealed systems that consist of an evaporator, a condenser, interconnecting piping, and an intermediate working fluid that is present in both liquid and vapor phases where the evaporator and the condenser are usually at opposite ends of a bundle of straight, individual thermosiphon tubes and the exhaust and supply ducts are adjacent to each other.
    • +
    • THERMOSIPHONCOILTYPEHEATEXCHANGERS: Sealed systems that consist of an evaporator, a condenser, interconnecting piping, and an intermediate working fluid that is present in both liquid and vapor phases where the evaporator and condensor coils are installed independently in the ducts and are interconnected by the working fluid piping.
    • +
    • USERDEFINED: User-defined air to air heat recovery type.
    • +
    • NOTDEFINED: Undefined air to air heat recovery type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3157;IfcBoilerTypeEnum;" +

    Enumeration defining the typical types of boilers. + The IfcBoilerTypeEnum contains the following:

    +
      +
    • WATER: Water boiler.
    • +
    • STEAM: Steam boiler.
    • +
    • USERDEFINED: User-defined Boiler type.
    • +
    • NOTDEFINED: Undefined Boiler type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3165;IfcBurnerTypeEnum;" +

    Enumeration defining the functional type of burner. + The IfcBurnerTypeEnum contains the following:

    + +
      +
    • USERDEFINED: User-defined burner type.
    • +
    • NOTDEFINED: Undefined burner type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x4.
    +
    +
    +
    " +3171;IfcChillerTypeEnum;" +

    Enumeration defining the typical types of Chillers classified by their method of heat rejection. + The IfcChillerTypeEnum contains the following:

    +
      +
    • AIRCOOLED: Air cooled chiller.
    • +
    • WATERCOOLED: Water cooled chiller.
    • +
    • HEATRECOVERY: Heat recovery chiller.
    • +
    • USERDEFINED: User-defined chiller type.
    • +
    • NOTDEFINED: Undefined chiller type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3180;IfcCoilTypeEnum;" +

    Enumeration defining the typical types of coils. + + The IfcCoilTypeEnum contains the following:

    + +
      + +
    • DXCOOLINGCOIL: Cooling coil using a refrigerant to cool the air stream directly.
    • + +
    • WATERCOOLINGCOIL: Cooling coil using chilled water. HYDRONICCOIL supercedes this enumerator.
    • + +
    • STEAMHEATINGCOIL: Heating coil using steam as heating source.
    • + +
    • WATERHEATINGCOIL: Heating coil using hot water as a heating source. HYDRONICCOIL supercedes this enumerator.
    • + +
    • ELECTRICHEATINGCOIL: Heating coil using electricity as a heating source.
    • + +
    • GASHEATINGCOIL: Heating coil using gas as a heating source.
    • + +
    • HYDRONICCOIL: Cooling or Heating coil that uses a hydronic fluid as a cooling or heating source.
    • +
    • USERDEFINED: User-defined coil type.
    • + +
    • NOTDEFINED: Undefined coil type.
    • + + +
    + + + +
    + + + + HISTORY: New enumeration in IFC R2x.
    + +
    + +
    +
    " +3193;IfcCondenserTypeEnum;" +

    Enumeration defining the typical types of condensers. Air is used as the cooling medium for AIRCOOLED; water is used as the cooling medium for all other types. The IfcCondenserTypeEnum contains the following:

    +
      +
    • AIRCOOLED: A condenser in which heat is transferred to an air-stream.
    • +
    • EVAPORATIVECOOLED: A condenser that is cooled evaporatively.
    • +
    • WATERCOOLED: Water-cooled condenser with unspecified operation.
    • +
    • WATERCOOLEDSHELLTUBE: Water-cooled condenser with cooling water circulated through one or more tubes contained within the shell.
    • +
    • WATERCOOLEDSHELLCOIL: Water-cooled condenser with cooling water circulated through one or more continuous or assembled coils contained within the shell.
    • +
    • WATERCOOLEDTUBEINTUBE: Water-cooled condenser consisting of one or more assemblies of two tubes, one within the other.
    • +
    • WATERCOOLEDBRAZEDPLATE: Water-cooled condenser condenser with plates brazed together to form an assembly of separate channels.
    • +
    • USERDEFINED: User-defined condenser type.
    • +
    • NOTDEFINED: Undefined condenser type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2. WATERCOOLED added in IFC 2x4.
    +
    +
    +
    " +3206;IfcCooledBeamTypeEnum;" +

    There are two general types of cooled or chilled beams: passive and active. + + An active Cooled Beam uses a fan or other auxilliary device to aid in air recirculation, while a passive + + Cooled Beam relies solely on convection to cool the space.

    + +

    Enumeration defining the typical types of cooled beams. + + The IfcCooledBeamTypeEnum contains the following:

    + +
      + +
    • ACTIVE: An active or ventilated cooled beam provides cooling (and heating) but can also function as an air terminal in a ventilation system.
    • + +
    • PASSIVE: A passive or static cooled beam provides cooling (and heating) to a room or zone.
    • + +
    • USERDEFINED: User-defined cooled beam type.
    • + +
    • NOTDEFINED: Undefined cooled beam type.
    • + +
    + + + +
    + + + + HISTORY: New enumeration in IFC 2x2.
    + +
    + +
    + +
    " +3214;IfcCoolingTowerTypeEnum;" +

    Enumeration defining the typical types of cooling towers. + The IfcCoolingTowerTypeEnum contains the following:

    +
      +
    • NATURALDRAFT: Air flow is produced naturally.
    • +
    • MECHANICALINDUCEDDRAFT: Air flow is produced by a mechanical device, typically one or more fans, located on +the air outlet side of the cooling tower.
    • +
    • MECHANICALFORCEDDRAFT: Air flow is produced by a mechanical device, typically one or more fans, located on +the inlet air side of the cooling tower.
    • +
    • USERDEFINED: User-defined cooling tower type.
    • +
    • NOTDEFINED: Undefined cooling tower type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3223;IfcEvaporativeCoolerTypeEnum;" +

    Enumeration defining the typical types of evaporative coolers. + The IfcEvaporativeCoolerTypeEnum contains the following:

    +
      +
    • DIRECTEVAPORATIVERANDOMMEDIAAIRCOOLER: Direct evaporative random media air cooler: Cools the air stream by evaporating water dircectly into the air stream using coolers with evaporative pads, usually of aspen wood or plastic fiber/foam.
    • +
    • DIRECTEVAPORATIVERIGIDMEDIAAIRCOOLER: Direct evaporative rigid media air cooler: Cools the air stream by evaporating water dircectly into the air stream using coolers with sheets of rigid, corrugated material as the wetted surface.
    • +
    • DIRECTEVAPORATIVESLINGERSPACKAGEDAIRCOOLER: Direct evaporative slingers packaged air cooler: Cools the air stream by evaporating water dircectly into the air stream using coolers with a water slinger in an evaporative cooling section and a fan section.
    • +
    • DIRECTEVAPORATIVEPACKAGEDROTARYAIRCOOLER: Direct evaporative packaged rotary air cooler: Cools the air stream by evaporating water dircectly into the air stream using coolers that wet and wash the evaporative pad by rotating it through a water bath.
    • +
    • DIRECTEVAPORATIVEAIRWASHER: Direct evaporative air washer: Cools the air stream by evaporating water dircectly into the air stream using coolers with spray-type air washer consist of a chamber or casing containing spray nozzles, and tank for collecting spray water, and an eliminator section for removing entrained drops of water from the air.
    • +
    • INDIRECTEVAPORATIVEPACKAGEAIRCOOLER: Indirect evaporative package air cooler: Cools the air stream by evaporating water indirectly and without adding moisture into the air stream. On one side of the heat exchanger, the secondary air stream is cooled by evaporation, while on the other side of heat exchanger, the primary air stream (conditioned air to be supplied to the room) is sensibly cooled by the heat exchanger surfaces.
    • +
    • INDIRECTEVAPORATIVEWETCOIL: Indirect evaporative wet coil: Cools the air stream by evaporating water indirectly and without adding moisture into the air stream. Water is sprayed directly on the tubes of the heat exchanger where latent cooling takes place and the vaporization of the water on the outside of the heat exchanger tubes allows the simultaneous heat and mass transfer which removes heat from the supply air on the tube side.
    • +
    • INDIRECTEVAPORATIVECOOLINGTOWERORCOILCOOLER: Indirect evaporative cooling tower or coil cooler: Cools the air stream by evaporating water indirectly and without adding moisture into the air stream using a combination of a cooling tower or other evaporative water cooler with a water-to-air heat exchanger coil and water circulating pump.
    • +
    • INDIRECTDIRECTCOMBINATION: Indirect/Direct combination: Cools the air stream by evaporating water indirectly and without adding moisture into the air stream using a two-stage cooler with a first-stage indirect evaporative cooler and second-stage direct evaporative cooler.
    • +
    • USERDEFINED: User-defined evaporative cooler type.
    • +
    • NOTDEFINED: Undefined evaporative cooler type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3238;IfcEvaporatorTypeEnum;" +

    Enumeration defining the typical types of evaporators. + The IfcEvaporatorTypeEnum contains the following:

    +
      +
    • DIRECTEXPANSION: Direct-expansion evaporator.
    • +
    • DIRECTEXPANSIONSHELLANDTUBE: Direct-expansion evaporator where a refrigerant evaporates inside a series of baffles that channel the fluid throughout the shell side.
    • +
    • DIRECTEXPANSIONTUBEINTUBE: Direct-expansion evaporator where a refrigerant evaporates inside one or more pairs of coaxial tubes.
    • +
    • DIRECTEXPANSIONBRAZEDPLATE: Direct-expansion evaporator where a refrigerant evaporates inside plates brazed or welded together to make up an assembly of separate channels.
    • +
    • FLOODEDSHELLANDTUBE: Evaporator in which refrigerant evaporates outside tubes.
    • +
    • SHELLANDCOIL: Evaporator in which refrigerant evaporates inside a simple coiled tube immersed in the fluid to be cooled.
    • +
    • USERDEFINED: User-defined evaporator type.
    • +
    • NOTDEFINED: Undefined evaporator type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3250;IfcHeatExchangerTypeEnum;" +

    Enumeration defining the typical types of heat exchangers. + The IfcHeatExchangerTypeEnum contains the following:

    +
      +
    • PLATE: Plate heat exchanger.
    • +
    • SHELLANDTUBE: Shell and Tube heat exchanger.
    • +
    • USERDEFINED: User-defined heat exchanger type.
    • +
    • NOTDEFINED: Undefined heat exchanger type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3258;IfcHumidifierTypeEnum;" +

    Enumeration defining the typical types of humidifiers. + The IfcHumidifierTypeEnum contains the following:

    +
      +
    • STEAMINJECTION: Water vapor is added into the airstream through direction steam injection.
    • +
    • ADIABATICAIRWASHER: Water vapor is added into the airstream through adiabatic evaporation using an air washing element.
    • +
    • ADIABATICPAN: Water vapor is added into the airstream through adiabatic evaporation using a pan.
    • +
    • ADIABATICWETTEDELEMENT: Water vapor is added into the airstream through adiabatic evaporation using a wetted element.
    • +
    • ADIABATICATOMIZING: Water vapor is added into the airstream through adiabatic evaporation using an atomizing element.
    • +
    • ADIABATICULTRASONIC: Water vapor is added into the airstream through adiabatic evaporation using an ultrasonic element.
    • +
    • ADIABATICRIGIDMEDIA: Water vapor is added into the airstream through adiabatic evaporation using a rigid media.
    • +
    • ADIABATICCOMPRESSEDAIRNOZZLE: Water vapor is added into the airstream through adiabatic evaporation using a compressed air nozzle.
    • +
    • ASSISTEDELECTRIC: Water vapor is added into the airstream through water heated evaporation using an electric heater.
    • +
    • ASSISTEDNATURALGAS: Water vapor is added into the airstream through water heated evaporation using a natural gas heater.
    • +
    • ASSISTEDPROPANE: Water vapor is added into the airstream through water heated evaporation using a propane heater.
    • +
    • ASSISTEDBUTANE: Water vapor is added into the airstream through water heated evaporation using a butane heater.
    • +
    • ASSISTEDSTEAM: Water vapor is added into the airstream through water heated evaporation using a steam heater.
    • +
    • USERDEFINED: User-defined humidifier type.
    • +
    • NOTDEFINED: Undefined humidifier type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3277;IfcTubeBundleTypeEnum;" +

    Enumeration defining the typical types of tube bundles. + The IfcTubeBundleTypeEnum contains the following:

    +
      +
    • FINNED: Finned tube bundle type.
    • +
    • USERDEFINED: User-defined tube bundle type.
    • +
    • NOTDEFINED: Undefined tube bundle type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3284;IfcUnitaryEquipmentTypeEnum;" +

    Enumeration defining the functional type of unitary equipment. + The IfcUnitaryEquipmentTypeEnum contains the following:

    +
      +
    • AIRHANDLER: A unitary air handling unit typically containing a fan, economizer, and coils.
    • +
    • AIRCONDITIONINGUNIT: A unitary packaged air-conditioning unit typically used in residential or light commercial applications.
    • +
    • DEHUMIDIFIER: A unitary packaged dehumidification unit. Note: units supporting multiple modes (dehumidification, cooling, and/or heating) should use AIRCONDITIONINGUNIT.
    • +
    • SPLITSYSTEM: A system which separates the compressor from the evaporator, but acts as a unitary component typically within residential or light commercial applications.
    • +
    • ROOFTOPUNIT: A packaged assembly that is either field-erected or manufactured atop the roof of a large residential or commercial building and acts as a unitary component.
    • +
    • USERDEFINED: User-defined unitary equipment type.
    • +
    • NOTDEFINED: Undefined unitary equipment type.
    • +
    + +
    + +

    + HISTORY: New enumeration in IFC R2x. DEHUMIDIFIER added in IFC 2x4
    +

    +
    +
    +
    " +3295;IfcEngineTypeEnum;" +

    Enumeration defining the typical types of engines. The IfcEngineTypeEnum contains the following:

    +
      +
    • EXTERNALCOMBUSTION: Combustion is external.
    • +
    • INTERNALCOMBUSTION: Combustion is internal.
    • +
    • USERDEFINED: User-defined engine type.
    • +
    • NOTDEFINED: Undefined engine type.
    • +
    + +
    HISTORY: New enumeration in IFC 2x4.
    +
    " +3303;IfcFanTypeEnum;" +

    + Enumeration defining the typical types of fans. + The IfcFanTypeEnum contains the following:

    +
      +
    • CENTRIFUGALFORWARDCURVED: Air flows through the impeller radially using blades that are forward curved.
    • +
    • CENTRIFUGALRADIAL: Air flows through the impeller radially using blades that are uncurved or slightl forward curved.
    • +
    • CENTRIFUGALBACKWARDINCLINEDCURVED: Air flows through the impeller radially using blades that are backward curved.
    • +
    • CENTRIFUGALAIRFOIL: Air flows through the impeller radially using blades are airfoil shaped.
    • +
    • TUBEAXIAL: Air flows through the impeller axially with reduced tip clearance and operating at higher tip speeds.
    • +
    • VANEAXIAL: Air flows through the impeller axially with guide vanes and reduced running blade tip clearance.
    • +
    • PROPELLORAXIAL: Air flows through the impeller axially and small hub-to-tip ratio impeller mounted in an orifice plate or inlet ring.
    • +
    • USERDEFINED: User-defined fan type.
    • +
    • NOTDEFINED: Undefined fan type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3316;IfcCompressorTypeEnum;" +

    + Types of compressors. + The IfcCompressorTypeEnum contains the following:

    +
      +
    • DYNAMIC: The pressure of refrigerant vapor is increased by a continuous transfer of angular momentum from a rotating member to the vapor followed by conversion of this momentum into static pressure.
    • +
    • RECIPROCATING: Positive-displacement compressor using a piston driven by a connecting rod from a crankshaft.
    • +
    • ROTARY: Positive-displacement compressor using a roller or rotor device.
    • +
    • SCROLL: Positive-displacement compressor using two inter-fitting, spiral-shaped scroll members.
    • +
    • TROCHOIDAL: Positive-displacement compressor using a rolling motion of one circle outside or inside the circumference of a basic circle and produce either epitrochoids or hypotrochoids.
    • +
    • SINGLESTAGE: Positive-displacement reciprocating compressor where vapor is compressed in a single stage.
    • +
    • BOOSTER: Positive-displacement reciprocating compressor where pressure is increased by a booster.
    • +
    • OPENTYPE: Positive-displacement reciprocating compressor where the shaft extends through a seal in the crankcase for an external drive.
    • +
    • HERMETIC: Positive-displacement reciprocating compressor where the motor and compressor are contained within the same housing, with the motor shaft integral with the compressor crankshaft and the motor in contact with refrigerant.
    • +
    • SEMIHERMETIC: Positive-displacement reciprocating compressor where the hermetic compressors use bolted construction amenable to field repair.
    • +
    • WELDEDSHELLHERMETIC: Positive-displacement reciprocating compressor where the motor compressor is mounted inside a steel shell, which, in turn is sealed by welding.
    • +
    • ROLLINGPISTON: Positive-displacement rotary compressor using a roller mounted on the eccentric of a shaft with a single vane in the nonrotating cylindrical housing.
    • +
    • ROTARYVANE: Positive-displacement rotary compressor using a roller mounted on the eccentric of a shaft with multiple vanes in the nontotating cylindrical housing.
    • +
    • SINGLESCREW: Positive-displacement rotary compressor using a single cylindrical main rotor that works with a pair of gate rotors.
    • +
    • TWINSCREW: Positive-displacement rotary compressor using two mating helically grooved rotors, male (lobes) and female (flutes) in a stationary housing with inlet and outlet gas ports.
    • +
    • USERDEFINED: User-defined compressor type.
    • +
    • NOTDEFINED: Undefined compressor type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x.
    +
    +
    +
    " +3337;IfcPumpTypeEnum;" +

    Defines general types of pumps. + + The IfcPumpTypeEnum contains the following:

    + +
      + +
    • CIRCULATOR: A Circulator pump is a generic low-pressure, low-capacity pump. It may have a wet rotor and + may be driven by a flexible-coupled motor.
    • + +
    • ENDSUCTION: An End Suction pump, when mounted horizontally, has a single horizontal inlet on the impeller suction side + and a vertical discharge. It may have a direct or close-coupled motor.
    • + +
    • SPLITCASE: A Split Case pump, when mounted horizontally, has an inlet and outlet on each side of the impeller. + The impeller can be easily accessed by removing the front of the impeller casing. It may have a direct or close-coupled motor.
    • + +
    • SUBMERSIBLEPUMP: A pump designed to be immersed in a fluid, typically a collection tank.
    • + +
    • SUMPPUMP: A pump designed to sit above a collection tank with a suction inlet extending into the tank.
    • + +
    • VERTICALINLINE: A Vertical Inline pump has the pump and motor close-coupled on the pump casing. + The pump depends on the connected, horizontal piping for support, with the suction and discharge along the piping axis.
    • + +
    • VERTICALTURBINE: A Vertical Turbine pump has a motor mounted vertically on the pump casing for either + wet-pit sump mounting or dry-well mounting.
    • + +
    • USERDEFINED: User-defined pump type.
    • + +
    • NOTDEFINED: Pump type has not been defined.
    • + +
    + + + +
    + + + + HISTORY: New enumeration in IFC R2x. SUBMERSIBLEPUMP and SUMPPUMP added in IFC2x4.
    + +
    + +
    +
    " +3350;IfcDamperTypeEnum;" +

    + This enumeration defines the various types of damper:

    +
      +
    • BALANCINGDAMPER: Damper used for purposes of manually balancing pressure differences. Commonly operated by mechanical adjustment.
    • +
    • BACKDRAFTDAMPER: Backdraft damper used to restrict the movement of air in one direction. Commonly operated by mechanical spring.
    • +
    • BLASTDAMPER: Blast damper use to prevent protect occupants and equipment against overpressures resultant of an explosion. Commonly operated by mechanical spring.
    • +
    • CONTROLDAMPER: Control damper used to modulate the flow of air by adjusting the position of the blades. Commonly operated by an actuator of a building automation system.
    • +
    • FIREDAMPER: Fire damper used to prevent the spread of fire for a specified duration. Commonly operated by fusable link that melts above a certain temperature.
    • +
    • FIRESMOKEDAMPER: Combination fire and smoke damper used to preven the spread of fire and smoke. Commonly operated by a fusable link and a smoke detector
    • +
    • FUMEHOODEXHAUST: Fume hood exhaust damper. Commonly operated by actuator.
    • +
    • GRAVITYDAMPER: Gravity damper closes from the force of gravity. Commonly operated by gravitational weight.
    • +
    • GRAVITYRELIEFDAMPER: Gravity-relief damper used to allow air to move upon a buildup of enough pressure to overcome the gravitational force exerted upon the damper blades. Commonly operated by gravitational weight.
    • +
    • RELIEFDAMPER: Relief damper used to allow air to move upon a buildup of a specified pressure differential. Commonly operated by mechanical spring.
    • +
    • SMOKEDAMPER: Smoke damper used to prevent the spread of smoke. Commonly operated by a smoke detector of a building automation system.
    • +
    • USERDEFINED: User-defined damper.
    • +
    • NOTDEFINED: Undefined damper.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2.0
    +
    +
    +
    " +3367;IfcAirTerminalBoxTypeEnum;" +

    + This enumeration identifies different types of air terminal boxes.

    + +

    Valid enumerations are:

    +
      +
    • CONSTANTFLOW: Terminal box does not include a means to reset the volume automatically to an outside signal such as thermostat.
    • +
    • VARIABLEFLOWPRESSUREDEPENDANT: terminal box includes a means to reset the volume automatically to a different control point in response to an outside signal such as thermostat: air-flow rate depends on supply pressure.
    • +
    • VARIABLEFLOWPRESSUREINDEPENDANT: terminal box includes a means to reset the volume automatically to a different control point in response to an outside signal such as thermostat: air-flow rate is independant of supply pressure.
    • +
    • USERDEFINED: User-defined terminal box.
    • +
    • NOTDEFINED: Undefined terminal box.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2.0
    +
    +
    +
    " +3376;IfcValveTypeEnum;" +

    The IfcValveTypeEnum defines the + range of different types of valve that can be specified. These are typically + used in conjunction with Pset_ValveTypeCommon, which contains common + properties for all valve types. The IfcValveTypeEnum contains:

    +
      +
    • AIRRELEASE: Valve used to release air from a pipe or fitting.
    • +
    • ANTIVACUUM: Valve that opens to admit air if the pressure falls below + atmospheric pressure (BS6100 330 4104)
    • +
    • CHANGEOVER: Valve that enables flow to be switched between pipelines (3 or 4 + port).
    • +
    • CHECK: Valve that permits water to flow in one direction only and is + enclosed when there is no flow (2 port).
    • +
    • COMMISSIONING: Valve used to facilitate commissioning of a system (2 port).
    • +
    • DIVERTING: Valve that enables flow to be diverted from one branch of a + pipeline to another (3 port).
    • +
    • DOUBLECHECK: An assembly that incorporates two valves used to prevent backflow + (BS6100 330 4106).
    • +
    • DOUBLEREGULATING: Valve used to facilitate regulation of fluid flow in a system.
    • +
    • DRAWOFFCOCK: A valve used to remove fluid from a piping system.
    • +
    • FAUCET: Faucet valve typically used as a flow discharge.
    • +
    • FLUSHING: Valve that flushes a predetermined quantity of water to cleanse a + toilet, urinal, etc.
    • +
    • GASCOCK: Valve that is used for controlling the flow of gas.
    • +
    • GASTAP: Gas tap typically used for venting or discharging gas from a system.
    • +
    • ISOLATING: Valve that closes off flow in a pipeline.
    • +
    • MIXING: Valve that enables flow from two branches of a pipeline to be mixed + together (3 port).
    • +
    • PRESSUREREDUCING: Valve that reduces the pressure of a fluid immediately downstream + of its position in a pipeline to a preselected value or by a predetermined + ratio.
    • +
    • PRESSURERELIEF: Spring or weight loaded valve that automatically discharges to a + safe place fluid that has built up to excessive pressure in pipes or + fittings
    • +
    • REGULATING: Valve used to facilitate regulation of fluid flow in a system.
    • +
    • SAFETYCUTOFF: Valve that closes under the action of a safety mechanism such as a + drop weight, solenoid etc.
    • +
    • STEAMTRAP: Valve that restricts flow of steam while allowing condensate to + pass through.
    • +
    • STOPCOCK: An isolating valve used on a domestic water service.
    • +
    • USERDEFINED: User-defined valve type.
    • +
    • NOTDEFINED: Undefined valve type.
    • +
    +
    +

    HISTORY: New type in IFC R2.0
    +

    +
    +
    " +3403;IfcFlowMeterTypeEnum;" +

    + + This enumeration defines various types of flow meter:

    + +
      + +
    • ENERGYMETER: An electric meter or energy meter is a device that measures the amount of electrical energy supplied to or produced by a residence, business or machine.
    • + +
    • GASMETER: A device that measures the quantity of a gas or fuel.
    • + +
    • OILMETER: A device that measures the quantity of oil.
    • + +
    • WATERMETER: A device that measures the quantity of water.
    • + +
    • USERDEFINED: User-defined meter type
    • + +
    • NOTDEFINED: Undefined meter type
    • + +
    + + + +
    + + + + HISTORY: New enumeration in IFC 2x2
    + +
    + +
    +
    " +3413;IfcDuctFittingTypeEnum;" +

    This enumeration is used to identify the primary purpose of a duct fitting. This is a very basic categorization mechanism + to generically identify the duct fitting type. Subcategories + of duct fittings are not enumerated. + The IfcDuctFittingTypeEnum contains the following:

    +
      +
    • BEND: A fitting with typically two ports used to change + the direction of flow between connected elements.
    • +
    • CONNECTOR: Connector fitting, typically used to join two + ports together within a flow distribution system + (e.g., a coupling used to join two duct segments).
    • +
    • ENTRY: Entry fitting, typically unconnected at one port + and connected to a flow distribution system at + the other (e.g., an outside air duct system + intake opening).
    • +
    • EXIT: Exit fitting, typically unconnected at one port + and connected to a flow distribution system at + the other (e.g., an exhaust air discharge + opening).
    • +
    • JUNCTION: A fitting with typically more than two ports used + to redistribute flow among the ports and/or to + change the direction of flow between connected + elements (e.g, tee, cross, wye, etc.).
    • +
    • OBSTRUCTION: A fitting with typically two ports used to + obstruct or restrict flow between the connected + elements (e.g., screen, perforated plate, etc.).
    • +
    • TRANSITION: A fitting with typically two ports having + different shapes or sizes. Can also be used to + change the direction of flow between connected + elements.
    • +
    • USERDEFINED: User-defined fitting.
    • +
    • NOTDEFINED: Undefined fitting.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2
    +
    +
    +
    " +3426;IfcPipeFittingTypeEnum;" +

    This enumeration is used to identify the primary purpose of a pipe fitting. This is a very basic categorization mechanism + to generically identify the pipe fitting type. Subcategories + of pipe fittings are not enumerated. + The IfcpipeFittingTypeEnum contains the following:

    +
      +
    • BEND: A fitting with typically two ports used to change + the direction of flow between connected elements.
    • +
    • CONNECTOR: Connector fitting, typically used to join two + ports together within a flow distribution system + (e.g., a coupling used to join two pipe segments).
    • +
    • ENTRY: Entry fitting, typically unconnected at one port + and connected to a flow distribution system at + the other (e.g., a breeching inlet).
    • +
    • EXIT: Exit fitting, typically unconnected at one port + and connected to a flow distribution system at + the other (e.g., a hose bibb).
    • +
    • JUNCTION: A fitting with typically more than two ports used + to redistribute flow among the ports and/or to + change the direction of flow between connected + elements (e.g, tee, cross, wye, etc.).
    • +
    • OBSTRUCTION: A fitting with typically two ports used to + obstruct or restrict flow between the connected + elements (e.g., screen, perforated plate, etc.).
    • +
    • TRANSITION: A fitting with typically two ports having + different shapes or sizes. Can also be used to + change the direction of flow between connected + elements.
    • +
    • USERDEFINED: User-defined fitting.
    • +
    • NOTDEFINED: Undefined fitting.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2
    +
    +
    +
    " +3439;IfcTankTypeEnum;" +

    Enumeration defining the typical types of tanks. + + The IfcTankTypeEnum contains the following:

    + +
      + +
    • BASIN: An arbitrary open tank type.
    • + +
    • BREAKPRESSURE: An open container that breaks the hydraulic pressure in a distribution system, typically located between the fluid reservoir and the fluid supply points. A typical break pressure tank allows the flow to discharge into the atmosphere, thereby reducing its hydrostatic pressure to zero.
    • + +
    • EXPANSION: A closed container used in a closed fluid distribution system to mitigate the effects of thermal expansion or water hammer. The tank is typically constructed with a diaphragm dividing the tank into two sections, with fluid on one side of the diaphragm and air on the other. One example application is when connected to the primary circuit of a hot water system to accommodate the increase in volume of the water when it is heated.
    • + +
    • FEEDANDEXPANSION: An open tank that is used for both storage and thermal expansion. A typical example is a tank used to store make-up water at ambient pressure for supply to a hot water system, simultaneously accommodating increases in volume of the water when heated.
    • + +
    • PRESSUREVESSEL: A closed container used for storing fluids or gases at a pressure different from the ambient pressure. A pressure vessel is typically rated by an authority having jurisdiction for the operational pressure.
    • + +
    • STORAGE: An open or closed containter used for storing a fluid at ambient pressure and from which it can be supplied to the fluid distribution system. There are many examples of storage tanks, such as potable water storage tanks, fuel storage tanks, etc.
    • + +
    • VESSEL: An arbitrary closed tank type.
    • + +
    • USERDEFINED: User-defined tank type.
    • + +
    • NOTDEFINED: Undefined tank type.
    • + +
    + + + +
    + + + + HISTORY: New enumeration in IFC 2x2. BASIN and VESSEL added in IFC2x4.
    + +
    + +
    +
    " +3452;IfcDuctSilencerTypeEnum;" +

    + Enumeration defining the typical types of duct silencers. + The IfcDuctSilencerTypeEnum contains the following:

    +
      +
    • FLATOVAL: Flat-oval shaped duct silencer type.
    • +
    • RECTANGULAR: Rectangular shaped duct silencer type.
    • +
    • ROUND: Round duct silencer type.
    • +
    • USERDEFINED: User-defined duct silencer type.
    • +
    • NOTDEFINED: Undefined duct silencer type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3461;IfcFilterTypeEnum;" +

    + This enumeration defines the various types of filter typically used + within building services distribution systems:

    +
      +
    • AIRPARTICLEFILTER: A filter used to remove particulates from air.
    • +
    • COMPRESSEDAIRFILTER: A filter used to remove particulates from compressed air.
    • +
    • ODORFILTER: A filter used to remove odors from air.
    • +
    • OILFILTER: A filter used to remove particulates from oil.
    • +
    • STRAINER: A filter used to remove particulates from a fluid.
    • +
    • WATERFILTER: A filter used to remove particulates from water.
    • +
    • USERDEFINED: User-defined filter type.
    • +
    • NOTDEFINED: Undefined filter type.
    • +
    + +
    + + HISTORY: New enumeration in IFC R2x. COMPRESSEDAIRFILTER added in IFC2x4.
    +
    +
    +
    " +3473;IfcPipeSegmentTypeEnum;" +

    + This enumeration is used to identify the primary purpose of a + pipe segment. This is a very basic categorization mechanism + to generically identify the pipe segment type. Subcategories + of pipe segments are not enumerated. + The IfcPipeSegmentTypeEnum contains the following:

    +
      +
    • CULVERT: A covered channel or large pipe that forms a watercourse below ground level, usually under a road or railway.
    • +
    • RIGIDSEGMENT: A rigid segment is continuous linear segment of pipe that cannot be deformed.
    • +
    • FLEXIBLESEGMENT: A flexible segment is a continuous non-linear segment of pipe that can be deformed and change the direction of flow.
    • +
    • GUTTER: A gutter segment is a continuous open-channel segment of pipe.
    • +
    • SPOOL: A type of rigid segment that is typically shorter and used for providing connectivity within a piping network.
    • +
    • USERDEFINED: User-defined segment.
    • +
    • NOTDEFINED: Undefined segment.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2
    +
    +
    +
    " +3484;IfcDuctSegmentTypeEnum;" +

    + This enumeration is used to identify the primary purpose of a + duct segment. This is a very basic categorization mechanism + to generically identify the duct segment type. Subcategories + of duct segments are not enumerated. + The IfcDuctSegmentTypeEnum contains the following:

    +
      +
    • RIGIDSEGMENT: A rigid segment is continuous linear segment of duct + that cannot be deformed.
    • +
    • FLEXIBLESEGMENT: A flexible segment is a continuous non-linear segment + of duct that can be deformed and change the direction + of flow.
    • +
    • USERDEFINED: User-defined segment.
    • +
    • NOTDEFINED: Undefined segment.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2
    +
    +
    +
    " +3529;IfcAirTerminalTypeEnum;" +

    + Enumeration defining the functional types of air terminals. + The IfcAirTerminalTypeEnum contains the following:

    +
      +
    • GRILLE: A covering for any area through which air passes.
    • +
    • REGISTER: A grille typically equipped with a damper or control valve.
    • +
    • DIFFUSER: An outlet discharging supply air in various directions and planes.
    • +
    • LOUVRE: A rectilinear louvre.
    • +
    • USERDEFINED: User-defined air terminal type.
    • +
    • NOTDEFINED: Undefined air terminal type.
    • +
    + +
    + + NOTE: Architectural louvres within doors or windows are defined by IfcPermeableCoveringProperties. + +
    + +
    + + HISTORY: New enumeration in IFC R2x2. Modified in IFC R2x4 to add LOUVRE and remove EYEBALL, IRIS, LINEARGRILLE, LINEARDIFFUSER
    +
    +
    +
    " +3540;IfcSpaceHeaterTypeEnum;" +

    Enumeration defining the functional type of space heater. + The IfcSpaceHeaterTypeEnum contains the following:

    + +
      +
    • CONVECTOR: A heat-distributing unit that operates with gravity-circulated air.
    • +
    • RADIATOR: A heat-distributing unit that operates with thermal radiation.
    • +
    • USERDEFINED: User-defined space heater type.
    • +
    • NOTDEFINED: Undefined space heater type.
    • +
    + +
    +NOTE: This enumeration was revised in IFC 2x4 and was renamed from IfcHydronicHeaterTypeEnum in IFC R2x. +
    + +
    +HISTORY: New enumeration in IFC R2x.
    +
    + +
    " +3549;IfcMedicalDeviceTypeEnum;" +

    Enumeration defining the functional type of medical device. + The IfcMedicalDeviceTypeEnum contains the following:

    + +
      +
    • AIRSTATION: Device that provides purified medical air, composed of an air compressor and air treatment line.
    • +
    • FEEDERUNIT: Device that feeds air to an oxygen generator, composed of an air compressor, air treatment line, and an air receiver.
    • +
    • OXYGENGENERATOR: Device that generates oxygen from air.
    • +
    • OXYGENPLANT: Device that combines a feed air unit, oxygen generator, and backup oxygen cylinders.
    • +
    • VACUUMSTATION: Device that provides suction, composed of a vacuum pump and bacterial filtration line.
    • +
    • USERDEFINED: User-defined medical device type.
    • +
    • NOTDEFINED: Undefined medical device type.
    • +
    + +
    +HISTORY: New enumeration in IFC 2x4.
    +
    + +
    " +3650;IfcVibrationIsolatorTypeEnum;" +

    Enumeration defining the typical types of vibration isolators. + The IfcVibrationIsolatorTypeEnum contains the following:

    +
      +
    • COMPRESSION: Compression type vibration isolator.
    • +
    • SPRING: Spring type vibration isolator.
    • +
    • USERDEFINED: User-defined vibration isolator type.
    • +
    • NOTDEFINED: Undefined vibration isolator type.
    • +
    + +
    + + HISTORY: New enumeration in IFC 2x2.
    +
    +
    +
    " +3662;IfcWasteTerminalTypeEnum;" +

    The IfcWasteTerminalTypeEnum defines the range of different types of waste terminal that can be specified.

    +

    HISTORY: New type in IFC 2x2. GREASEINTERCEPTOR, OILINTERCEPTOR, PETROLINTERCEPTOR moved to IfcInterceptorTypeEnum in IFC2x4.

    +
    +

    Enumeration

    +
      +
    • FLOORTRAP: Pipe fitting, set into the floor, that retains liquid to prevent the passage of foul air
    • +
    • FLOOORWASTE: Pipe fitting, set into the floor, that collects waste water and discharges it to a separate trap.
    • +
    • GULLYSUMP: Pipe fitting or assembly of fittings to receive surface water or waste water, fitted with a grating or sealed cover.
    • +
    • GULLYTRAP: Pipe fitting or assembly of fittings to receive surface water or waste water, fitted with a grating or sealed cover and discharging through a trap (BS6100 330 3504 modified).
    • +
    • ROOFDRAIN: Pipe fitting, set into the roof, that collects rainwater for discharge into the rainwater system.
    • +
    • WASTEDISPOSALUNIT: Electrically operated device that reduces kitchen or other waste into fragments small enough to be flushed into a drainage system.
    • +
    • WASTETRAP: Pipe fitting, set adjacent to a sanitary terminal, that retains liquid to prevent the passage of foul air.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3675;IfcStackTerminalTypeEnum;" +

    An IfcStackTerminalTypeEnum defines the range of different types of stack terminal that can be specified for use at the top of a vertical stack subsystem.

    +

    HISTORY: New type in IFC 2x

    +

    Enumeration

    +
      +
    • BIRDCAGE: Guard cage, typically wire mesh, at the top of the stack preventing access by birds.
    • +
    • COWL: A cowling placed at the top of a stack to eliminate downdraft.
    • +
    • RAINWATERHOPPER: A box placed at the top of a rainwater downpipe to catch rainwater from guttering.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3684;IfcSanitaryTerminalTypeEnum;" +

    The IfcSanitaryTerminalTypeEnum defines the range of different types of sanitary terminal that can be specified.

    + +
    +

    NOTE: The value WCSEAT has been deprecated and should no longer be used; toilet seats should be represented by IfcDiscreteAccessory with ObjectType 'WC Seat'.

    +

    HISTORY: New type in IFC 2x2

    +
    +

    Enumeration

    +
      +
    • BATH: Sanitary appliance for immersion of the human body or parts of it.
    • +
    • BIDET: Waste water appliance for washing the excretory organs while sitting astride the bowl.
    • +
    • CISTERN: A water storage unit attached to a sanitary terminal that is fitted with a device, operated automatically or by the user, that discharges water to cleanse a water closet (toilet) pan, urinal or slop hopper.
    • +
    • SHOWER: Installation or waste water appliance that emits a spray of water to wash the human body.
    • +
    • SINK: Waste water appliance for receiving, retaining or disposing of domestic, culinary, laboratory or industrial process liquids.
    • +
    • SANITARYFOUNTAIN: A sanitary terminal that provides a low pressure jet of water for a specific purpose.
    • +
    • TOILETPAN: Soil appliance for the disposal of excrement.
    • +
    • URINAL: Soil appliance that receives urine and directs it to a waste outlet (BS6100).
    • +
    • WASHHANDBASIN: Waste water appliance for washing the upper parts of the body.
    • +
    • WCSEAT: [Deprecated] Hinged seat that fits on the top of a water closet (WC) pan.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3700;IfcFireSuppressionTerminalTypeEnum;" + +

    The IfcFireSuppressionTerminalTypeEnum defines the range of different types of fire suppression terminal that can be specified.

    + +
    HISTORY: New type in IFC 2x2
    + +Enumeration + +
      +
    • BREECHINGINLET: Symmetrical pipe fitting that unites two or more inlets into a single pipe (BS6100 330 114 adapted). A breeching inlet may be used on either a wet or dry riser. Used by fire services personnel for fast connection of fire appliance hose reels. May also be used for foam.
    • +
    • FIREHYDRANT: Device, fitted to a pipe, through which a temporary supply of water may be provided (BS6100 330 6107). May also be termed a stand pipe.
    • +
    • HOSEREEL: A supporting framework on which a hose may be wound (BS6100 155 8201).
    • +
    • SPRINKLER: Device for sprinkling water from a pipe under pressure over an area (BS6100 100 3432).
    • +
    • SPRINKLERDEFLECTOR: Device attached to a sprinkler to deflect the water flow into a spread pattern to cover the required area.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Underined type.
    • +
    + +
    " +3727;IfcInterceptorTypeEnum;" +

    The IfcInterceptorTypeEnum defines the range of different types of interceptor that can be specified.

    +

    HISTORY: New type in IFC 2x4

    +

    Enumeration

    + +
      +
    • CYCLONIC: Removes larger liquid drops or larger solid particles.
    • +
    • GREASE: Chamber, on the line of a drain or discharge pipe, that prevents grease passing into a drainage system (BS6100 330 6205).
    • +
    • OIL: One or more chambers arranged to prevent the ingress of oil to a drain or sewer, that retain the oil for later removal (BS6100 330 67316).
    • +
    • PETROL: Two or more chambers with inlet and outlet pipes arranged to allow petrol/gasoline collected on the surface of water drained into them to evaporate through ventilating pipes.
    • +
    • USERDEFINED: User-defined type.
    • +
    • NOTDEFINED: Undefined type.
    • +
    +
    " +3819;IfcDocumentConfidentialityEnum;" + +

    IfcDocumentConfidentialityEnum enables selection of the level of confidentiality of document information from a list of choices.

    + +
    +HISTORY: New enumeration in IFC 2x +
    + +

    Enumeration

    +
      +
    • PUBLIC: Document is publicly available.
    • +
    • RESTRICTED: Document availability is restricted.
    • +
    • CONFIDENTIAL: Document is confidential and its contents should not be revealed without permission.
    • +
    • PERSONAL: Document is personal to the author.
    • +
    • USERDEFINED
    • +
    • NOTDEFINED
    • +
    + +
    " +3826;IfcDocumentStatusEnum;" + +

    IfcDocumentStatusEnum enables selection of the status of document information from a list of choices.

    + +
    +HISTORY: New enumeration in IFC Release 2x. +
    + +
    " +3903;IfcBenchmarkEnum;" + +

    IfcBenchmarkEnum is an enumeration used to identify the logical comparators that can be applied in conjunction with constraint values.

    + +
    +HISTORY: New type in IFC Release 2.0 +
    + +
    +IFC2x4 CHANGE: Extended to include comparators for item-set and set-item comparisons: INCLUDES, NOTINCLUDES, INCLUDEDIN and NOTINCLUDEDIN, to test if an individual item is a member of a given aggregation, or if an aggregation has a given individual item as a member. +
    + +

    Enumeration

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ValueDefinition
    GREATERTHANIdentifies that a value must be greater than that set by the constraint.
    GREATERTHANOREQUALTOIdentifies that a value must be either greater than or equal to that set by the constraint.
    LESSTHANIdentifies that a value must be less than that set by the constraint.
    LESSTHANOREQUALTOIdentifies that a value must be either less than or equal to that set by the constraint.
    EQUALTOIdentifies that a value must be equal to that set by the constraint.
    NOTEQUALTOIdentifies that a value must be not equal to that set by the constraint.
    INCLUDESIdentifies that an aggregation (set, list or table) must include the value (individual item) set by the constraint.
    NOTINCLUDESIdentifies that an aggregation (set, list or table) must not include (i.e must exclude) the value (individual item) set by the constraint.
    INCLUDEDINIdentifies that a value (individual item) must be included in the aggregation (set, list or table) set by the constraint.
    NOTINCLUDEDINIdentifies that a value (individual item) must not be included (i.e. must be excluded) in the aggregation (set, list or table) set by the constraint.
    + +
    " +3921;IfcObjectiveEnum;" + +

    IfcObjectiveEnum is an enumeration used to determine the objective for which purpose the constraint needs to be satisfied.

    + +
    +HISTORY: IFC2x4 CHANGE: Extended to include CODEWAIVER. +
    + +

    Enumeration

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    ValueDefinition
    CODECOMPLIANCEA constraint whose objective is to ensure satisfaction of a code compliance provision.
    CODEWAIVERA constraint whose objective is to identify an agreement that code compliance requirements (the waiver) will not be enforced.
    DESIGNINTENTA constraint whose objective is to ensure satisfaction of a design intent provision.
    HEALTHANDSAFETYA constraint whose objective is to ensure satisfaction of a health and safety provision.
    REQUIREMENTA constraint whose objective is to ensure satisfaction of a project requirement provision.
    SPECIFICATIONA constraint whose objective is to ensure satisfaction of a specification provision.
    TRIGGERCONDITIONA constraint whose objective is to indicate a limiting value beyond which the condition of an object requires a particular form of attention.
    + +
    " +3931;IfcConstraintEnum;" + +

    IfcConstraintEnum is an enumeration used to qualify a constraint.

    + +
    +HISTORY: New type in IFC Release 2.0 +
    + +

    Enumeration

    + + + + + + + + + + + + + + + + + +
    ValueDefinition
    HARDQualifies a constraint such that it must be followed rigidly within or at the values set.
    SOFTQualifies a constraint such that it should be followed within or at the values set.
    ADVISORYQualifies a constraint such that it is advised that it is followed within or at the values set.
    + +
    " +3947;IfcLogicalOperatorEnum;" + +

    Definition: IfcLogicalOperatorEnum is an enumeration that defines the logical operators that may be applied for the satisfaction of one or more operands (IfcConstraint) at a time.

    + +
    +HISTORY  New type in IFC Release 2.0. Renamed from IfcConstraintAggregatorEnum in IFC 2x2 +
    +
    +IFC2x4 CHANGE: Extended to include LOGICALXOR, LOGICALNOTAND and LOGICALNOTOR. +
    + +

    Enumeration

    + + + + + + + + + + + + + + + + + + + + + + + + + +
    ValueDefinition
    LOGICALANDDefines a relationship between operands whereby the result is true if all operands are true, i.e. false if at least +one operand is false.
    LOGICALORDefines a relationship between operands whereby the result is true if at least one operand is true, i.e false if +all operands are false.
    LOGICALXORDefines a relationship between operands whereby the result is true if exactly one operand is true (exclusive or).
    LOGICALNOTANDDefines a relationship between operands whereby the result is true if at least one operand is false, i.e false if +all operands are true.
    LOGICALNOTORDefines a relationship between operands whereby the result is true if all operands are false, i.e false if at least +one operand is true.
    + +

    Use Definition

    + +

    The IfcLogicalOperatorEnum, when applied in a case of three operands, A, B and C, evaluates for each operator as +follows: +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TRUTH TABLE: LOGICALAND(A,B,C)
    AFFFTFTTT
    BFFTFTFTT
    CFTFFTTFT
    ANDFFFFFFFT
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TRUTH TABLE: LOGICALOR(A,B,C)
    AFFFTFTTT
    BFFTFTFTT
    CFTFFTTFT
    ORFTTTTTTT
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TRUTH TABLE: LOGICALXOR(A,B,C)
    AFFFTFTTT
    BFFTFTFTT
    CFTFFTTFT
    XORFTTTFFFF
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TRUTH TABLE: LOGICALNOTAND(A,B,C)
    AFFFTFTTT
    BFFTFTFTT
    CFTFFTTFT
    NOTANDTTTTTTTF
    +

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    TRUTH TABLE: LOGICALNOTOR(A,B,C)
    AFFFTFTTT
    BFFTFTFTT
    CFTFFTTFT
    NOTORTFFFFFFF
    + +
    " +3984;IfcArithmeticOperatorEnum;" + +

    IfcArithmeticOperatorEnum specifies the form of arithmetical operation implied by the relationship.

    +

    Enumeration

    +
      +
    • ADD
    • +
    • DIVIDE
    • +
    • MULTIPLY
    • +
    • SUBTRACT
    • +
    + +
    +HISTORY: New enumeration in IFC2x2. +
    + +

    Use definitions

    +

    There can be only one arithmetic operator for each applied value relationship. This is to enforce arithmetic consistency. Given this consistency, the cardinality of the IfcAppliedValueRelationship.Components attribute is a set of one to many applied values that are components of an applied value.

    + +
    " +4027;IfcTimeSeriesDataTypeEnum;" + +

    IfcTimeSeriesDataTypeEnum describes a type of time series data and is used to determine a value during the time series which is not explicitly specified:

    +
      +
    • CONTINUOUS: The time series data is continuous.
    • +
    • DISCRETE: The time series data is discrete.
    • +
    • DISCRETEBINARY: The time series data is discrete binary.
    • +
    • PIECEWISEBINARY: The time series data is piecewise binary.
    • +
    • PIECEWISECONSTANT: The time series data is piecewise constant.
    • +
    • PIECEWISECONTINUOUS: The time series data is piecewise continuous.
    • +
    • NOTDEFINED: The time series data is not defined.
    • +
    + +
    +HISTORY: New enumeration in IFC2x2. +
    + +
    " +4035;IfcDataOriginEnum;" + +

    IfcDataOriginEnum identifies the origin of time data:

    +
      +
    • MEASURED: The origin of the time data is a measurement device.
    • +
    • PREDICTED: The time data are a prediction.
    • +
    • SIMULATED: The origin of the time data is a simulation.
    • +
    • NOTDEFINED: The origin of the time data is undefined.
    • +
    +
    +HISTORY: New enumeration in IFC 2x2.
    +
    + +
    " +4075;IfcTaskDurationEnum;" +

    IfcTaskDurationEnum identifies how a time duration is measured:

    +
      +
    • ELAPSEDTIME: The time duration is based on elapsed time (24 hours per day, independent of calendar).
    • +
    • WORKTIME: The time duration is based on work time (calendar-dependent).
    • +
    • NOTDEFINED: The time duration is undefined.
    • +
    +
    HISTORY: New enumeration in IFC2x4.
    +
    " +4113;IfcRecurrenceTypeEnum;" +

    + IfcRecurrenceTypeEnum enumerates the recurring pattern type. The following + combinations are valid: +

    +
      +
    • DAILY: Interval, Occurrences
    • +
    +
      +
    • WEEKLY: WeekdayComponent, Interval, Occurrences
    • +
    +
      +
    • MONTHLY_BY_DAY_OF_MONTH: DayComponent, Interval, Occurrences
    • +
    +
      +
    • MONTHLY_BY_POSITION: WeekdayComponent, Position, Interval, Occurrences
    • +
    +
      +
    • BY_DAY_COUNT: Interval, Occurrences
    • +
    +
      +
    • BY_WEEKDAY_COUNT: WeekdayComponent, Interval, Occurrences
    • +
    +
      +
    • YEARLY_BY_DAY_OF_MONTH: DayComponent, MonthComponent, Interval, Occurrences
    • +
    +
      +
    • YEARLY_BY_POSITION: WeekdayComponent, MonthComponent, Position, Interval, Occurrences
    • +
    +
    + HISTORY: New enumeration in IFC + Release 2x4. +
    +
    " +4230;IfcLayerSetDirectionEnum;" + +

    IfcLayerSetDirectionEnum provides identification of the axis of element geometry, denoting the layer set thickness direction, or direction of layer offsets.

    + +

    ENUMERATION

    +
      +
    • AXIS1: Usually x-axis.
    • +
    • AXIS2: Usually y-axis.
    • +
    • AXIS3: Usually z-axis.
    • +
    + +
    +HISTORY: New Type in IFC2x. +
    + +
    " +4300;IfcDirectionSenseEnum;" + +

    IfcDirectionSenseEnum is an enumeration denoting whether sense of direction is positive or negative along the given axis.

    + +

    ENUMERATION

    +
      +
    • POSITIVE: Direction defined to be positive.
    • +
    • NEGATIVE: Direction defined to be negative.
    • +
    + +
    +HISTORY New Type in IFC2x. +
    + +
    " +4571;IfcSIPrefix;" + +

    Definition from ISO/CD 10303-41:1992: An SI prefix is the name of a prefix that may be associated +with an SI unit. The definitions of SI prefixes are specified in ISO 1000 (clause 3).

    + +
    +NOTE The prefix defines multiples and submultiples of the SI units. +
    + +
    +NOTE Corresponding ISO 10303 name: SI_prefix, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
    + + +

    ENUMERATION

    +
      +
    • EXA: 10^18.
    • +
    • PETA: 10^15.
    • +
    • TERA: 10^12.
    • +
    • GIGA: 10^9.
    • +
    • MEGA: 10^6.
    • +
    • KILO: 10^3.
    • +
    • HECTO: 10^2.
    • +
    • DECA: 10.
    • +
    • DECI: 10^-1.
    • +
    • CENTI: 10^-2.
    • +
    • MILLI: 10^-3.
    • +
    • MICRO: 10^-6.
    • +
    • NANO: 10^-9.
    • +
    • PICO: 10^-12.
    • +
    • FEMTO: 10^-15.
    • +
    • ATTO: 10^-18.
    • +
    + +
    + HISTORY New entity in IFC Release 1.5.1. +
    + +
    " +4588;IfcSIUnitName;" + +

    Definition from ISO/CD 10303-41:1992: An SI unit name is the name of an SI unit. The definitions of the +names of SI units are specified in ISO 1000 (clause 2).

    + +
    +NOTE Corresponding STEP name: SI_unit_name, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
    + +

    ENUMERATION

    +
      +
    • AMPERE: Unit for electric current.
    • +
    • BECQUEREL: Unit for radioactivity.
    • +
    • CANDELA: Unit for luminousintensity.
    • +
    • COULOMB: Unit for electric charge.
    • +
    • CUBIC_METRE: Unit for volume.
    • +
    • DEGREE_CELSIUS: Unit for thermodynamic temperature.
    • +
    • FARAD: Unit for electric capacitance.
    • +
    • GRAM: Unit for mass.
    • +
    • GRAY: Unit for absorbed radioactive dose.
    • +
    • HENRY: Unit for inductance.
    • +
    • HERTZ: Unit for frequency.
    • +
    • JOULE: Unit for energy.
    • +
    • KELVIN: Unit for thermodynamic temperature.
    • +
    • LUMEN: Unit for luminous flux.
    • +
    • LUX: Unit for illuminance.
    • +
    • METRE: Unit for length.
    • +
    • MOLE: Unit for amount of substance.
    • +
    • NEWTON: Unit for force.
    • +
    • OHM: Unit for electric resistance.
    • +
    • PASCAL: Unit for pressure.
    • +
    • RADIAN: Unit for plane angle.
    • +
    • SECOND: Unit for time.
    • +
    • SIEMENS: Unit for electric conductance.
    • +
    • SIEVERT: Unit for radioactive dose equivalent.
    • +
    • SQUARE_METRE: Unit for area.
    • +
    • STERADIAN: Unit for solid angle.
    • +
    • TESLA: Unit for magnetic flux density.
    • +
    • VOLT: Unit for electric voltage.
    • +
    • WATT: Unit for power.
    • +
    • WEBER: Unit for magnetic flux.
    • +
    + +
    +HISTORY New entity in IFC Release 1.5.1. +
    + +
    " +4627;IfcUnitEnum;" + +

    IfcUnitEnum is an enumeration type for allowed unit types of IfcNamedUnit.

    + +

    ENUMERATION

    +
      +
    • ABSORBEDDOSEUNIT
    • +
    • AMOUNTOFSUBSTANCEUNIT
    • +
    • AREAUNIT
    • +
    • DOSEEQUIVALENTUNIT
    • +
    • ELECTRICCAPACITANCEUNIT
    • +
    • ELECTRICCHARGEUNIT
    • +
    • ELECTRICCONDUCTANCEUNIT
    • +
    • ELECTRICCURRENTUNIT
    • +
    • ELECTRICRESISTANCEUNIT
    • +
    • ELECTRICVOLTAGEUNIT
    • +
    • ENERGYUNIT
    • +
    • FORCEUNIT
    • +
    • FREQUENCYUNIT
    • +
    • ILLUMINANCEUNIT
    • +
    • INDUCTANCEUNIT
    • +
    • LENGTHUNIT
    • +
    • LUMINOUSFLUXUNIT
    • +
    • LUMINOUSINTENSITYUNIT
    • +
    • MAGNETICFLUXDENSITYUNIT
    • +
    • MAGNETICFLUXUNIT
    • +
    • MASSUNIT
    • +
    • PLANEANGLEUNIT
    • +
    • POWERUNIT
    • +
    • PRESSUREUNIT
    • +
    • RADIOACTIVITYUNIT
    • +
    • SOLIDANGLEUNIT
    • +
    • THERMODYNAMICTEMPERATUREUNIT
    • +
    • TIMEUNIT
    • +
    • VOLUMEUNIT
    • +
    • USERDEFINED: User defined unit type. The type of unit is only implied by its name or the usage context.
    • +
    + +
    +HISTORY New type in IFC Release 1.5.1. +
    + +
    " +4658;IfcDerivedUnitEnum;" + +

    IfcDerivedUnitEnum is an enumeration type for allowed types of derived units.

    +

    ENUMERATION

    +
      +
    • ACCELERATIONUNIT
    • +
    • ANGULARVELOCITYUNIT
    • +
    • COMPOUNDPLANEANGLEUNIT
    • +
    • DYNAMICVISCOSITYUNIT
    • +
    • HEATFLUXDENSITYUNIT
    • +
    • INTEGERCOUNTRATEUNIT
    • +
    • ISOTHERMALMOISTURECAPACITYUNIT
    • +
    • KINEMATICVISCOSITYUNIT
    • +
    • LINEARFORCEUNIT
    • +
    • LINEARMOMENTUNIT
    • +
    • LINEARSTIFFNESSUNIT
    • +
    • LINEARVELOCITYUNIT
    • +
    • MASSDENSITYUNIT
    • +
    • MASSFLOWRATEUNIT
    • +
    • MODULUSOFELASTICITYUNIT
    • +
    • MODULUSOFSUBGRADEREACTIONUNIT
    • +
    • MOISTUREDIFFUSIVITYUNIT
    • +
    • MOLECULARWEIGHTUNIT
    • +
    • MOMENTORINERTIAUNIT
    • +
    • PLANARFORCEUNIT
    • +
    • ROTATIONALFREQUENCYUNIT
    • +
    • ROTATIONALSTIFFNESSUNIT
    • +
    • SHEARMODULUSUNIT
    • +
    • SPECIFICHEATCAPACITYUNIT
    • +
    • THERMALADMITTANCEUNIT
    • +
    • THERMALCONDUCTANCEUNIT
    • +
    • THERMALRESISTANCEUNIT
    • +
    • THERMALTRANSMITTANCEUNIT
    • +
    • TORQUEUNIT
    • +
    • VAPORPERMEABILITYUNIT
    • +
    • VOLUMETRICFLOWRATEUNIT
    • +
    • CURVATUREUNIT
    • +
    • HEATINGVALUEUNIT
    • +
    • IONCONCENTRATIONUNIT
    • +
    • LUMINOUSINTENSITYDISTRIBUTIONUNIT
    • +
    • MASSPERLENGTHUNIT
    • +
    • MODULUSOFLINEARSUBGRADEREACTIONUNIT
    • +
    • MODULUSOFROTATIONALSUBGRADEREACTIONUNIT
    • +
    • PHUNIT
    • +
    • ROTATIONALMASSUNIT
    • +
    • SECTIONAREAINTEGRALUNIT
    • +
    • SECTIONMODULUSUNIT
    • +
    • SOUNDPOWERUNIT
    • +
    • SOUNDPRESSUREUNIT
    • +
    • TEMPERATUREGRADIENTUNIT
    • +
    • TEMPERATURERATEOFCHANGE
    • +
    • THERMALEXPANSIONCOEFFICIENTUNIT
    • +
    • WARPINGCONSTANTUNIT
    • +
    • WARPINGMOMENTUNIT
    • +
    • USERDEFINED: User defined derived unit.
    • +
    + +
    +HISTORY: New type in IFC Release 2.0. +
    + +
    +IFC 2x4 change: added TEMPERATURERATEOFCHANGE. +
    + +
    " +4823;IfcNullStyle;" + +

    Definition from ISO/CD 10303-46:1992: The null style type specifies, that a representation item is not styled.

    + +
    +NOTE  Corresponding ISO 10303 name: null_style. Please refer to ISO/IS 10303-46:1994 for the final +definition of the formal standard. +
    + +
    +HISTORY  New enumeration in IFC2x2. +
    + +
    +IFC2x4 CHANGE  The enumeration is deprecated. +
    + +
    " +4837;IfcSurfaceSide;" + +

    IfcSurfaceSide is a denotion of whether negative, positive or both sides of a surface are being referenced.

    + +

    ENUMERATION Definition from ISO/CD 10303-46:1992:

    +
      +
    • POSITIVE: The side of a surface which is in the same direction as the surface normal derived from the mathematical definition.
    • +
    • NEGATIVE: The side of a surface which is in the opposite direction than the surface normal derived from the mathematical definition.
    • +
    • BOTH: Both, positive and negative side.
    • +
    + +
    +NOTE Corresponding ISO 10303 type: surface_side. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY: New Enumeration in IFC 2.0 +
    + +
    " +4868;IfcReflectanceMethodEnum;" + +

    The IfcReflectanceMethodEnum defines the range of different reflectance methods available.

    + +
    +HISTORY: New type in IFC 2x2. +
    + +

    Enumeration

    +
      +
    • BLINN: A reflectance model providing a smooth, slightly shiny appearance.
    • +
    • FLAT: A reflectance model providing a constant colour. This model ignores the effect of all light sources.
    • +
    • GLASS: A reflectance model that supports an approximation of glass-like materials that have both reflective and transmissive properties.
    • +
    • MATT: A reflectance model providing a dull matte appearance.
    • +
    • METAL: A reflectance model providing a specular metallic appearance.
    • +
    • MIRROR: A reflectance model that supports secondary mirrored views through ray tracing.
    • +
    • PHONG: A reflectance model conforming with the Phong model in which reflections are greatest in the `mirror' direction of a surface opposite the viewing direction with respect to the surface normal.
    • +
    • PLASTIC: A reflectance model providing a specular effect which is similar to the Phong model.
    • +
    • STRAUSS: A reflectance model for metallic and non-metallic appearance based on a limited set of control parameter.
    • +
    • NOTDEFINED
    • +
    + +
    " +4975;IfcTextPath;" + +

    The text path determines the direction of the text characters in respect to each other.

    + +
    +NOTE: The IfcTextPath is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
    + +
    +NOTE Corresponding ISO 10303 name:text_path . Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New entity in IFC2x2. +
    + +
    " +5012;IfcLightEmissionSourceEnum;" + +

    IfcLightEmissionSourceEnum defines the range of different types of light emitter available.

    + +
    +HISTORY: New type in IFC2x2. +
    + +

    Enumeration

    +
      +
    • COMPACTFLUORESCENT
    • +
    • FLUORESCENT
    • +
    • HIGHPRESSUREMERCURY
    • +
    • HIGHPRESSURESODIUM
    • +
    • LIGHTEMITTINGDIODE
    • +
    • LOWPRESSURESODIUM
    • +
    • LOWVOLTAGEHALOGEN
    • +
    • MAINVOLTAGEHALOGEN
    • +
    • METALHALIDE
    • +
    • TUNGSTENFILAMENT
    • +
    • NOTDEFINED
    • +
    + +
    " +5030;IfcLightDistributionCurveEnum;" + +

    There are three kinds of light distribution curves, according to Standard CEN TC 169, prEN 13032-1, CIE 121:

    + +
      +
    • TYPE_A: Type A is basically not used. For completeness the Type A Photometry equals the Type B rotated 90° around the Z-Axis counter clockwise.
    • +
    • TYPE_B: Type B is sometimes used for floodlights. The B-Plane System has a horizontal axis. B-Angles are valid from -180° to +180° with B 0° at the bottom and B180°/B-180° at the top, β-Angles are valid from -90° to +90°. (See Figure 302.)
    • +
    • TYPE_C: Type C is the recommended standard system. The C-Plane system equals a globe with a vertical axis. C-Angles are valid from 0° to 360°, γ-Angles are valid from 0° (south pole) to 180° (north pole). (See Figure 302.)
    • +
    + + + +
    + + + + + + + + + +
    B-Type SystemC-Type System
    +

    Figure 302 — Light distribution curves

    + +
    +HISTORY  This is a new enumeration in IFC2x2. +
    + +
    " +5109;IfcProfileTypeEnum;" + +

    The enumeration defines whether the definition of a profile shape shall be geometrically resolved into a curve or into a surface.

    + +
    +HISTORY: New type in IFC 1.5. +
    + +

    Enumeration values:

    +
      +
    • CURVE: The resulting geometric item is of type curve and closed (with the only exception of the curve created by the IfcArbitraryOpenProfileDef which resolves into an open curve). The resulting geometry after applying a sweeping operation is a swept surface. This can be used to define shapes with thin sheets, such as ducts, where the thickness is not appropriate for geometric representation.
    • +
    • AREA: The resulting geometric item is of type surface. The resulting geometry after applying a sweeping operation is a swept solid with defined volume.
    • +
    + +
    " +5214;IfcReinforcingBarSurfaceEnum;" +

    Definition from IAI: Enumeration indicating whether the bar has a + plain or textured (ribbed) surface.

    +
    +

    HISTORY New type in IFC Release 2x2 +

    +

    ENUMERATION

    +
      +
    • PLAIN The reinforcing bar surface is plain.
    • +
    • TEXTURED The reinforcing bar surface is textured (ribbed). +
    • +
    +
    " +5221;IfcSectionTypeEnum;" +

    Definition from IAI: An enumeration indicating whether a + specific piece of a cross section is uniform or tapered in longitudinal + direction.

    +
    HISTORY New type in IFC + Release 2x2
    +

    ENUMERATION

    +
      +
    • UNIFORM The section is uniform in longitudinal direction. +
    • +
    • TAPERED The section is tapered in longitudinal direction. +
    • +
    +
    " +5231;IfcReinforcingBarRoleEnum;" +

    Definition from IAI: Enumeration defining standard types for the + role, purpose or usage of the bar, i.e. the kind of loads and stresses they are + intended to carry.

    +
    +

    HISTORY New type in IFC Release 2x2.
    + Item ANCHORING (documented since IFC 2x2) added to the EXPRESS definition in IFC 2x4. +

    +

    ENUMERATION

    +
      +
    • MAIN The reinforcing bar is a main bar.
    • +
    • SHEAR The reinforcing bar is a shear bar.
    • +
    • LIGATURE The reinforcing bar is a ligature (link, stirrup).
    • +
    • STUD The reinforcing bar is a stud.
    • +
    • PUNCHING Punching reinforcement.
    • +
    • EDGE Edge reinforcement.
    • +
    • RING Ring reinforcement.
    • +
    • ANCHORING Anchoring reinforcement.
    • +
    • USERDEFINED The type of reinforcement is user defined.
    • +
    • NOTDEFINED The type of reinforcement is not defined.
    • +
    +
    " +5263;IfcStateEnum;" + +

    The IfcStateEnum enumeration identifies the state or accessibility of the object (for example, read/write, locked).

    + +

    Valid enumerations are:

    +
      +
    • READWRITE: Object is in a Read-Write state. It may be modified by an application.
    • +
    • READONLY: Object is in a Read-Only state. It may be viewed but not modified by an application.
    • +
    • LOCKED: Object is in a Locked state. It may not be accessed by an application.
    • +
    • READWRITELOCKED: Object is in a Read-Write-Locked state. It may not be accessed by an application.
    • +
    • READONLYLOCKED: Object is in a Read-Only-Locked state. It may not be accessed by an application.
    • +
    + +
    +HISTORY  New enumeration in IFC R2.0. +
    + +
    +IFC2x3 CHANGE  This concept was initially introduced in IFC 2.0 as IfcModifiedFlag of type BINARY(3) FIXED and has been modified in R2x to an enumeration. It was initially introduced as a first step towards providing facilities for partial model exchange from a server as requested by the IFC implementers. It is intended for use primarily by a model server so that an application can identify the state of the object. +
    + +
    " +5269;IfcChangeActionEnum;" + +

    IfcChangeActionEnum identifies the type of change that might have occurred to the object during the last session (for example, added, modified, deleted). This information is required in a partial model exchange scenario so that an application or model server will know how an object might have been affected by the previous application. Valid enumerations are:

    + +
      +
    • NOCHANGE: Object has not been modified.
    • +
    • MODIFIED: A modification to the object has been made by the user and application defined by the LastModifyingUser and LastModifyingApplication respectively.
    • +
    • ADDED: The object has been created by the user and application defined by the OwningUser and OwningApplication respectively.
    • +
    • DELETED: The object has been deleted by the user and application defined by the LastModifyingUser and LastModifyingApplication respectively.
    • +
    • NOTDEFINED: The change action is not known or has not been defined.
    • +
    + +

    Consider Application A will create an IFC dataset that it wants to publish to others for modification and have the ability to subsequently merge these changes back into the original model. Before publication, it may want to set the IfcChangeActionEnum to NOCHANGE to establish a baseline so that other application changes can be easily identified. Application B then receives this IFC dataset and adds a new object and sets IfcChangeActionEnum to ADDED with Application B defined as the OwningApplication. Application B then modifies an existing object and (re)defines the LastModifiedDate to the time of the modification, LastModifyingUser to the IfcPersonAndOrganization making the change, and sets the LastModifyingApplication to Application B. When Application A receives this modified dataset, it can determine which objects have been added and modified by Application B and either merge or reject these changes as necessary. Consequently, the intent is that an application only modifies the value of IfcChangeActionEnum when it does something to the object, with the further intent that a model server is responsible for clearing the IfcChangeActionEnum back to NOCHANGE when it is ready to be republished.

    + +
    +HISTORY: New enumeration in IFC R2.0. Modified in IFC2x4. +
    + +
    " +5452;IfcBooleanOperator;" +

    Definition from ISO/CD 10303-42:1992: This type defines the three Boolean operators used in the definition of CSG solids.

    + +
      +
    • UNION: The operation of constructing the regularized set theoretic union of the volumes defined by two solids.
    • +
    • INTERSECTION: The operation of constructing the regularised set theoretic intersection of the volumes defined by two solids.
    • +
    • DIFFERENCE: The operation of constructing the regularized set theoretic intersection of the volumes defined by two solids.
    • +
    + +
    +NOTE Corresponding STEP type: boolean_operator, please refer to ISO/IS 10303-42:1994, p.167 for the final definition of the formal standard. +
    +
    +HISTORY New Type in IFC Release 1.5.1. +
    + +
    " +5699;IfcKnotType; +5704;IfcBSplineSurfaceForm; +5727;IfcTransitionCode;" + +

    Definition from ISO/CD 10303-42:1992: This type conveys the continuity properties of a composite curve or surface. The continuity referred to is geometric, not parametric continuity. For example, in ContSameGradient the tangent vectors of successive segments will have the same direction, but may have different magnitude.

    + +
    +NOTE  Corresponding ISO 10303 type: transition_code, please refer to ISO/IS 10303-42:1994, p. 14 for the final definition of the formal standard. +
    + +
    +HISTORY  New Type in IFC Release 1.0 +
    + +

    Figure 273 (quoted from ISO/CD 10303-42:1992, p.55) illustrates transition types. + + + +

    Figure 273 — Transition code

    + +

    ENUMERATION

    +
      +
    • DISCONTINUOUS: The segments do not join. This is permitted only at the boundary of the curve or surface to indicate that it is not closed.
    • +
    • CONTINUOUS: The segments join but no condition on their tangents is implied.
    • +
    • CONTSAMEGRADIENT: The segments join and their tangent vectors or tangent planes are parallel and have the same direction at the joint: equality of derivatives is not required.
    • +
    • CONTSAMEGRADIENTSAMECURVATURE: For a curve, the segments join, their tangent vectors are parallel and in the same direction and their curvatures are equal at the joint: equality of derivatives is not required. For a surface this implies that the principle curvatures are the same and the principle directions are coincident along the common boundary.
    • +
    + +
    " +5747;IfcTrimmingPreference;" + +

    Definition from ISO/CD 10303-42:1992: This type is used to describe the preferred way of trimming a parametric curve where the trimming is multiply defined.

    + +
    +NOTE Corresponding ISO 10303 type: trimming_preference, please refer to ISO/IS 10303-42:1994, p. 18 for the final definition of the formal standard. +
    + +
    +HISTORY New Type in IFC Release 1.0 +
    + +

    ENUMERATION

    +
      +
    • CARTESIAN: Indicates that trimming by Cartesian point is preferred.
    • +
    • PARAMETER: Indicates the preference for the parameter value.
    • +
    • UNSPECIFIED: Indicates that no preference is communicated.
    • +
    + +
    " +5774;IfcBSplineCurveForm;" + +

    Definition from ISO/CD 10303-42:1992: This type is used to indicate that the B-spline curve represents a part of a curve of some specific form.

    + +

    Enumeration

    +
      +
    • polyline form: A connected sequence of line segments represented by degree 1 B-spline basis functions.
    • +
    • circular arc: An arc of a circle, or a complete circle represented by a B-spline curve.
    • +
    • elliptic arc: An arc of an ellipse, or a complete ellipse, represented by a B-spline curve.
    • +
    • parabolic arc: An arc of finite length of a parabola represented by a B-spline curve.
    • +
    • hyperbolic arc: An arc of finite length of one branch of a hyperbola represented by a B-spline curve.
    • +
    • unspecified: A B-spline curve for which no particular form is specified.
    • +
    + +
    +NOTE  Corresponding ISO 10303 type: b_spline_curve_form. Please refer to ISO/IS 10303-42:1994, p. 15 for the final definition of the formal standard. +
    + +
    +HISTORY  New type in Release IFC2x2. +
    + +
    " diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocSelect.csv b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocSelect.csv new file mode 100644 index 0000000000000000000000000000000000000000..099cf2ca74330258b49b36236a01f541e0e90120 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/DocSelect.csv @@ -0,0 +1,1015 @@ +27;IfcActorSelect;" + +

    The actor select type allows a person, or an organization, or a person associated with an organization to be referenced.

    + +
    +NOTE Corresponds to the following entity in ISO 10303-41: person_organization_select. +
    + +
    +HISTORY New entity in IFC Release 1.5.1 +
    + +

    SELECT

    +
      +
    • IfcOrganization An organization.
    • +
    • IfcPerson A person.
    • +
    • IfcPersonAndOrganization A person related to an organization.
    • +
    + +
    " +268;IfcBendingParameterSelect;" + +

    Definition from IAI: A select type for selecting between simple measure types for reinforcement bending parameters.

    + +
    HISTORY New type in IFC Release 2x4
    + +
    " +276;IfcTextFontSelect;" + +

    IfcTextFontSelect allows for either a predefined text font, a text font model or an externally defined text font to be used to describe the font of a text literal. The definition of the text font model is based on W3C TR Cascading Style Sheet Version 1, whereas the definition of predefined text font is based on ISO 10303. +

    + +
    +NOTE  IfcTextFontSelect is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. Corresponding ISO 10303 name: font_select. Please refer to ISO/IS 10303-46:1994, p. 133 for the final definition of the formal standard. +
    + +
    +HISTORY  New type in IFC2x2. +
    + +
    +IFC2x3 CHANGE  The select type has been renamed from IfcFontSelect. +
    + +
    " +320;IfcColour;" + +

    Definition from ISO/CD 10303-46:1992: The colour entity defines a basic appearance of elements which shall be visualized in a picture.

    + +
    +NOTE  Corresponding STEP name: colour. It has been made into a SELECT type in IFC to avoid multiple inheritance for pre defined colour. Please refer to ISO/IS 10303-46:1994, p. 138 for the final definition of the formal standard. +
    + +
    +HISTORY  New entity in IFC2x2. +
    + +
    " +391;IfcObjectReferenceSelect;" + +

    IfcObjectReferenceSelect is a select type, that holds a list of resource level entities that can be used as properties within a property set.

    + +
    +HISTORY  New select type in IFC Release 2.0. +
    + +
    " +491;IfcSpaceBoundarySelect;" +

    Definition from IAI: The +IfcSpaceBoundarySelect selects either an internal space +for internal or external space boundaries, or an external spatial +element for external space boundaries at the outer envelop of the +building.

    +SELECT
    +
      +
    • IfcSpace,
    • +
    • IfcExternalSpatialElement
    • +
    +
    HISTORY  New select type +in IFC2x4.
    + +
    " +635;IfcDistributionElementSelect;" +

    Definition from IAI: The +IfcDistributionElementSelect provides the option to either +select a distribution element occurrence, +IfcDistributionElement, or a distribution element type, +IfcDistributionElementType.

    +SELECT
    +
      +
    • IfcDistributionElement,
    • +
    • IfcDistributionElementType
    • +
    +
    HISTORY  New select type +in IFC2x4.
    +
    " +859;IfcProcessSelect;" +

    + IfcProcessSelect provides the option to either + select a process or activity occurrence, IfcProcess, + or a process or activity type, IfcTypeProcess. +

    SELECT
    +
      +
    • + IfcProcess, +
    • +
    • + IfcTypeProcess +
    • +
    + +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +889;IfcProductSelect;" +

    IfcProductSelect provides the option to either select a +product occurrence, IfcProduct, or a product type, +IfcTypeProduct.

    +SELECT
    +
      +
    • IfcProduct,
    • +
    • IfcTypeProduct
    • +
    +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +900;IfcResourceSelect;" +

    IfcResourceSelect provides the option to either select a +resource occurrence, IfcResource, or a resource type, +IfcTypeResource.

    +SELECT
    +
      +
    • IfcResource,
    • +
    • IfcTypeResource
    • +
    + +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +962;IfcDefinitionSelect;" + +

    IfcDefinitionSelect provides the option to either select an object or type object IfcObjectDefinition, or a property set template or property set, IfcPropertyDefinition.

    +SELECT
    +
      +
    • IfcObjectDefinition,
    • +
    • IfcPropertyDefinition
    • +
    + +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +2005;IfcStructuralActivityAssignmentSelect;" +

    Definition from IAI: This type definition shall be used to + distinguish between a reference to an instance either of + IfcStructuralItem or IfcBuildingElement. The + IfcStructuralActivityAssignmentSelect type is referenced by the entity + IfcRelConnectsStructuralActivity which defines the connection between + activities (IfcStructuralActivity) and the loaded element.

    +
    +

    HISTORY: New type in Release IFC2x + Edition 2.

    +
    " +2255;IfcCoordinateReferenceSystemSelect;" + +

    IfcCoordinateReferenceSystemSelect is a select between either the local engineering coordinate system, represented by the IfcGeometricRepresentationContext, or another coordinate reference system, represented by IfcCoordinateReferenceSystem, to be the source of a coordinate operation.

    + +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +2357;IfcWarpingStiffnessSelect;" + +

    Definition from IAI: A measure of warping stiffness. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2360;IfcTranslationalStiffnessSelect;" + +

    Definition from IAI: A measure of linear stiffness. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2363;IfcRotationalStiffnessSelect;" + +

    Definition from IAI: A measure of rotational stiffness. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2373;IfcModulusOfTranslationalSubgradeReactionSelect;" + +

    Definition from IAI: A measure for modulus of translational subgrade reaction which expresses the translational bedding of a structural curve item per length. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2376;IfcModulusOfRotationalSubgradeReactionSelect;" + +

    Definition from IAI: A measure for modulus of rotational subgrade reaction which expresses the rotational bedding of a structural curve item per length. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2383;IfcModulusOfSubgradeReactionSelect;" + +

    Definition from IAI: Bedding measure which expresses the bedding of a structural face item per area. TRUE denotes infinite stiffness (rigidity). FALSE denotes no stiffness (a release). A numeric value denotes finite linear-elastic stiffness.

    + +
    HISTORY: New type in IFC 2x4.
    + +
    " +2473;IfcShell;" + +

    Definition from ISO/CD 10303-42:1992 This type collects together, for reference when constructing more complex models, the subtypes which have the characteristics of a shell. A shell is a connected object of fixed dimensionality d = 0; 1; or 2, typically used to bound a region. The domain of a shell, if present, includes its bounds and 0 £ X < ¥.

    +
      +
    • A shell of dimensionality 0 is represented by a graph consisting of a single vertex. The vertex shall not have any associated edges.
    • +
    • A shell of dimensionality 1 is represented by a connected graph of dimensionality 1.
    • +
    • A shell of dimensionality 2 is a topological entity constructed by joining faces along edges. Its domain, if present, is a connected, orientable 2-manifold with boundary, that is, a connected, oriented, finite, non-self-intersecting surface, which may be closed or open.
    • +
    +

    Shells of dimensionality 0 and 1 are not part of the current IFC release.

    + +
    +NOTE  Corresponding ISO 10303 type: shell. Please refer to ISO/IS 10303-42:1994, p. 127 for the final definition of the formal standard. Only the select items closed_shell (IfcClosedShell) and open_shell (IfcOpenShell) have been incorporated in the current IFC release.
    + +
    +HISTORY  New type in IFC2x. +
    + +
    " +3739;IfcClassificationSelect;" +

    IfcClassificationSelect enables selection of whether a classification reference is to be referenced from an external source, or whether a classification is referenced as such.

    + +
    +NOTE  Generally, it is expected that selection will be by IfcClassificationReference to identify an individual classification notation that classifies an element in the building information model. For example an element, such as IfcTank, might be further classified by assigning an IfcClassificationReference with Identification = ""L6814"" and a ClassificationSource identifying the appropriate version of Uniclass. IfcClassification should only be selected in +circumstances where there could be a need to indicate the classification system that will be used without associating a notation or reference to an individual object. This may occur for higher level objects such as IfcProject, IfcSystem, or similar. For example an IfcStructuralAnalysisModel might be classified to be applicable to a particular version of EuroCode. +
    + +
    +HISTORY  New select type in IFC2x +
    +
    +IFC2x4 CHANGE  Select renamed from IfcClassificationNotationSelect. +
    + +

    Select from:

    +
      +
    • IfcClassification (for referencing a classification system)
    • +
    • IfcClassificationReference (for referencing a classification item (or facet) inside a classification system)
    • +
    + +
    " +3784;IfcClassificationReferenceSelect;" + +

    IfcClassificationReferenceSelect enables selection of whether a classification reference is a subset of another classification reference or is a top level entry of a classification source.

    + +
    +HISTORY: New Select Type in IFC2x +
    + +

    Select From:

    +
      +
    • IfcClassification (for classification information)
    • +
    • IfcClassificationReference (for reference into a classification source)
    • +
    + +
    " +3852;IfcResourceObjectSelect;" + +

    IfcResourceObjectSelect enables selection of resource level objects that are to be related to an resource level relationship object. The use of IfcResourceObjectSelect includes the ability to assign an external reference entity (library, classification, or documentation reference) to entities within the resource level.

    + +
    +HISTORY  New Select type in IFC2x4. +
    + +
    " +3870;IfcLibrarySelect;" + +

    IfcLibrarySelect enables selection of whether library information is to be contained within an IFC model or is to be referenced from an external source.

    + +
    +HISTORY: New Select Type in IFC2x +
    + +

    Select From:

    +
      +
    • IfcLibraryInformation (for library information)
    • +
    • IfcLibraryReference (for reference into a library of information by location)
    • +
    + +

    Generally, it is expected that selection will be IfcLibraryReference and only rarely IfcLibraryInformation. IfcLibraryInformation should only be selected in circumstances where there could be a need to indicate the libraries that will be used without making individual references. This may occur for higher level objects such as a project or building.

    + +
    " +3873;IfcDocumentSelect;" + +

    IfcDocumentSelect enables selection of whether document information is to be contained within an IFC model or is to be referenced from an external source.

    + +
    +HISTORY: New Select Type in IFC 2x +
    + +

    Select From:

    +
      +
    • IfcDocumentInformation (for ""metadata"" of an external document)
    • +
    • IfcDocumentReference (for reference within a document)
    • +
    + +
    " +3914;IfcMetricValueSelect;" + +

    IfcMetricValueSelect is a select type that enables selection of the data type for the value component of an IfcMetric.

    + +
    +HISTORY: New type in IFC Release 2.0 +
    + +

    Select

    +
      +
    • IfcCostValue
    • +
    • IfcDateTime
    • +
    • IfcMeasureWithUnit
    • +
    • IfcTable
    • +
    • IfcText
    • +
    • IfcTimeSeries
    • +
    + +
    " +3969;IfcAppliedValueSelect;" + +

    IfcAppliedValueSelect defines the selection of whether a value (expressed as a ratio) or an amount should be used as the value for an IfcAppliedValue.

    + +

    Select from:

    +
      +
    • IfcMeasureWithUnit
    • +
    • IfcMonetaryMeasure
    • +
    • IfcRatioMeasure
    • +
    + +
    +HISTORY: New SELECT type in IFC 2x2. +
    + +

    Use definitions

    +

    Selecting IfcMeasureWithUnit allows the specification of both the actual figure for the value together with the currency in which the value is represented.

    +

    Selecting IfcMonetaryMeasure allows the specification only of the value, the currency being as set by the global context

    +

    Selecting IfcRatioMeasure assumes that the amount is a percentage or other REAL number. Note that if the amount is normally specified as -20%, then this figure will need to be converted to a multiplier of 0.8

    + +
    " +4072;IfcTimeOrRatioSelect;" + +

    IfcTimeOrRatioSelect allows a value to be selected as being either a ratio or a time measure.

    +
    HISTORY New SELECT in IFC2x4
    + +
    " +4147;IfcPointOrVertexPoint;" + +

    IfcPointOrVertexPoint provides the option to either select a geometric point (IfcPoint and subtypes) within a geometric model, or a vertex with associated point coordinates (IfcVertexPoint) within a topological model.

    +SELECT
    +
      +
    • IfcPoint,
    • +
    • IfcVertexPoint
    • +
    + +
    +HISTORY  New select type in IFC2x Edition 3. +
    + +
    " +4153;IfcCurveOrEdgeCurve;" + +

    IfcCurveOrEdgeCurve provides the option to either select a geometric curve (IfcCurve +and subtypes) within a geometric model, or a curve with associated geometry and coordinates (IfcEdgeCurve) within a topological model.

    +SELECT
    +
      +
    • IfcCurve
    • +
    • IfcEdgeCurve
    • +
    + +
    +HISTORY  New select type in IFC2x Edition 3. +
    + +
    " +4159;IfcSurfaceOrFaceSurface;" +

    IfcSurfaceOrFaceSurface provides the option to either select a geometric surface (IfcSurface +and subtypes) within a geometric model, or a face with associated surface geometry and coordinates (IfcFaceSurface) within a topological model.

    +SELECT
    +
      +
    • IfcSurface
    • +
    • IfcFaceSurface
    • +
    • IfcFaceBasedSurfaceModel (a connected face set, representing a faceted surface as an approximation of a non planar, non rectangular bounded surface)
    • +
    + +
    +HISTORY  New select type in IFC2x3. +
    + +
    " +4166;IfcSolidOrShell;" +

    The IfcSolidOrShell provides the option to either select a geometric volume (IfcSolidModel and subtypes) within a geometric model, or a shell (IfcClosedShell) within a topological model.

    +SELECT
    +
      +
    • IfcSolidModel
    • +
    • IfcClosedShell
    • +
    +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +4194;IfcGridPlacementDirectionSelect;" + +

    IfcGridPlacementDirectionSelect enables the choice of defining a grid placement be either an explicit direction, or by referencing a second grid intersection to provide the direction.

    + +

    SELECT

    +
      +
    • IfcDirection,
    • +
    • IfcVirtualGridIntersection
    • +
    + +
    +HISTORY  New select type in IFC2x4. +
    + +
    " +4306;IfcMaterialSelect;" +

    IfcMaterialSelect provides selection of either a material +definition or a material usage definition that can be assigned to +an element, a resource or another entity within IFC.

    +

    SELECT

    +
      +
    • IfcMaterialDefinition +
        +
      • IfcMaterial
      • +
      • IfcMaterialLayer
      • +
      • IfcMaterialLayerSet
      • +
      • IfcMaterialProfile
      • +
      • IfcMaterialProfileSet
      • +
      • IfcMaterialConstituent
      • +
      • IfcMaterialConstituentSet
      • +
      +
    • +
    • IfcMaterialUsageDefinition +
        +
      • IfcMaterialLayerSetUsage
      • +
      • IfcMaterialProfileSetUsage
      • +
      +
    • +
    • IfcMaterialList +
    • +
    + +
    +HISTORY New select in IFC 1.0 +
    + +
    +IFC2x4 CHANGE The select now includes two new abstract entities IfcMaterialDefinition +and IfcMaterialUsageDefinition with upward compatibility. The use of IfcMaterialList is deprecated from IFC2x4 onwards. +
    + +
    " +4363;IfcUnit;" + +

    Definition from ISO/CD 10303-41:1992: A unit is a physical quantity, with a value of one, which is used as a standard in terms of which other quantities are expressed.

    + +
    +NOTE: Select item IfcMonetaryUnit is an addition to ISO 10303-41. +
    + +
    +NOTE: Corresponding ISO 10303 name: unit, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
    + +

    SELECT

    +
      +
    • IfcNamedUnit: A unit which is identified by a name.
    • +
    • IfcDerivedUnit: A unit which is derived from an expression of units.
    • +
    • IfcMonetaryUnit: A unit for defining currencies.
    • +
    + +
    +HISTORY: New type in IFC Release 1.5.1. +
    + +
    " +4398;IfcValue;" + +

    IfcValue is a select type for selecting between more specialised select types IfcSimpleValue, +IfcMeasureValue and IfcDerivedMeasureValue. + +

    SELECT

    +
      +
    • IfcSimpleValue A select type for basic defined types of simple data type.
    • +
    • IfcMeasureValue A select type for basic measure types of ISO 10303-41.
    • +
    • IfcDerivedMeasureValue A select type for derived measure types.
    • +
    + +
    +HISTORY New type in IFC Release 2x. +
    + +
    " +4402;IfcMeasureValue;" + +

    Definition from ISO/CD 10303-41:1992: A measure value is a value as defined in ISO 31-0 (clause 2).

    + +
    +NOTE IfcMeasureValue is a select data type for most basic measure types coming from ISO 10303-41. Select item IfcNonNegativeLengthMeasure is in addition to ISO 10303-41. +
    + +
    +NOTE Corresponding ISO 10303 name: measure_value, please refer to ISO/IS 10303-41 for the final definition of the formal standard. +
    + +
    +HISTORY New type in IFC Release 1.5.1. +
    + +
    +IFC 2x4 change: added IfcNonNegativeLengthMeasure +
    + +
    " +4432;IfcSimpleValue;" + +

    IfcSimpleValue is a select type for selecting between simple value types.

    + +

    SELECT

    +
      +
    • IfcInteger: Defined type of simple type INTEGER.
    • +
    • IfcReal: Defined type of simple type REAL.
    • +
    • IfcBoolean: Defined type of simple type BOOLEAN.
    • +
    • IfcLogical: Defined type of simple type LOGICAL.
    • +
    • IfcIdentifier: Defined type of simple type STRING for identification purposes.
    • +
    • IfcLabel: Defined type of simple type STRING for naming purposes.
    • +
    • IfcText: Defined type of simple type STRING for descriptive purposes.
    • +
    • IfcDateTime: Defined type of simple type STRING to represent a date and time.
    • +
    • IfcDate: Defined type of simple type STRING to represent a date.
    • +
    • IfcTime: Defined type of simple type STRING to represent a time.
    • +
    • IfcDuration: Defined type of simple type STRING to represent a duration.
    • +
    + +
    +HISTORY New type in IFC Release 2x. +
    + +
    +IFC2x4 CHANGE Items IfcDateTime, IfcDate, IfcTime, IfcDuration added. +
    + +
    " +4446;IfcDerivedMeasureValue;" + +

    IfcDerivedMeasureValue is a select type for selecting between derived measure types.

    + +

    SELECT

    +
      +
    • IfcAbsorbedDoseMeasure
    • +
    • IfcAccelerationMeasure
    • +
    • IfcAngularVelocityMeasure
    • +
    • IfcCompoundPlaneAngleMeasure
    • +
    • IfcDoseEquivalentMeasure
    • +
    • IfcDynamicViscosityMeasure
    • +
    • IfcElectricCapacitanceMeasure
    • +
    • IfcElectricChargeMeasure
    • +
    • IfcElectricConductanceMeasure
    • +
    • IfcElectricResistanceMeasure
    • +
    • IfcElectricVoltageMeasure
    • +
    • IfcEnergyMeasure
    • +
    • IfcForceMeasure
    • +
    • IfcFrequencyMeasure
    • +
    • IfcHeatFluxDensityMeasure
    • +
    • IfcIlluminanceMeasure
    • +
    • IfcInductanceMeasure
    • +
    • IfcIntegerCountRateMeasure
    • +
    • IfcIsothermalMoisturecapacityMeasure
    • +
    • IfcKinematicViscosityMeasure
    • +
    • IfcLinearForceMeasure
    • +
    • IfcLinearMomentMeasure
    • +
    • IfcLinearStiffnessMeasure
    • +
    • IfcLinearVelocityMeasure
    • +
    • IfcLuminousFluxMeasure
    • +
    • IfcMagneticFluxDensityMeasure
    • +
    • IfcMagneticFluxMeasure
    • +
    • IfcMassDensityMeasure
    • +
    • IfcMassFlowRateMeasure
    • +
    • IfcModulusOfElasticityMeasure
    • +
    • IfcModulusOfSubgradeReactionMeasure
    • +
    • IfcMoistureDiffusivityMeasure
    • +
    • IfcMolecularWeightMeasure
    • +
    • IfcMomentOfInertiaMeasure
    • +
    • IfcMonetaryMeasure
    • +
    • IfcPlanarForceMeasure
    • +
    • IfcPowerMeasure
    • +
    • IfcPressureMeasure
    • +
    • IfcRadioActivityMeasure
    • +
    • IfcRotationalFrequencyMeasure
    • +
    • IfcRotationalStiffnessMeasure
    • +
    • IfcShearModulusMeasure
    • +
    • IfcSpecificHeatCapacityMeasure
    • +
    • IfcThermalAdmittanceMeasure
    • +
    • IfcThermalConductivityMeasure
    • +
    • IfcThermalResistanceMeasure
    • +
    • IfcThermalTransmittanceMeasure
    • +
    • IfcTimeStamp
    • +
    • IfcTorqueMeasure
    • +
    • IfcVaporPermeabilityMeasure
    • +
    • IfcVolumetricFlowRateMeasure
    • +
    • IfcCurvatureMeasure
    • +
    • IfcMassPerLengthMeasure
    • +
    • IfcRotationalMassMeasure
    • +
    • IfcSectionalAreaIntegralMeasure
    • +
    • IfcSectionModulusMeasure
    • +
    • IfcTemperatureGradientMeasure
    • +
    • IfcTemperatureRateOfChangeMeasure
    • +
    • IfcWarpingConstantMeasure
    • +
    • IfcWarpingMomentMeasure
    • +
    • IfcThermalExpansionCoefficientMeasure
    • +
    • IfcModulusOfLinearSubgradeReactionMeasure
    • +
    • IfcModulusOfRotationalSubgradeReactionMeasure
    • +
    • IfcLuminousIntensityDistributionMeasure
    • +
    • IfcSoundPowerMeasure
    • +
    • IfcSoundPressureMeasure
    • +
    + +
    +HISTORY New type in IFC Release 2x. +
    + +
    +IFC2x4 change: added IfcTemperatureRateOfChangeMeasure. +
    + +
    " +4744;IfcCharacterStyleSelect;" + +

    The character style select allows for a selection of character styles for text. Currently only text color and background color is selectable.

    + +
    +NOTE  Corresponding ISO 10303 name: character_style_select. Please refer to ISO/IS +10303-46:1994, p. 89 for the final definition of the formal standard. +
    + +
    +HISTORY  New type in IFC2x2. +
    + +
    +IFC2x3 CHANGE  The SELECT item IfcTextStyleForDefinedFont replaces the old IfcColour. +
    + +
    " +4753;IfcTextStyleSelect;" + +

    The text style select allows for the selection of styles to be assigned to an annotated text. The text style determines the text model that affect the visual presentation of characters, spaces, words, and paragraphs. There are two choices:

    +
      +
    • IfcTextStyleWithBoxCharacteristics for definitions from ISO/IS 10303-46:1994 for (old) vector based and monospace text.
    • +
    • IfcTextStyleTextModel for definitions from Cascading +Style Sheets, level 1, W3C Recommendation 17 Dec 1996, revised 11 Jan 1999, CSS1, for all true type text. The use of the CSS1 definitions is the preferred way to represent text styles.
    • +
    + +
    +HISTORY  New type in IFC2x2. +
    + +
    +IFC2x3 CHANGE  The items within the IfcTextStyleSelect have changed to IfcTextStyleWithBoxCharacteristics and IfcTextStyleTextModel. +
    + +
    " +4762;IfcSizeSelect;" + +

    Definition from ISO/CD 10303-46:1992: The size select is a selection of a specific positive length measure.

    + +

    Definition from ISO: The size (or width) measure value is given in the global drawing length units.

    + +
    +NOTE  global units are defined at the single IfcProject instance, given by UnitsInContext:IfcUnitAssignment, the same units are used for the geometric representation items and for the style definitions. +
    + +
    +NOTE  Corresponding ISO 10303 name: size_select. Please refer to ISO/IS 10303-46:1994 for the final +definition of the formal standard. +
    + +
    +HISTORY  New type in IFC2x2. +
    + +
    +IFC2x3 CHANGE  The SELECT item IfcMeasureWithUnit has been removed from the IfcSizeSelect, the IfcRatioMeasure and IfcDescriptiveMeasure has been added. +
    + +
    " +4788;IfcFillStyleSelect;" + +

    Definition from ISO/CD 10303-46:1992: The fill style select is a selection between different fill area styles.

    + +
    +NOTE Corresponding ISO 10303 name: fill_style_select. Please refer to ISO/IS 10303-46:1994 for +the final definition of the formal standard. +
    + +
    +HISTORY New type in IFC2x2. +
    + +
    " +4802;IfcFillAreaStyleTileShapeSelect;" + +

    The fill area style tile shape select is used to make a selection for the style of the fill area style tile.

    + +
    +NOTE: The IfcFillAreaStyleTileShapeSelect is an entity that had been adopted from ISO 10303, Industrial automation systems and integration—Product data representation and exchange, Part 46: Integrated generic resources: Visual presentation. +
    + +
    +NOTE Corresponding ISO 10303 name: fill_area_style_tile_shape_select. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New type in IFC2x2. +
    + +
    " +4811;IfcStyleAssignmentSelect;" + +

    The style assignment select is a selection of two wasy of assigning presentation styles to an IfcStyledItem.

    +
      +
    • by directly assigning presentation styles as subtypes of IfcPresentationStyle
    • +
    • by assigning presentation stypes via an intermediate collection entity IfcPresentationStyleAssignment +
        +
      • NOTE Using IfcPresentationStyleAssignment is deprecated in IFC2x4 onwards
      • +
      +
    • +
    + +
    +NOTE The select type has been introduced to provide an upward compatible improvement for assigning styles to a styled items. +
    + +
    +HISTORY New select type in IFC2x4. +
    + +
    " +4816;IfcPresentationStyleSelect;" + +

    Definition from ISO/CD 10303-46:1992: The presentation style select is a selection of one of many kinds of styles, a different one for each kind of geometric representation item to be styled.

    + +
    +NOTE Corresponding ISO 10303 name: presentation_style_Select. Please refer to ISO/IS +10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New type in IFC2x2. +
    + +
    +IFC2x4 CHANGE The select type has been deprecated. +
    + +
    " +4827;IfcSymbolStyleSelect;" + +

    The symbol style select allows for the selection of styles to be assigned to an annotated symbol.

    + +
    +NOTE: The selection is restricted to colour within the current release of IFC +
    + +
    +NOTE Corresponding ISO 10303 name: symbol_style_select. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New entity in IFC2x2. +
    + +
    " +4841;IfcSurfaceStyleElementSelect;" + +

    Definition from ISO/CD 10303-46:1992: The surface style element select is a selection of the different surface styles to use in the presentation of the side of a surface.

    + +

    The select type only includes the IfcSurfaceStyleRendering (which is the equivalent to surface_style_rendering) from the select type surface_style_element_select. In addition it has the IfcSurfaceStyleLighting, which holds the exact physically based lighting properties for lighting based calculation algorithms (as the opposite to the rendering based calculation), the IfcSurfaceStyleRefraction (for more advanced refraction indices) and IfcSurfaceStyleWithTextures (to allow for image textures applied to surfaces). In addition an IfcExternallyDefinedSurfaceStyle can be selected that points into an external material library.

    + +
    +NOTE The IfcSurfaceLightingProperties are needed for exact lighting calculation, because physically based lighting calculation algorithms need exact physically based parameters. The factors in IfcSurfaceStyleRendering lack the physical base, they are intended for rendering calculations, but a lighting calculation based software cannot use these values. +
    + +
    +NOTE: Corresponding ISO 10303 type: surface_style_element_select. Please refer to ISO/IS 10303-46:1994, p. 85 for the final definition of the formal standard. +
    + +
    +HISTORY: New Select type in IFC2x2. +
    + +
    " +4859;IfcColourOrFactor;" + +

    The IfcColourOrFactor enables the selection of either a RGB colour value or a scalar factor value for the use as values of the reflectance components.

    + +
    +HISTORY: New type in IFC2x2. +
    + +
    " +4862;IfcSpecularHighlightSelect;" + +

    The IfcSpecularHighlightSelect defines the selectable types of value for specular highlight sharpness.

    + +
    +NOTE: The two select types relate to the different ways to specifiy the sharpness (or shininess) of the specular part of the reflectance equation. It relates to the attributes:

    +
      +
    • in ISO10303-46 the attribute specular_exponent is given
    • +
    • in VRML97 the attribute shininess is given
    • +
    +For each surface side style only one of the two methods is needed for calculating the specular part of the equation. +
    + +
    +HISTORY: New type in IFC2x2. +
    + +
    " +4919;IfcCurveFontOrScaledCurveFontSelect;" + +

    Definition from ISO/CD 10303-46:1992: The curve font or scaled curve font select is a selection of either a curve font style select (being either a predefined curve font or an explicitly defined curve font) or a curve style font and scaling.

    + +
    +NOTE Corresponding ISO 10303 name: curve_font_or_scaled_curve_font_select. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New entity in IFC2x2. +
    + +
    " +4922;IfcCurveStyleFontSelect;" + +

    Definition from ISO/CD 10303-46:1992: The curve style font select is a selection of a curve style font or a predefined curve style font.

    + +
    +NOTE Corresponding ISO 10303 name: curve_style_font_select. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New entity in IFC2x2. +
    + +
    " +4936;IfcHatchLineDistanceSelect;" + +

    The IfcHatchLineDistanceSelect is a selection between different ways to determine the distance and potentially start point of hatch lines, either by an offset distance length measure or by a vector.

    + +
    +HISTORY  New type in IFC2x3. +
    + +
    " +4952;IfcDefinedSymbolSelect;" + +

    The defined symbol select is a selection between a predefined symbol and an externally defined symbol.

    + +
    +NOTE Corresponding ISO 10303 name: defined_symbol_select. Please refer to ISO/IS 10303-46:1994 for the final definition of the formal standard. +
    + +
    +HISTORY New type in IFC2x2. +
    + +
    " +5024;IfcLightDistributionDataSourceSelect;" + +

    A goniometric light gets its intensity distribution function (how much light goes in any one direction) from one of two sources: (i) an industry-standard file, (ii) from distribution data passed directly via the IfcLightIntensityDistribution.

    + +

    The light distribution provides the luminous intensity distribution according to some standardized light distribution curves.

    + +

    Select:

    + + + + + + + + + + + + + +
    TypeDefinition
    IfcExternalReferenceLight distribution is represented by a standard photometric data file such as Eulumdat, IES, CIBSE TM14.
    IfcLightIntensityDistributionFor representing a light distribution directly the + following values needs to be given in a table like structure with column and + row headings. These headings should contain the angles (C/γ or B/β ) + and the table body contains the intensity values, (normally normalized to + cd/Klm). The angles can be non- equidistant and the angle steps can be almost + any value in the valid range, so a list of all available angles in both + directions covers all cases.
    + +
    +HISTORY New type in IFC2x2. +
    + +
    " +5052;IfcLayeredItem;" + +

    Definition from ISO/CD 10303-46:1992: The layered things type selects those things, which can be grouped in layers.

    + +

    It is the collection of all those items, that are assigned to a single layer. These items are representation items or complete representations (IfcRepresentationItem, IfcRepresentation). If an IfcRepresentation is referenced, all IfcRepresentationItem within its set of Items are assigned to the same layer.

    + +
    +NOTE: Corresponding ISO 10303 name: layered_item. It was called layered_things in the ISO/CD version and had been renamed to layered_item in the ISO/IS final version. Please refer to ISO/IS 10303-46:1994, p. 13 for the final definition of the formal standard. +
    + +
    +HISTORY: New type in IFC2x2. +
    + +
    " +5382;IfcCsgSelect;" + +

    Definition from ISO/CD 10303-42:1992: This type identifies the types of entity which may be selected as the root of a CSG tree including a single CSG primitive as a special case.

    +

    Definition from IAI: The IfcBooleanResult, and subtypes of IfcCsgPrimitive3D are defined as potential root tree expression (at IfcCsgSolid). A subtype of IfcCsgPrimitive3D marks the special case of a CSG solid solely expressed by a single primitive.

    + +
    +NOTE Corresponding ISO 10303-42 type: csg_select, please refer to ISO/IS 10303-42:1994, p.168 for the final definition of the formal standard. +
    +
    +HISTORY New Type in IFC Release 1.5.1. +
    + +
    " +5438;IfcGeometricSetSelect;" + +

    Definition from ISO/CD 10303-42:1992: This select type identifies the types of entities which can occur in a geometric set.

    + +
    +NOTE: Corresponding ISO 10303 type: geometric_set_select. Please refer to ISO/IS 10303-42:1994, p. 169 for the final definition of the formal standard. +
    + +
    +HISTORY: New type in IFC Release 2x. +
    + +
    " +5456;IfcBooleanOperand;" +

    Definition from ISO/CD 10303-42:1992: This select type identifies + all those types of entities which may participate in a Boolean operation to + form a CSG solid.

    +

    Definition from IAI: CSG primitives are out of scope for the + current IFC Release. Only faceted B-reps, swept area solids and half space + solids are available as Boolean operands. Boolean results themselves can be used + as operands thus enabling nested Boolean operations.

    +
    +

    NOTE Corresponding STEP type: + boolean_operand, please refer to ISO/IS 10303-42:1994, p.167 for the final + definition of the formal standard. In IFC Release 1.5.1 & 2.0 only Boolean + results (IfcBooleanResult), half space solids + (IfcHalfSpaceSolid), faceted B-Rep, extruded solids and revolved solids + (IfcSolidModel) are defined for being valid Boolean operands. +

    +

    HISTORY: New Type in IFC Release 1.5.1 +

    +
    " +5465;IfcAxis2Placement;" + +

    Definition from ISO/CD 10303-42:1992: This select type collects together both versions of the placement as used in two dimensional or in three dimensional Cartesian space. This enables entities requiring this information to reference them without specifying the space dimensionality.

    + +
    +NOTE: Corresponding STEP type: axis2_placement, please refer to ISO/IS 10303-42:1994, p. 19 for the final definition of the formal standard. +
    + +
    +HISTORY: New type in IFC Release 1.5 +
    + +
    " +5744;IfcTrimmingSelect;" + +

    Definition from ISO/CD 10303-42:1992: This select type identifies the two possible ways of trimming a parametric curve; by a Cartesian point on the curve, or by a REAL number defining a parameter value within the parametric range of the curve.

    + +
    +NOTE Corresponding ISO 10303 type: trimming_select, please refer to ISO/IS 10303-42:1994, p. 20 for the final definition of the formal standard. +
    + +
    +HISTORY New Type in IFC Release 1.0 +
    + +
    " +5810;IfcVectorOrDirection;" +

    Definition from ISO/CD 10303-42:1992: This type is used to + identify the types of entity which can participate in vector computations.

    + +
    NOTE Corresponding STEP type: + vector_or_direction, please refer to ISO/IS 10303-42:1994, p. 20 for the final + definition of the formal standard.
    +
    HISTORY New Type in IFC Release + 1.5
    +
    " +5833;IfcCurveOnSurface; diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/README.md b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3c57d4cab5021833cbb348b1abd10c8d8089f8a0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/README.md @@ -0,0 +1,40 @@ +# IfcOpenShell express schema parser and code generator + +This folder contains Python code to generate C++ type information based on an +Express schema. In particular is has only been tested using recent version of +the IFC schema and will most likely fail on any other Express schema. + +The code can be invoked in the following way and results in several code outputs +named according to the schema name in the Express file. A python 3 interpreter +with the `pyparsing` (`pip install pyparsing`) library is required. + +note: +**Keep in mind that Express is not very suitable for this kind of usage. In the end, (as far as I can tell) no tool is able to read your model, because it doesn't understand the schema as it has no notion of the core part vs the addition.** + +## Command line usage for code generation + +The usage for C++ project. +~~~ +# bootstrap.py express.bnf in ifcopenshell-python.ifcopenshell.express. +>>> python3 bootstrap.py express.bnf > express_parser.py +>>> python3 express_parser.py IFC2X3_TC1.exp header implementation schema_class definitions +~~~ + +The usage for python project. +~~~ +# code rule generation +# generating 'ifcopenshell.express.rules.IFC2X3_TC1' in ifcopenshell-python.ifcopenshell.express.rules. +# rule_compiler in ifcopenshell-python.ifcopenshell.express. +>>> python -m rule_compiler IFC2X3_TC1.exp +~~~ + +## Programmatic usage + +~~~py +import ifcopenshell +import ifcopenshell.express +schema = ifcopenshell.express.parse('IFC.exp') +ifcopenshell.register_schema(schema) +f = ifcopenshell.file(schema=schema.schema.name()) +f.createIfcProject(ifcopenshell.guid.new()) +~~~ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..91aa35fd82441d1972b36a1f04d7919243bcedb3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/__init__.py @@ -0,0 +1,43 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import os +import sys +import subprocess +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + import schema_class + +d = os.path.abspath(os.path.dirname(__file__)) +sys.path.append(d) + +exp_parser_fn = os.path.join(d, "express_parser.py") + +if not os.path.exists(exp_parser_fn): + with open(exp_parser_fn, "w") as f: + subprocess.call([sys.executable, "bootstrap.py"], cwd=d, stdout=f) + + +def parse(fn: str) -> schema_class.SchemaClass: + import express_parser + import schema_class + + mapping = express_parser.parse(fn) + return schema_class.SchemaClass(mapping, schema_class.LateBoundSchemaInstantiator).code diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/bootstrap.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/bootstrap.py new file mode 100644 index 0000000000000000000000000000000000000000..9ff87d5ad0f65165e5ba471c15393bf2b2dc8627 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/bootstrap.py @@ -0,0 +1,247 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import os +import sys +import string +import operator +import itertools + +from pyparsing import * + +try: + from functools import reduce +except: + pass + + +class Expression: + def __init__(self, contents): + self.contents = contents[0] + + def __repr__(self): + if self.op is None: + return repr(self.contents) + c = [isinstance(c, str) and c or str(c) for c in self.contents] + if "%s" in self.op: + return self.op % (" ".join(c)) + else: + return "(%s)" % (" %s " % self.op).join(c) + + def __iter__(self): + return self.contents.__iter__() + + +class Union(Expression): + op = "|" + + +class Concat(Expression): + op = "+" + + +class Optional(Expression): + op = "Optional(%s)" + + +class Repeated(Expression): + op = "ZeroOrMore(%s)" + + +class Term(Expression): + op = None + + +class Keyword: + def __init__(self, contents): + self.contents = contents[0] + + def __repr__(self): + return self.contents + + +class Terminal: + def __init__(self, contents): + self.contents = contents[0] + s = self.contents + self.is_keyword = len(s) >= 4 and s[0 :: len(s) - 1] == '""' and all(c in alphanums + "_" for c in s[1:-1]) + + def __repr__(self): + ty = "CaselessKeyword" if self.is_keyword else "CaselessLiteral" + return "%s(%s)" % (ty, self.contents) + + +LPAREN = Suppress("(") +RPAREN = Suppress(")") +LBRACK = Suppress("[") +RBRACK = Suppress("]") +LBRACE = Suppress("{") +RBRACE = Suppress("}") +EQUALS = Suppress("=") +VBAR = Suppress("|") +PERIOD = Suppress(".") +HASH = Suppress("#") + +identifier = Word(alphanums + "_") +keyword = Word(alphanums + "_").setParseAction(Keyword) +expression = Forward() +optional = Group(LBRACK + expression + RBRACK).setParseAction(Optional) +repeated = Group(LBRACE + expression + RBRACE).setParseAction(Repeated) +terminal = quotedString.setParseAction(Terminal) +term = (keyword | terminal | optional | repeated | (LPAREN + expression + RPAREN)).setParseAction(Term) +concat = Group(term + OneOrMore(term)).setParseAction(Concat) +factor = concat | term +union = Group(factor + OneOrMore(VBAR + factor)).setParseAction(Union) +rule = identifier + EQUALS + expression + PERIOD + +expression << (union | factor) + +grammar = OneOrMore(Group(rule)) +grammar.ignore(HASH + restOfLine) + +express = grammar.parseFile(os.path.join(os.path.dirname(__file__), "express.bnf")) + + +def find_bytype(expr, ty, li=None): + if li is None: + li = [] + if isinstance(expr, Term): + expr = expr.contents + if isinstance(expr, ty): + li.append(expr) + return set(li) + elif isinstance(expr, Expression): + for term in expr: + find_bytype(term, ty, li) + return set(li) + + +actions = { + "type_decl": "TypeDeclaration", + "entity_decl": "EntityDeclaration", + "enumeration_type": "EnumerationType", + "aggregation_types": "AggregationType", + "general_aggregation_types": "AggregationType", + "select_type": "SelectType", + "binary_type": "BinaryType", + "subtype_declaration": "SubTypeExpression", + "supertype_constraint": "SuperTypeExpression", + "derive_clause": "AttributeList", + "inverse_clause": "AttributeList", + "inverse_attr": "InverseAttribute", + "bound_spec": "BoundSpecification", + "explicit_attr": "ExplicitAttribute", + "width_spec": "WidthSpec", + "string_type": "StringType", + "named_types": "NamedType", + "simple_types": "SimpleType", + "function_decl": "FunctionDeclaration", + "rule_decl": "RuleDeclaration", +} + +to_emit = set(id for id, expr in express) +emitted = set() +to_combine = set(["simple_id"]) +statements = [] + +terminals = reduce(lambda x, y: x | y, (find_bytype(e, Terminal) for id, e in express)) +keywords = list(filter(operator.attrgetter("is_keyword"), terminals)) +negated_keywords = map(lambda s: "~%s" % s, keywords) +no_action = {"letter", "digit", "digits", "real_literal", "integer_literal", "string_literal", "simple_string_literal", "letter", "not_quote", "not_paren_star_quote_special"} + +while True: + emitted_in_loop = set() + for id, expr in express: + kws = map(repr, find_bytype(expr, Keyword)) + found = [k in emitted for k in kws] + if id in to_emit and all(found): + emitted_in_loop.add(id) + emitted.add(id) + stmt = "(%s)" % expr + if id in to_combine: + stmt = " + ".join(itertools.chain(negated_keywords, ("originalTextFor(Combine%s)" % stmt,))) + if id not in no_action and not isinstance(expr.contents, Keyword) and not id in to_combine: + node_type = "ListNode" if "ZeroOrMore" in stmt else "Node" + action = actions.get(id, 'lambda s, loc, t: %s(s, loc, t, rule="%s")' % (node_type, id)) + stmt = "%s.setParseAction(%s)" % (stmt, action) + statements.append('%s = %s("%s")' % (id, stmt, id)) + to_emit -= emitted_in_loop + if not emitted_in_loop: + break + +for id in to_emit: + statements.append('%s = Forward()("%s")' % (id, id)) + +for id in to_emit: + expr = [e for k, e in express if k == id][0] + stmt = "(%s)" % expr + if id in to_combine: + stmt = "Suppress%s" % stmt + if id not in no_action and not isinstance(expr.contents, Keyword): + children = list(map(operator.attrgetter('contents'), reduce(lambda x, y: x | y, (find_bytype(e, Keyword) for e in [expr])))) + has_duplicates = len(children) > len(set(children)) + node_type = "ListNode" if ("ZeroOrMore" in stmt or has_duplicates) else "Node" + action = ".setParseAction(%s)" % ( + actions[id] if id in actions else 'lambda s, loc, t: %s(s, loc, t, rule="%s")' % (node_type, id) + ) + stmt = "(%s)%s" % (stmt, action) + statements.append("%s << %s" % (id, stmt)) + +if __name__ == "__main__": + print(r""" +# This file is generated by IfcOpenShell ifcexpressparser bootstrap.py + +from __future__ import annotations +import os +import sys +import pickle + +import schema +import mapping + +from pyparsing import * +from nodes import * + +def parse(fn: str) -> mapping.Mapping: + cache_file = fn + ".cache.dat" + if os.path.exists(cache_file) and os.path.getmtime(cache_file) >= os.path.getmtime(fn): + with open(cache_file, "rb") as f: + m = pickle.load(f) + else: + %s + + syntax.ignore("--" + restOfLine) + syntax.ignore(Regex(r"\((?:\*(?:[^*]*\*+)+?\))")) + ast = syntax.parseFile(fn) + s = schema.Schema(ast) + m = mapping.Mapping(s) + + with open(cache_file, "wb") as f: + pickle.dump(m, f, protocol=0) + return m + +if __name__ == "__main__": + m = parse(sys.argv[1]) + import importlib + for output in sys.argv[2:]: + mdl = importlib.import_module(output) + mdl.Generator(m).emit() + sys.stdout.write(m.schema.name) +""" % ("\n ".join(statements)) + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/cat.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/cat.py new file mode 100644 index 0000000000000000000000000000000000000000..d6e7b2c880dbb02172bcbb5a50ce9ed935ef7e6d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/cat.py @@ -0,0 +1,15 @@ +import sys, fileinput + +if sys.platform == "win32" and not hasattr(sys.stdout, 'buffer'): + import os, msvcrt + msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY) + +files = sys.argv[1:] +if files[0] == '-o': + b = open(files[1], 'wb') + files = files[2:] +else: + b = getattr(sys.stdout, 'buffer', sys.stdout) + +for line in fileinput.input(files=files, mode='rb'): + b.write(line) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/codegen.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/codegen.py new file mode 100644 index 0000000000000000000000000000000000000000..fe997091b138b157b587d532bafc2cff3c542625 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/codegen.py @@ -0,0 +1,50 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import itertools +import functools + + +def indent(n, s): + if isinstance(s, str): + strs = [s] + else: + strs = s + splitted = itertools.chain.from_iterable(map(functools.partial(str.split, sep="\n"), map(str, strs))) + return "\n".join(" "*n + l for l in splitted) + + +class Base: + """ + A base class for all code generation classes. Currently only working around + some python 2/3 incompatibilities in terms of unicode file handling. + """ + + def emit(self): + import platform + + if tuple(map(int, platform.python_version_tuple())) < (2, 8): + from io import open as unicode_open + + unicode_type = unicode + else: + unicode_open = open + unicode_type = lambda x, *args, **kwargs: x + f = unicode_open(self.file_name, "w", encoding="utf-8") + f.write(unicode_type(repr(self), encoding="utf-8", errors="ignore")) + f.close() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/definitions.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/definitions.py new file mode 100644 index 0000000000000000000000000000000000000000..66e9542af3778f5da49c9547dc1005b6fa99d53d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/definitions.py @@ -0,0 +1,70 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import operator + +import nodes +import codegen + +from collections import defaultdict + + +class Definitions(codegen.Base): + def __init__(self, mapping): + + schema_name = mapping.schema.name + self.schema_name = schema_name_title = schema_name.capitalize() + + statements = [""] + + def write_entity(schema_name, name, type): + + attribute_names = list(map(lambda t: (t.name, t.optional), type.attributes)) + for attr, is_optional in attribute_names: + statements.append("#define SCHEMA_%(name)s_HAS_%(attr)s" % locals()) + if is_optional: + statements.append("#define SCHEMA_%(name)s_%(attr)s_IS_OPTIONAL" % locals()) + inverse_attribute_names = list(map(operator.attrgetter("name"), type.inverse)) + for attr in inverse_attribute_names: + statements.append("#define SCHEMA_%(name)s_HAS_%(attr)s" % locals()) + + def write(name): + statements.append("#define SCHEMA_HAS_%(name)s" % locals()) + fn = None + if mapping.schema.is_entity(name): + fn = write_entity + + if fn is not None: + decl = mapping.schema[name] + if isinstance(decl, nodes.TypeDeclaration): + decl = decl.type.type + fn(schema_name, name, decl) is not False + + for name in mapping.schema: + write(name) + + self.str = "\n".join(statements) + "\n" + + self.file_name = "%s-definitions.h" % self.schema_name + + def __repr__(self): + return self.str + + +Generator = Definitions diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/documentation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/documentation.py new file mode 100644 index 0000000000000000000000000000000000000000..fc98ccedbe61f2d6ec8e6e3dad62e646a8014e26 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/documentation.py @@ -0,0 +1,88 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +############################################################################### +# # +# This files uses the documentation files from buildingSMART to generate # +# descriptions from EXPRESS names that are suitable for comments in the C++ # +# code. The .csv files used by this file are generated from the MS Office # +# Access database, which in turn has been generated from the IFC baseline # +# documentation by the IFCDOC utility provided by buildingSMART. # +# # +############################################################################### + +import re +import os +import csv + +from schema import OrderedCaseInsensitiveDict + +try: + from html.entities import entitydefs +except: + from htmlentitydefs import entitydefs + +make_absolute = lambda fn: os.path.join(os.path.dirname(os.path.realpath(__file__)), fn) + +name_to_oid = OrderedCaseInsensitiveDict() +oid_to_desc = {} +oid_to_name = {} +oid_to_pid = {} +regices = list( + zip( + [re.compile(s, re.M) for s in [r'<[\w\n=" \-/\.;_\t:%#,\?\(\)]+>', r"(\n[\t ]*){2,}", r"^[\t ]+"]], + ["", "\n\n", " "], + ) +) + +definition_files = ["DocEntity.csv", "DocEnumeration.csv", "DocDefined.csv", "DocSelect.csv"] +definition_files = map(make_absolute, definition_files) +for fn in definition_files: + with open(fn, encoding="utf8", errors="ignore") as f: + for oid, name, desc in csv.reader(f, delimiter=";", quotechar='"'): + name_to_oid[name] = oid + oid_to_name[oid] = name + oid_to_desc[oid] = desc + +with open(make_absolute("DocEntityAttributes.csv")) as f: + for pid, x, oid in csv.reader(f, delimiter=";", quotechar='"'): + oid_to_pid[oid] = pid + +with open(make_absolute("DocAttribute.csv")) as f: + for oid, name, desc in csv.reader(f, delimiter=";", quotechar='"'): + pid = oid_to_pid[oid] + pname = oid_to_name[pid] + name_to_oid[".".join((pname, name))] = oid + oid_to_desc[oid] = desc + + +def description(item): + global name_to_oid, oid_to_desc, oid_to_name, oid_to_pid + oid = name_to_oid.get(item, 0) + desc = oid_to_desc.get(oid, None) + if desc: + for a, b in entitydefs.items(): + desc = desc.replace("&%s;" % a, b) + desc = desc.replace("\r", "") + for r, s in regices: + desc = r.sub(s, desc) + desc = desc.strip() + return desc.split("\n") + else: + return [] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express.bnf b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express.bnf new file mode 100644 index 0000000000000000000000000000000000000000..de40bfaf23f2c61d6ff9221189bc1e7ef3d508e0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express.bnf @@ -0,0 +1,342 @@ +ABS = "abs" . +ABSTRACT = "abstract" . +ACOS = "acos" . +AGGREGATE = "aggregate" . +ALIAS = "alias" . +AND = "and" . +ANDOR = "andor" . +ARRAY = "array" . +AS = "as" . +ASIN = "asin" . +ATAN = "atan" . +BAG = "bag" . +BASED_ON = "based_on" . +BEGIN = "begin" . +BINARY = "binary" . +BLENGTH = "blength" . +BOOLEAN = "boolean" . +BY = "by" . +CASE = "case" . +CONSTANT = "constant" . +CONST_E = "const_e" . +COS = "cos" . +DERIVE = "derive" . +DIV = "div" . +ELSE = "else" . +END = "end" . +END_ALIAS = "end_alias" . +END_CASE = "end_case" . +END_CONSTANT = "end_constant" . +END_ENTITY = "end_entity" . +END_FUNCTION = "end_function" . +END_IF = "end_if" . +END_LOCAL = "end_local" . +END_PROCEDURE = "end_procedure" . +END_REPEAT = "end_repeat" . +END_RULE = "end_rule" . +END_SCHEMA = "end_schema" . +END_SUBTYPE_CONSTRAINT = "end_subtype_constraint" . +END_TYPE = "end_type" . +ENTITY = "entity" . +ENUMERATION = "enumeration" . +ESCAPE = "escape" . +EXISTS = "exists" . +EXTENSIBLE = "extensible" . +EXP = "exp" . +FALSE = "false" . +FIXED = "fixed" . +FOR = "for" . +FORMAT = "format" . +FROM = "from" . +FUNCTION = "function" . +GENERIC = "generic" . +GENERIC_ENTITY = "generic_entity" . +HIBOUND = "hibound" . +HIINDEX = "hiindex" . +IF = "if" . +IN = "in" . +INSERT = "insert" . +INTEGER = "integer" . +INVERSE = "inverse" . +LENGTH = "length" . +LIKE = "like" . +LIST = "list" . +LOBOUND = "lobound" . +LOCAL = "local" . +LOG = "log" . +LOG10 = "log10" . +LOG2 = "log2" . +LOGICAL = "logical" . +LOINDEX = "loindex" . +MOD = "mod" . +NOT = "not" . +NUMBER = "number" . +NVL = "nvl" . +ODD = "odd" . +OF = "of" . +ONEOF = "oneof" . +OPTIONAL = "optional" . +OR = "or" . +OTHERWISE = "otherwise" . +PI = "pi" . +PROCEDURE = "procedure" . +QUERY = "query" . +REAL = "real" . +REFERENCE = "reference" . +REMOVE = "remove" . +RENAMED = "renamed" . +REPEAT = "repeat" . +RETURN = "return" . +ROLESOF = "rolesof" . +RULE = "rule" . +SCHEMA = "schema" . +SELECT = "select" . +SELF = "self" . +SET = "set" . +SIN = "sin" . +SIZEOF = "sizeof" . +SKIP = "skip" . +SQRT = "sqrt" . +STRING = "string" . +SUBTYPE = "subtype" . +SUBTYPE_CONSTRAINT = "subtype_constraint" . +SUPERTYPE = "supertype" . +TAN = "tan" . +THEN = "then" . +TO = "to" . +TOTAL_OVER = "total_over" . +TRUE = "true" . +TYPE = "type" . +TYPEOF = "typeof" . +UNIQUE = "unique" . +UNKNOWN = "unknown" . +UNTIL = "until" . +USE = "use" . +USEDIN = "usedin" . +VALUE = "value" . +VALUE_IN = "value_in" . +VALUE_UNIQUE = "value_unique" . +VAR = "var" . +WHERE = "where" . +WHILE = "while" . +WITH = "with" . +XOR = "xor" . +bit = "0" | "1" . +digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" . +digits = digit { digit } . +encoded_character = octet octet octet octet . +hex_digit = digit | "a" | "b" | "c" | "d" | "e" | "f" . +letter = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" . +lparen_then_not_lparen_star = "(" { "(" } not_lparen_star { not_lparen_star } . +not_lparen_star = not_paren_star | ")" . +not_paren_star = letter | digit | not_paren_star_special . +not_paren_star_quote_special = "!" | "#" | "$" | "%" | "&" | "+" | "," | "-" | "." | "/" | ":" | ";" | "<" | "=" | ">" | "?" | "@" | "[" | "\\" | "]" | "^" | "_" | "{" | "|" | "}" | "~" . +not_paren_star_special = not_paren_star_quote_special | "\"\"" . +not_quote = not_paren_star_quote_special | letter | digit | "(" | ")" | "*" . +not_rparen_star = not_paren_star | "(" . +octet = hex_digit hex_digit . +special = not_paren_star_quote_special | "(" | ")" | "*" | "\"\"" . +not_rparen_star_then_rparen = not_rparen_star { not_rparen_star } ")" { ")" } . +binary_literal = "%" bit { bit } . +encoded_string_literal = "\"" encoded_character { encoded_character } "\"" . +integer_literal = digits . +real_literal = ( digits "." [ digits ] [ "e" [ sign ] digits ] ) | integer_literal . +simple_id = letter { letter | digit | "_" } . +simple_string_literal = "'" { ( "'" "'" ) | not_quote } "'" . +embedded_remark = "(*" [ remark_tag ] { ( not_paren_star { not_paren_star } ) | lparen_then_not_lparen_star | ( "*" { "*" } ) | not_rparen_star_then_rparen | embedded_remark } "*)" . +remark = embedded_remark | tail_remark . +remark_tag = "\"" remark_ref { "." remark_ref } "\"" . +remark_ref = attribute_ref | constant_ref | entity_ref | enumeration_ref | function_ref | parameter_ref | procedure_ref | rule_label_ref | rule_ref | schema_ref | subtype_constraint_ref | type_label_ref | type_ref | variable_ref . +tail_remark = "--" [ remark_tag ] . +attribute_ref = attribute_id . +constant_ref = constant_id . +entity_ref = entity_id . +enumeration_ref = enumeration_id . +function_ref = function_id . +parameter_ref = parameter_id . +procedure_ref = procedure_id . +rule_label_ref = rule_label_id . +rule_ref = rule_id . +schema_ref = schema_id . +subtype_constraint_ref = subtype_constraint_id . +type_label_ref = type_label_id . +type_ref = type_id . +variable_ref = variable_id . +abstract_entity_declaration = ABSTRACT . +abstract_supertype = ABSTRACT SUPERTYPE ";" . +abstract_supertype_declaration = ABSTRACT SUPERTYPE [ subtype_constraint ] . +actual_parameter_list = "(" [ parameter ] { "," parameter } ")" . +add_like_op = "+" | "-" | OR | XOR . +aggregate_initializer = "[" [ element { "," element } ] "]" . +aggregate_source = simple_expression . +aggregate_type = AGGREGATE [ ":" type_label ] OF parameter_type . +aggregation_types = array_type | bag_type | list_type | set_type . +algorithm_head = { declaration } [ constant_decl ] [ local_decl ] . +alias_stmt = ALIAS variable_id FOR general_ref { qualifier } ";" stmt { stmt } END_ALIAS ";" . +array_type = ARRAY bound_spec OF [ OPTIONAL ] [ UNIQUE ] instantiable_type . +assignment_stmt = general_ref { qualifier } ":=" expression ";" . +attribute_decl = redeclared_attribute | attribute_id . +attribute_id = simple_id . +attribute_qualifier = "." attribute_ref . +bag_type = BAG [ bound_spec ] OF instantiable_type . +binary_type = BINARY [ width_spec ] . +boolean_type = BOOLEAN . +bound_1 = numeric_expression . +bound_2 = numeric_expression . +bound_spec = "[" bound_1 ":" bound_2 "]" . +built_in_constant = CONST_E | PI | SELF | "?" . +built_in_function = ABS | ACOS | ASIN | ATAN | BLENGTH | COS | EXISTS | EXP | FORMAT | HIBOUND | HIINDEX | LENGTH | LOBOUND | LOINDEX | LOG | LOG2 | LOG10 | NVL | ODD | ROLESOF | SIN | SIZEOF | SQRT | TAN | TYPEOF | USEDIN | VALUE | VALUE_IN | VALUE_UNIQUE . +built_in_procedure = INSERT | REMOVE . +case_action = case_label { "," case_label } ":" stmt . +case_label = expression . +case_stmt = CASE selector OF { case_action } [ OTHERWISE ":" stmt ] END_CASE ";" . +compound_stmt = BEGIN stmt { stmt } END ";" . +concrete_types = aggregation_types | simple_types | type_ref . +constant_body = constant_id ":" instantiable_type ":=" expression ";" . +constant_decl = CONSTANT constant_body { constant_body } END_CONSTANT ";" . +constant_factor = built_in_constant | constant_ref . +constant_id = simple_id . +constructed_types = enumeration_type | select_type . +declaration = entity_decl | function_decl | procedure_decl | subtype_constraint_decl | type_decl . +derived_attr = attribute_decl ":" parameter_type ":=" expression ";" . +derive_clause = DERIVE derived_attr { derived_attr } . +domain_rule = [ rule_label_id ":" ] expression . +element = expression [ ":" repetition ] . +entity_body = { explicit_attr } [ derive_clause ] [ inverse_clause ] [ unique_clause ] [ where_clause ] . +entity_constructor = entity_ref "(" [ expression { "," expression } ] ")" . +entity_decl = entity_head entity_body END_ENTITY ";" . +entity_head = ENTITY entity_id subsuper ";" . +entity_id = simple_id . +enumeration_extension = BASED_ON type_ref [ WITH enumeration_items ] . +enumeration_id = simple_id . +enumeration_items = "(" enumeration_id { "," enumeration_id } ")" . +enumeration_reference = [ type_ref "." ] enumeration_ref . +enumeration_type = [ EXTENSIBLE ] ENUMERATION [ ( OF enumeration_items ) | enumeration_extension ] . +escape_stmt = ESCAPE ";" . +explicit_attr = attribute_decl { "," attribute_decl } ":" [ OPTIONAL ] parameter_type ";" . +expression = simple_expression [ rel_op_extended simple_expression ] . +factor = simple_factor [ "**" simple_factor ] . +formal_parameter = parameter_id { "," parameter_id } ":" parameter_type . +function_call = ( built_in_function | function_ref ) actual_parameter_list . +function_decl = function_head algorithm_head stmt { stmt } END_FUNCTION ";" . +function_head = FUNCTION function_id [ "(" formal_parameter { ";" formal_parameter } ")" ] ":" parameter_type ";" . +function_id = simple_id . +generalized_types = aggregate_type | general_aggregation_types | generic_entity_type | generic_type . +general_aggregation_types = general_array_type | general_bag_type | general_list_type | general_set_type . +general_array_type = ARRAY [ bound_spec ] OF [ OPTIONAL ] [ UNIQUE ] parameter_type . +general_bag_type = BAG [ bound_spec ] OF parameter_type . +general_list_type = LIST [ bound_spec ] OF [ UNIQUE ] parameter_type . +general_ref = parameter_ref | variable_ref . +general_set_type = SET [ bound_spec ] OF parameter_type . +generic_entity_type = GENERIC_ENTITY [ ":" type_label ] . +generic_type = GENERIC [ ":" type_label ] . +group_qualifier = "\\" entity_ref . +if_stmt = IF logical_expression THEN stmt { stmt } [ ELSE stmt { stmt } ] END_IF ";" . +increment = numeric_expression . +increment_control = variable_id ":=" bound_1 TO bound_2 [ BY increment ] . +index = numeric_expression . +index_1 = index . +index_2 = index . +index_qualifier = "[" index_1 [ ":" index_2 ] "]" . +instantiable_type = concrete_types | entity_ref . +integer_type = INTEGER . +interface_specification = reference_clause | use_clause . +interval = "{" interval_low interval_op interval_item interval_op interval_high "}" . +interval_high = simple_expression . +interval_item = simple_expression . +interval_low = simple_expression . +interval_op = "<=" | "<" . +inverse_attr = attribute_decl ":" [ ( SET | BAG ) [ bound_spec ] OF ] entity_ref FOR [ entity_ref "." ] attribute_ref ";" . +inverse_clause = INVERSE inverse_attr { inverse_attr } . +list_type = LIST [ bound_spec ] OF [ UNIQUE ] instantiable_type . +literal = binary_literal | logical_literal | real_literal | string_literal . +local_decl = LOCAL local_variable { local_variable } END_LOCAL ";" . +local_variable = variable_id { "," variable_id } ":" parameter_type [ ":=" expression ] ";" . +logical_expression = expression . +logical_literal = FALSE | TRUE | UNKNOWN . +logical_type = LOGICAL . +multiplication_like_op = "*" | "/" | DIV | MOD | AND | "||" . +named_types = entity_ref | type_ref . +named_type_or_rename = named_types [ AS ( entity_id | type_id ) ] . +null_stmt = ";" . +number_type = NUMBER . +numeric_expression = simple_expression . +one_of = ONEOF "(" supertype_expression { "," supertype_expression } ")" . +parameter = expression . +parameter_id = simple_id . +parameter_type = generalized_types | simple_types | named_types . +population = entity_ref . +precision_spec = numeric_expression . +primary = literal | ( qualifiable_factor { qualifier } ) . +procedure_call_stmt = ( built_in_procedure | procedure_ref ) actual_parameter_list ";" . +procedure_decl = procedure_head algorithm_head { stmt } END_PROCEDURE ";" . +procedure_head = PROCEDURE procedure_id [ "(" [ VAR ] formal_parameter { ";" [ VAR ] formal_parameter } ")" ] ";" . +procedure_id = simple_id . +qualifiable_factor = function_call | attribute_ref | constant_factor | general_ref | population . +qualified_attribute = SELF group_qualifier attribute_qualifier . +qualifier = attribute_qualifier | group_qualifier | index_qualifier . +query_expression = QUERY "(" variable_id "<*" aggregate_source "|" logical_expression ")" . +real_type = REAL [ "(" precision_spec ")" ] . +redeclared_attribute = qualified_attribute [ RENAMED attribute_id ] . +referenced_attribute = attribute_ref | qualified_attribute . +reference_clause = REFERENCE FROM schema_ref [ "(" resource_or_rename { "," resource_or_rename } ")" ] ";" . +rel_op = "<=" | ">=" | "<>" | "=" | ":<>:" | ":=:" | "<" | ">" . +rel_op_extended = rel_op | IN | LIKE . +rename_id = constant_id | entity_id | function_id | procedure_id | type_id . +repeat_control = [ increment_control ] [ while_control ] [ until_control ] . +repeat_stmt = REPEAT repeat_control ";" stmt { stmt } END_REPEAT ";" . +repetition = numeric_expression . +resource_or_rename = resource_ref [ AS rename_id ] . +resource_ref = constant_ref | entity_ref | function_ref | procedure_ref | type_ref . +return_stmt = RETURN [ "(" expression ")" ] ";" . +rule_decl = rule_head algorithm_head { stmt } where_clause END_RULE ";" . +rule_head = RULE rule_id FOR "(" entity_ref { "," entity_ref } ")" ";" . +rule_id = simple_id . +rule_label_id = simple_id . +schema_body = { interface_specification } [ constant_decl ] { declaration | rule_decl } . +schema_decl = SCHEMA schema_id [ schema_version_id ] ";" schema_body END_SCHEMA ";" . +schema_id = simple_id . +schema_version_id = string_literal . +selector = expression . +select_extension = BASED_ON type_ref [ WITH select_list ] . +select_list = "(" named_types { "," named_types } ")" . +select_type = [ EXTENSIBLE [ GENERIC_ENTITY ] ] SELECT [ select_list | select_extension ] . +set_type = SET [ bound_spec ] OF instantiable_type . +sign = "+" | "-" . +simple_expression = term { add_like_op term } . +simple_factor = aggregate_initializer | interval | query_expression | ( [ unary_op ] ( "(" expression ")" | primary ) ) | entity_constructor | enumeration_reference . +simple_types = binary_type | boolean_type | integer_type | logical_type | number_type | real_type | string_type . +skip_stmt = SKIP ";" . +stmt = alias_stmt | assignment_stmt | case_stmt | compound_stmt | escape_stmt | if_stmt | null_stmt | procedure_call_stmt | repeat_stmt | return_stmt | skip_stmt . +string_literal = simple_string_literal | encoded_string_literal . +string_type = STRING [ width_spec ] . +subsuper = [ supertype_constraint ] [ subtype_declaration ] . +subtype_constraint = OF "(" supertype_expression ")" . +subtype_constraint_body = [ abstract_supertype ] [ total_over ] [ supertype_expression ";" ] . +subtype_constraint_decl = subtype_constraint_head subtype_constraint_body END_SUBTYPE_CONSTRAINT ";" . +subtype_constraint_head = SUBTYPE_CONSTRAINT subtype_constraint_id FOR entity_ref ";" . +subtype_constraint_id = simple_id . +subtype_declaration = SUBTYPE OF "(" entity_ref { "," entity_ref } ")" . +supertype_constraint = abstract_supertype_declaration | abstract_entity_declaration | supertype_rule . +supertype_expression = supertype_factor { ANDOR supertype_factor } . +supertype_factor = supertype_term { AND supertype_term } . +supertype_rule = SUPERTYPE subtype_constraint . +supertype_term = one_of | "(" supertype_expression ")" | entity_ref . +syntax = schema_decl { schema_decl } . +term = factor { multiplication_like_op factor } . +total_over = TOTAL_OVER "(" entity_ref { "," entity_ref } ")" ";" . +type_decl = TYPE type_id "=" underlying_type ";" [ where_clause ] END_TYPE ";" . +type_id = simple_id . +type_label = type_label_id | type_label_ref . +type_label_id = simple_id . +unary_op = "+" | "-" | NOT . +underlying_type = constructed_types | concrete_types . +unique_clause = UNIQUE unique_rule ";" { unique_rule ";" } . +unique_rule = [ rule_label_id ":" ] referenced_attribute { "," referenced_attribute } . +until_control = UNTIL logical_expression . +use_clause = USE FROM schema_ref [ "(" named_type_or_rename { "," named_type_or_rename } ")" ] ";" . +variable_id = simple_id . +where_clause = WHERE domain_rule ";" { domain_rule ";" } . +while_control = WHILE logical_expression . +width = numeric_expression . +width_spec = "(" width ")" [ FIXED ] . \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express_parser.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..8e2de281287bae6674c3af7a84d8d43021d9ab71 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/express_parser.py @@ -0,0 +1,490 @@ + +# This file is generated by IfcOpenShell ifcexpressparser bootstrap.py + +from __future__ import annotations +import os +import sys +import pickle + +import schema +import mapping + +from pyparsing import * +from nodes import * + +def parse(fn: str) -> mapping.Mapping: + cache_file = fn + ".cache.dat" + if os.path.exists(cache_file) and os.path.getmtime(cache_file) >= os.path.getmtime(fn): + with open(cache_file, "rb") as f: + m = pickle.load(f) + else: + ABS = (CaselessKeyword("abs")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ABS"))("ABS") + ABSTRACT = (CaselessKeyword("abstract")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ABSTRACT"))("ABSTRACT") + ACOS = (CaselessKeyword("acos")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ACOS"))("ACOS") + AGGREGATE = (CaselessKeyword("aggregate")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="AGGREGATE"))("AGGREGATE") + ALIAS = (CaselessKeyword("alias")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ALIAS"))("ALIAS") + AND = (CaselessKeyword("and")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="AND"))("AND") + ANDOR = (CaselessKeyword("andor")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ANDOR"))("ANDOR") + ARRAY = (CaselessKeyword("array")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ARRAY"))("ARRAY") + AS = (CaselessKeyword("as")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="AS"))("AS") + ASIN = (CaselessKeyword("asin")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ASIN"))("ASIN") + ATAN = (CaselessKeyword("atan")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ATAN"))("ATAN") + BAG = (CaselessKeyword("bag")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BAG"))("BAG") + BASED_ON = (CaselessKeyword("based_on")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BASED_ON"))("BASED_ON") + BEGIN = (CaselessKeyword("begin")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BEGIN"))("BEGIN") + BINARY = (CaselessKeyword("binary")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BINARY"))("BINARY") + BLENGTH = (CaselessKeyword("blength")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BLENGTH"))("BLENGTH") + BOOLEAN = (CaselessKeyword("boolean")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BOOLEAN"))("BOOLEAN") + BY = (CaselessKeyword("by")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="BY"))("BY") + CASE = (CaselessKeyword("case")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="CASE"))("CASE") + CONSTANT = (CaselessKeyword("constant")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="CONSTANT"))("CONSTANT") + CONST_E = (CaselessKeyword("const_e")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="CONST_E"))("CONST_E") + COS = (CaselessKeyword("cos")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="COS"))("COS") + DERIVE = (CaselessKeyword("derive")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="DERIVE"))("DERIVE") + DIV = (CaselessKeyword("div")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="DIV"))("DIV") + ELSE = (CaselessKeyword("else")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ELSE"))("ELSE") + END = (CaselessKeyword("end")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END"))("END") + END_ALIAS = (CaselessKeyword("end_alias")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_ALIAS"))("END_ALIAS") + END_CASE = (CaselessKeyword("end_case")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_CASE"))("END_CASE") + END_CONSTANT = (CaselessKeyword("end_constant")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_CONSTANT"))("END_CONSTANT") + END_ENTITY = (CaselessKeyword("end_entity")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_ENTITY"))("END_ENTITY") + END_FUNCTION = (CaselessKeyword("end_function")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_FUNCTION"))("END_FUNCTION") + END_IF = (CaselessKeyword("end_if")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_IF"))("END_IF") + END_LOCAL = (CaselessKeyword("end_local")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_LOCAL"))("END_LOCAL") + END_PROCEDURE = (CaselessKeyword("end_procedure")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_PROCEDURE"))("END_PROCEDURE") + END_REPEAT = (CaselessKeyword("end_repeat")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_REPEAT"))("END_REPEAT") + END_RULE = (CaselessKeyword("end_rule")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_RULE"))("END_RULE") + END_SCHEMA = (CaselessKeyword("end_schema")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_SCHEMA"))("END_SCHEMA") + END_SUBTYPE_CONSTRAINT = (CaselessKeyword("end_subtype_constraint")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_SUBTYPE_CONSTRAINT"))("END_SUBTYPE_CONSTRAINT") + END_TYPE = (CaselessKeyword("end_type")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="END_TYPE"))("END_TYPE") + ENTITY = (CaselessKeyword("entity")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ENTITY"))("ENTITY") + ENUMERATION = (CaselessKeyword("enumeration")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ENUMERATION"))("ENUMERATION") + ESCAPE = (CaselessKeyword("escape")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ESCAPE"))("ESCAPE") + EXISTS = (CaselessKeyword("exists")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="EXISTS"))("EXISTS") + EXTENSIBLE = (CaselessKeyword("extensible")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="EXTENSIBLE"))("EXTENSIBLE") + EXP = (CaselessKeyword("exp")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="EXP"))("EXP") + FALSE = (CaselessKeyword("false")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FALSE"))("FALSE") + FIXED = (CaselessKeyword("fixed")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FIXED"))("FIXED") + FOR = (CaselessKeyword("for")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FOR"))("FOR") + FORMAT = (CaselessKeyword("format")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FORMAT"))("FORMAT") + FROM = (CaselessKeyword("from")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FROM"))("FROM") + FUNCTION = (CaselessKeyword("function")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="FUNCTION"))("FUNCTION") + GENERIC = (CaselessKeyword("generic")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="GENERIC"))("GENERIC") + GENERIC_ENTITY = (CaselessKeyword("generic_entity")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="GENERIC_ENTITY"))("GENERIC_ENTITY") + HIBOUND = (CaselessKeyword("hibound")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="HIBOUND"))("HIBOUND") + HIINDEX = (CaselessKeyword("hiindex")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="HIINDEX"))("HIINDEX") + IF = (CaselessKeyword("if")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="IF"))("IF") + IN = (CaselessKeyword("in")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="IN"))("IN") + INSERT = (CaselessKeyword("insert")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="INSERT"))("INSERT") + INTEGER = (CaselessKeyword("integer")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="INTEGER"))("INTEGER") + INVERSE = (CaselessKeyword("inverse")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="INVERSE"))("INVERSE") + LENGTH = (CaselessKeyword("length")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LENGTH"))("LENGTH") + LIKE = (CaselessKeyword("like")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LIKE"))("LIKE") + LIST = (CaselessKeyword("list")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LIST"))("LIST") + LOBOUND = (CaselessKeyword("lobound")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOBOUND"))("LOBOUND") + LOCAL = (CaselessKeyword("local")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOCAL"))("LOCAL") + LOG = (CaselessKeyword("log")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOG"))("LOG") + LOG10 = (CaselessKeyword("log10")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOG10"))("LOG10") + LOG2 = (CaselessKeyword("log2")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOG2"))("LOG2") + LOGICAL = (CaselessKeyword("logical")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOGICAL"))("LOGICAL") + LOINDEX = (CaselessKeyword("loindex")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="LOINDEX"))("LOINDEX") + MOD = (CaselessKeyword("mod")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="MOD"))("MOD") + NOT = (CaselessKeyword("not")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="NOT"))("NOT") + NUMBER = (CaselessKeyword("number")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="NUMBER"))("NUMBER") + NVL = (CaselessKeyword("nvl")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="NVL"))("NVL") + ODD = (CaselessKeyword("odd")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ODD"))("ODD") + OF = (CaselessKeyword("of")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="OF"))("OF") + ONEOF = (CaselessKeyword("oneof")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ONEOF"))("ONEOF") + OPTIONAL = (CaselessKeyword("optional")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="OPTIONAL"))("OPTIONAL") + OR = (CaselessKeyword("or")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="OR"))("OR") + OTHERWISE = (CaselessKeyword("otherwise")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="OTHERWISE"))("OTHERWISE") + PI = (CaselessKeyword("pi")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="PI"))("PI") + PROCEDURE = (CaselessKeyword("procedure")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="PROCEDURE"))("PROCEDURE") + QUERY = (CaselessKeyword("query")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="QUERY"))("QUERY") + REAL = (CaselessKeyword("real")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="REAL"))("REAL") + REFERENCE = (CaselessKeyword("reference")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="REFERENCE"))("REFERENCE") + REMOVE = (CaselessKeyword("remove")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="REMOVE"))("REMOVE") + RENAMED = (CaselessKeyword("renamed")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="RENAMED"))("RENAMED") + REPEAT = (CaselessKeyword("repeat")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="REPEAT"))("REPEAT") + RETURN = (CaselessKeyword("return")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="RETURN"))("RETURN") + ROLESOF = (CaselessKeyword("rolesof")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="ROLESOF"))("ROLESOF") + RULE = (CaselessKeyword("rule")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="RULE"))("RULE") + SCHEMA = (CaselessKeyword("schema")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SCHEMA"))("SCHEMA") + SELECT = (CaselessKeyword("select")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SELECT"))("SELECT") + SELF = (CaselessKeyword("self")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SELF"))("SELF") + SET = (CaselessKeyword("set")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SET"))("SET") + SIN = (CaselessKeyword("sin")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SIN"))("SIN") + SIZEOF = (CaselessKeyword("sizeof")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SIZEOF"))("SIZEOF") + SKIP = (CaselessKeyword("skip")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SKIP"))("SKIP") + SQRT = (CaselessKeyword("sqrt")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SQRT"))("SQRT") + STRING = (CaselessKeyword("string")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="STRING"))("STRING") + SUBTYPE = (CaselessKeyword("subtype")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SUBTYPE"))("SUBTYPE") + SUBTYPE_CONSTRAINT = (CaselessKeyword("subtype_constraint")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SUBTYPE_CONSTRAINT"))("SUBTYPE_CONSTRAINT") + SUPERTYPE = (CaselessKeyword("supertype")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="SUPERTYPE"))("SUPERTYPE") + TAN = (CaselessKeyword("tan")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TAN"))("TAN") + THEN = (CaselessKeyword("then")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="THEN"))("THEN") + TO = (CaselessKeyword("to")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TO"))("TO") + TOTAL_OVER = (CaselessKeyword("total_over")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TOTAL_OVER"))("TOTAL_OVER") + TRUE = (CaselessKeyword("true")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TRUE"))("TRUE") + TYPE = (CaselessKeyword("type")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TYPE"))("TYPE") + TYPEOF = (CaselessKeyword("typeof")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="TYPEOF"))("TYPEOF") + UNIQUE = (CaselessKeyword("unique")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="UNIQUE"))("UNIQUE") + UNKNOWN = (CaselessKeyword("unknown")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="UNKNOWN"))("UNKNOWN") + UNTIL = (CaselessKeyword("until")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="UNTIL"))("UNTIL") + USE = (CaselessKeyword("use")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="USE"))("USE") + USEDIN = (CaselessKeyword("usedin")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="USEDIN"))("USEDIN") + VALUE = (CaselessKeyword("value")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="VALUE"))("VALUE") + VALUE_IN = (CaselessKeyword("value_in")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="VALUE_IN"))("VALUE_IN") + VALUE_UNIQUE = (CaselessKeyword("value_unique")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="VALUE_UNIQUE"))("VALUE_UNIQUE") + VAR = (CaselessKeyword("var")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="VAR"))("VAR") + WHERE = (CaselessKeyword("where")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="WHERE"))("WHERE") + WHILE = (CaselessKeyword("while")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="WHILE"))("WHILE") + WITH = (CaselessKeyword("with")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="WITH"))("WITH") + XOR = (CaselessKeyword("xor")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="XOR"))("XOR") + bit = ((CaselessLiteral("0") | CaselessLiteral("1"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="bit"))("bit") + digit = ((CaselessLiteral("0") | CaselessLiteral("1") | CaselessLiteral("2") | CaselessLiteral("3") | CaselessLiteral("4") | CaselessLiteral("5") | CaselessLiteral("6") | CaselessLiteral("7") | CaselessLiteral("8") | CaselessLiteral("9")))("digit") + digits = ((digit + ZeroOrMore(digit)))("digits") + hex_digit = ((digit | CaselessLiteral("a") | CaselessLiteral("b") | CaselessLiteral("c") | CaselessLiteral("d") | CaselessLiteral("e") | CaselessLiteral("f"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="hex_digit"))("hex_digit") + letter = ((CaselessLiteral("a") | CaselessLiteral("b") | CaselessLiteral("c") | CaselessLiteral("d") | CaselessLiteral("e") | CaselessLiteral("f") | CaselessLiteral("g") | CaselessLiteral("h") | CaselessLiteral("i") | CaselessLiteral("j") | CaselessLiteral("k") | CaselessLiteral("l") | CaselessLiteral("m") | CaselessLiteral("n") | CaselessLiteral("o") | CaselessLiteral("p") | CaselessLiteral("q") | CaselessLiteral("r") | CaselessLiteral("s") | CaselessLiteral("t") | CaselessLiteral("u") | CaselessLiteral("v") | CaselessLiteral("w") | CaselessLiteral("x") | CaselessLiteral("y") | CaselessLiteral("z")))("letter") + not_paren_star_quote_special = ((CaselessLiteral("!") | CaselessLiteral("#") | CaselessLiteral("$") | CaselessLiteral("%") | CaselessLiteral("&") | CaselessLiteral("+") | CaselessLiteral(",") | CaselessLiteral("-") | CaselessLiteral(".") | CaselessLiteral("/") | CaselessLiteral(":") | CaselessLiteral(";") | CaselessLiteral("<") | CaselessLiteral("=") | CaselessLiteral(">") | CaselessLiteral("?") | CaselessLiteral("@") | CaselessLiteral("[") | CaselessLiteral("\\") | CaselessLiteral("]") | CaselessLiteral("^") | CaselessLiteral("_") | CaselessLiteral("{") | CaselessLiteral("|") | CaselessLiteral("}") | CaselessLiteral("~")))("not_paren_star_quote_special") + not_paren_star_special = ((not_paren_star_quote_special | CaselessLiteral("\"\""))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="not_paren_star_special"))("not_paren_star_special") + not_quote = ((not_paren_star_quote_special | letter | digit | CaselessLiteral("(") | CaselessLiteral(")") | CaselessLiteral("*")))("not_quote") + octet = ((hex_digit + hex_digit)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="octet"))("octet") + special = ((not_paren_star_quote_special | CaselessLiteral("(") | CaselessLiteral(")") | CaselessLiteral("*") | CaselessLiteral("\"\""))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="special"))("special") + binary_literal = ((CaselessLiteral("%") + bit + ZeroOrMore(bit))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="binary_literal"))("binary_literal") + integer_literal = (digits)("integer_literal") + simple_id = ~CaselessKeyword("generic") + ~CaselessKeyword("value") + ~CaselessKeyword("case") + ~CaselessKeyword("for") + ~CaselessKeyword("sin") + ~CaselessKeyword("value_unique") + ~CaselessKeyword("extensible") + ~CaselessKeyword("tan") + ~CaselessKeyword("local") + ~CaselessKeyword("string") + ~CaselessKeyword("procedure") + ~CaselessKeyword("derive") + ~CaselessKeyword("end_if") + ~CaselessKeyword("supertype") + ~CaselessKeyword("entity") + ~CaselessKeyword("oneof") + ~CaselessKeyword("constant") + ~CaselessKeyword("end_case") + ~CaselessKeyword("end_alias") + ~CaselessKeyword("unknown") + ~CaselessKeyword("total_over") + ~CaselessKeyword("div") + ~CaselessKeyword("type") + ~CaselessKeyword("true") + ~CaselessKeyword("end_repeat") + ~CaselessKeyword("unique") + ~CaselessKeyword("end_rule") + ~CaselessKeyword("number") + ~CaselessKeyword("end_function") + ~CaselessKeyword("where") + ~CaselessKeyword("self") + ~CaselessKeyword("usedin") + ~CaselessKeyword("end_type") + ~CaselessKeyword("logical") + ~CaselessKeyword("generic_entity") + ~CaselessKeyword("end_schema") + ~CaselessKeyword("xor") + ~CaselessKeyword("until") + ~CaselessKeyword("to") + ~CaselessKeyword("in") + ~CaselessKeyword("inverse") + ~CaselessKeyword("enumeration") + ~CaselessKeyword("var") + ~CaselessKeyword("value_in") + ~CaselessKeyword("const_e") + ~CaselessKeyword("use") + ~CaselessKeyword("exists") + ~CaselessKeyword("exp") + ~CaselessKeyword("while") + ~CaselessKeyword("if") + ~CaselessKeyword("fixed") + ~CaselessKeyword("subtype") + ~CaselessKeyword("format") + ~CaselessKeyword("as") + ~CaselessKeyword("and") + ~CaselessKeyword("rule") + ~CaselessKeyword("function") + ~CaselessKeyword("lobound") + ~CaselessKeyword("length") + ~CaselessKeyword("hiindex") + ~CaselessKeyword("log2") + ~CaselessKeyword("reference") + ~CaselessKeyword("skip") + ~CaselessKeyword("with") + ~CaselessKeyword("integer") + ~CaselessKeyword("sqrt") + ~CaselessKeyword("insert") + ~CaselessKeyword("nvl") + ~CaselessKeyword("log") + ~CaselessKeyword("boolean") + ~CaselessKeyword("from") + ~CaselessKeyword("rolesof") + ~CaselessKeyword("hibound") + ~CaselessKeyword("abs") + ~CaselessKeyword("like") + ~CaselessKeyword("pi") + ~CaselessKeyword("alias") + ~CaselessKeyword("not") + ~CaselessKeyword("repeat") + ~CaselessKeyword("based_on") + ~CaselessKeyword("subtype_constraint") + ~CaselessKeyword("asin") + ~CaselessKeyword("optional") + ~CaselessKeyword("list") + ~CaselessKeyword("abstract") + ~CaselessKeyword("mod") + ~CaselessKeyword("false") + ~CaselessKeyword("log10") + ~CaselessKeyword("loindex") + ~CaselessKeyword("aggregate") + ~CaselessKeyword("end_constant") + ~CaselessKeyword("end") + ~CaselessKeyword("sizeof") + ~CaselessKeyword("remove") + ~CaselessKeyword("acos") + ~CaselessKeyword("set") + ~CaselessKeyword("renamed") + ~CaselessKeyword("end_local") + ~CaselessKeyword("of") + ~CaselessKeyword("escape") + ~CaselessKeyword("begin") + ~CaselessKeyword("select") + ~CaselessKeyword("end_procedure") + ~CaselessKeyword("else") + ~CaselessKeyword("end_subtype_constraint") + ~CaselessKeyword("cos") + ~CaselessKeyword("real") + ~CaselessKeyword("query") + ~CaselessKeyword("odd") + ~CaselessKeyword("andor") + ~CaselessKeyword("return") + ~CaselessKeyword("then") + ~CaselessKeyword("end_entity") + ~CaselessKeyword("array") + ~CaselessKeyword("blength") + ~CaselessKeyword("or") + ~CaselessKeyword("typeof") + ~CaselessKeyword("binary") + ~CaselessKeyword("atan") + ~CaselessKeyword("by") + ~CaselessKeyword("otherwise") + ~CaselessKeyword("bag") + ~CaselessKeyword("schema") + originalTextFor(Combine((letter + ZeroOrMore((letter | digit | CaselessLiteral("_"))))))("simple_id") + simple_string_literal = ((CaselessLiteral("'") + ZeroOrMore(((CaselessLiteral("'") + CaselessLiteral("'")) | not_quote)) + CaselessLiteral("'")))("simple_string_literal") + abstract_entity_declaration = (ABSTRACT)("abstract_entity_declaration") + abstract_supertype = ((ABSTRACT + SUPERTYPE + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="abstract_supertype"))("abstract_supertype") + add_like_op = ((CaselessLiteral("+") | CaselessLiteral("-") | OR | XOR)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="add_like_op"))("add_like_op") + attribute_id = (simple_id)("attribute_id") + boolean_type = (BOOLEAN)("boolean_type") + built_in_constant = ((CONST_E | PI | SELF | CaselessLiteral("?"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="built_in_constant"))("built_in_constant") + built_in_function = ((ABS | ACOS | ASIN | ATAN | BLENGTH | COS | EXISTS | EXP | FORMAT | HIBOUND | HIINDEX | LENGTH | LOBOUND | LOINDEX | LOG | LOG2 | LOG10 | NVL | ODD | ROLESOF | SIN | SIZEOF | SQRT | TAN | TYPEOF | USEDIN | VALUE | VALUE_IN | VALUE_UNIQUE)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="built_in_function"))("built_in_function") + built_in_procedure = ((INSERT | REMOVE)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="built_in_procedure"))("built_in_procedure") + constant_id = (simple_id)("constant_id") + entity_id = (simple_id)("entity_id") + enumeration_id = (simple_id)("enumeration_id") + enumeration_items = ((CaselessLiteral("(") + enumeration_id + ZeroOrMore((CaselessLiteral(",") + enumeration_id)) + CaselessLiteral(")"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="enumeration_items"))("enumeration_items") + escape_stmt = ((ESCAPE + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="escape_stmt"))("escape_stmt") + function_id = (simple_id)("function_id") + integer_type = (INTEGER)("integer_type") + interval_op = ((CaselessLiteral("<=") | CaselessLiteral("<"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="interval_op"))("interval_op") + logical_literal = ((FALSE | TRUE | UNKNOWN)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="logical_literal"))("logical_literal") + logical_type = (LOGICAL)("logical_type") + multiplication_like_op = ((CaselessLiteral("*") | CaselessLiteral("/") | DIV | MOD | AND | CaselessLiteral("||"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="multiplication_like_op"))("multiplication_like_op") + null_stmt = (CaselessLiteral(";")).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="null_stmt"))("null_stmt") + number_type = (NUMBER)("number_type") + parameter_id = (simple_id)("parameter_id") + procedure_id = (simple_id)("procedure_id") + rel_op = ((CaselessLiteral("<=") | CaselessLiteral(">=") | CaselessLiteral("<>") | CaselessLiteral("=") | CaselessLiteral(":<>:") | CaselessLiteral(":=:") | CaselessLiteral("<") | CaselessLiteral(">"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="rel_op"))("rel_op") + rel_op_extended = ((rel_op | IN | LIKE)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="rel_op_extended"))("rel_op_extended") + rule_id = (simple_id)("rule_id") + rule_label_id = (simple_id)("rule_label_id") + schema_id = (simple_id)("schema_id") + sign = ((CaselessLiteral("+") | CaselessLiteral("-"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="sign"))("sign") + skip_stmt = ((SKIP + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="skip_stmt"))("skip_stmt") + subtype_constraint_id = (simple_id)("subtype_constraint_id") + type_id = (simple_id)("type_id") + type_label_id = (simple_id)("type_label_id") + unary_op = ((CaselessLiteral("+") | CaselessLiteral("-") | NOT)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="unary_op"))("unary_op") + variable_id = (simple_id)("variable_id") + encoded_character = ((octet + octet + octet + octet)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="encoded_character"))("encoded_character") + not_paren_star = ((letter | digit | not_paren_star_special)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="not_paren_star"))("not_paren_star") + not_rparen_star = ((not_paren_star | CaselessLiteral("("))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="not_rparen_star"))("not_rparen_star") + not_rparen_star_then_rparen = ((not_rparen_star + ZeroOrMore(not_rparen_star) + CaselessLiteral(")") + ZeroOrMore(CaselessLiteral(")")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="not_rparen_star_then_rparen"))("not_rparen_star_then_rparen") + encoded_string_literal = ((CaselessLiteral("\"") + encoded_character + ZeroOrMore(encoded_character) + CaselessLiteral("\""))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="encoded_string_literal"))("encoded_string_literal") + real_literal = (((digits + CaselessLiteral(".") + Optional(digits) + Optional((CaselessLiteral("e") + Optional(sign) + digits))) | integer_literal))("real_literal") + attribute_ref = (attribute_id)("attribute_ref") + constant_ref = (constant_id)("constant_ref") + entity_ref = (entity_id)("entity_ref") + enumeration_ref = (enumeration_id)("enumeration_ref") + function_ref = (function_id)("function_ref") + parameter_ref = (parameter_id)("parameter_ref") + procedure_ref = (procedure_id)("procedure_ref") + rule_label_ref = (rule_label_id)("rule_label_ref") + rule_ref = (rule_id)("rule_ref") + schema_ref = (schema_id)("schema_ref") + subtype_constraint_ref = (subtype_constraint_id)("subtype_constraint_ref") + type_label_ref = (type_label_id)("type_label_ref") + type_ref = (type_id)("type_ref") + variable_ref = (variable_id)("variable_ref") + attribute_qualifier = ((CaselessLiteral(".") + attribute_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="attribute_qualifier"))("attribute_qualifier") + constant_factor = ((built_in_constant | constant_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="constant_factor"))("constant_factor") + enumeration_extension = ((BASED_ON + type_ref + Optional((WITH + enumeration_items)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="enumeration_extension"))("enumeration_extension") + enumeration_reference = ((Optional((type_ref + CaselessLiteral("."))) + enumeration_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="enumeration_reference"))("enumeration_reference") + enumeration_type = ((Optional(EXTENSIBLE) + ENUMERATION + Optional(((OF + enumeration_items) | enumeration_extension)))).setParseAction(EnumerationType)("enumeration_type") + general_ref = ((parameter_ref | variable_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="general_ref"))("general_ref") + group_qualifier = ((CaselessLiteral("\\") + entity_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="group_qualifier"))("group_qualifier") + named_types = ((entity_ref | type_ref)).setParseAction(NamedType)("named_types") + named_type_or_rename = ((named_types + Optional((AS + (entity_id | type_id))))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="named_type_or_rename"))("named_type_or_rename") + population = (entity_ref)("population") + qualified_attribute = ((SELF + group_qualifier + attribute_qualifier)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="qualified_attribute"))("qualified_attribute") + redeclared_attribute = ((qualified_attribute + Optional((RENAMED + attribute_id)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="redeclared_attribute"))("redeclared_attribute") + referenced_attribute = ((attribute_ref | qualified_attribute)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="referenced_attribute"))("referenced_attribute") + rename_id = ((constant_id | entity_id | function_id | procedure_id | type_id)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="rename_id"))("rename_id") + resource_ref = ((constant_ref | entity_ref | function_ref | procedure_ref | type_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="resource_ref"))("resource_ref") + rule_head = ((RULE + rule_id + FOR + CaselessLiteral("(") + entity_ref + ZeroOrMore((CaselessLiteral(",") + entity_ref)) + CaselessLiteral(")") + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="rule_head"))("rule_head") + select_list = ((CaselessLiteral("(") + named_types + ZeroOrMore((CaselessLiteral(",") + named_types)) + CaselessLiteral(")"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="select_list"))("select_list") + string_literal = ((simple_string_literal | encoded_string_literal))("string_literal") + subtype_constraint_head = ((SUBTYPE_CONSTRAINT + subtype_constraint_id + FOR + entity_ref + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="subtype_constraint_head"))("subtype_constraint_head") + subtype_declaration = ((SUBTYPE + OF + CaselessLiteral("(") + entity_ref + ZeroOrMore((CaselessLiteral(",") + entity_ref)) + CaselessLiteral(")"))).setParseAction(SubTypeExpression)("subtype_declaration") + total_over = ((TOTAL_OVER + CaselessLiteral("(") + entity_ref + ZeroOrMore((CaselessLiteral(",") + entity_ref)) + CaselessLiteral(")") + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="total_over"))("total_over") + type_label = ((type_label_id | type_label_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="type_label"))("type_label") + unique_rule = ((Optional((rule_label_id + CaselessLiteral(":"))) + referenced_attribute + ZeroOrMore((CaselessLiteral(",") + referenced_attribute)))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="unique_rule"))("unique_rule") + use_clause = ((USE + FROM + schema_ref + Optional((CaselessLiteral("(") + named_type_or_rename + ZeroOrMore((CaselessLiteral(",") + named_type_or_rename)) + CaselessLiteral(")"))) + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="use_clause"))("use_clause") + not_lparen_star = ((not_paren_star | CaselessLiteral(")"))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="not_lparen_star"))("not_lparen_star") + remark_ref = ((attribute_ref | constant_ref | entity_ref | enumeration_ref | function_ref | parameter_ref | procedure_ref | rule_label_ref | rule_ref | schema_ref | subtype_constraint_ref | type_label_ref | type_ref | variable_ref)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="remark_ref"))("remark_ref") + attribute_decl = ((redeclared_attribute | attribute_id)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="attribute_decl"))("attribute_decl") + generic_entity_type = ((GENERIC_ENTITY + Optional((CaselessLiteral(":") + type_label)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="generic_entity_type"))("generic_entity_type") + generic_type = ((GENERIC + Optional((CaselessLiteral(":") + type_label)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="generic_type"))("generic_type") + literal = ((binary_literal | logical_literal | real_literal | string_literal)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="literal"))("literal") + resource_or_rename = ((resource_ref + Optional((AS + rename_id)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="resource_or_rename"))("resource_or_rename") + schema_version_id = (string_literal)("schema_version_id") + select_extension = ((BASED_ON + type_ref + Optional((WITH + select_list)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="select_extension"))("select_extension") + select_type = ((Optional((EXTENSIBLE + Optional(GENERIC_ENTITY))) + SELECT + Optional((select_list | select_extension)))).setParseAction(SelectType)("select_type") + unique_clause = ((UNIQUE + unique_rule + CaselessLiteral(";") + ZeroOrMore((unique_rule + CaselessLiteral(";"))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="unique_clause"))("unique_clause") + lparen_then_not_lparen_star = ((CaselessLiteral("(") + ZeroOrMore(CaselessLiteral("(")) + not_lparen_star + ZeroOrMore(not_lparen_star))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="lparen_then_not_lparen_star"))("lparen_then_not_lparen_star") + remark_tag = ((CaselessLiteral("\"") + remark_ref + ZeroOrMore((CaselessLiteral(".") + remark_ref)) + CaselessLiteral("\""))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="remark_tag"))("remark_tag") + tail_remark = ((CaselessLiteral("--") + Optional(remark_tag))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="tail_remark"))("tail_remark") + constructed_types = ((enumeration_type | select_type)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="constructed_types"))("constructed_types") + reference_clause = ((REFERENCE + FROM + schema_ref + Optional((CaselessLiteral("(") + resource_or_rename + ZeroOrMore((CaselessLiteral(",") + resource_or_rename)) + CaselessLiteral(")"))) + CaselessLiteral(";"))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="reference_clause"))("reference_clause") + interface_specification = ((reference_clause | use_clause)).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="interface_specification"))("interface_specification") + supertype_factor = Forward()("supertype_factor") + interval_item = Forward()("interval_item") + subtype_constraint = Forward()("subtype_constraint") + repeat_stmt = Forward()("repeat_stmt") + subsuper = Forward()("subsuper") + increment = Forward()("increment") + remark = Forward()("remark") + increment_control = Forward()("increment_control") + local_variable = Forward()("local_variable") + until_control = Forward()("until_control") + while_control = Forward()("while_control") + parameter = Forward()("parameter") + width = Forward()("width") + string_type = Forward()("string_type") + array_type = Forward()("array_type") + if_stmt = Forward()("if_stmt") + index = Forward()("index") + repetition = Forward()("repetition") + index_qualifier = Forward()("index_qualifier") + bound_1 = Forward()("bound_1") + procedure_decl = Forward()("procedure_decl") + entity_constructor = Forward()("entity_constructor") + inverse_clause = Forward()("inverse_clause") + function_head = Forward()("function_head") + formal_parameter = Forward()("formal_parameter") + interval_high = Forward()("interval_high") + entity_decl = Forward()("entity_decl") + abstract_supertype_declaration = Forward()("abstract_supertype_declaration") + index_1 = Forward()("index_1") + general_aggregation_types = Forward()("general_aggregation_types") + real_type = Forward()("real_type") + type_decl = Forward()("type_decl") + stmt = Forward()("stmt") + declaration = Forward()("declaration") + explicit_attr = Forward()("explicit_attr") + compound_stmt = Forward()("compound_stmt") + aggregation_types = Forward()("aggregation_types") + simple_factor = Forward()("simple_factor") + where_clause = Forward()("where_clause") + entity_head = Forward()("entity_head") + underlying_type = Forward()("underlying_type") + subtype_constraint_decl = Forward()("subtype_constraint_decl") + logical_expression = Forward()("logical_expression") + case_label = Forward()("case_label") + expression = Forward()("expression") + general_list_type = Forward()("general_list_type") + actual_parameter_list = Forward()("actual_parameter_list") + width_spec = Forward()("width_spec") + selector = Forward()("selector") + syntax = Forward()("syntax") + aggregate_source = Forward()("aggregate_source") + return_stmt = Forward()("return_stmt") + embedded_remark = Forward()("embedded_remark") + parameter_type = Forward()("parameter_type") + term = Forward()("term") + derived_attr = Forward()("derived_attr") + repeat_control = Forward()("repeat_control") + assignment_stmt = Forward()("assignment_stmt") + bag_type = Forward()("bag_type") + inverse_attr = Forward()("inverse_attr") + constant_body = Forward()("constant_body") + precision_spec = Forward()("precision_spec") + general_bag_type = Forward()("general_bag_type") + qualifiable_factor = Forward()("qualifiable_factor") + bound_2 = Forward()("bound_2") + instantiable_type = Forward()("instantiable_type") + general_set_type = Forward()("general_set_type") + supertype_rule = Forward()("supertype_rule") + factor = Forward()("factor") + list_type = Forward()("list_type") + one_of = Forward()("one_of") + aggregate_type = Forward()("aggregate_type") + entity_body = Forward()("entity_body") + generalized_types = Forward()("generalized_types") + case_stmt = Forward()("case_stmt") + binary_type = Forward()("binary_type") + local_decl = Forward()("local_decl") + alias_stmt = Forward()("alias_stmt") + simple_expression = Forward()("simple_expression") + general_array_type = Forward()("general_array_type") + interval = Forward()("interval") + procedure_head = Forward()("procedure_head") + function_decl = Forward()("function_decl") + supertype_expression = Forward()("supertype_expression") + set_type = Forward()("set_type") + primary = Forward()("primary") + procedure_call_stmt = Forward()("procedure_call_stmt") + simple_types = Forward()("simple_types") + query_expression = Forward()("query_expression") + index_2 = Forward()("index_2") + constant_decl = Forward()("constant_decl") + case_action = Forward()("case_action") + schema_body = Forward()("schema_body") + element = Forward()("element") + numeric_expression = Forward()("numeric_expression") + aggregate_initializer = Forward()("aggregate_initializer") + schema_decl = Forward()("schema_decl") + supertype_term = Forward()("supertype_term") + algorithm_head = Forward()("algorithm_head") + supertype_constraint = Forward()("supertype_constraint") + interval_low = Forward()("interval_low") + domain_rule = Forward()("domain_rule") + rule_decl = Forward()("rule_decl") + concrete_types = Forward()("concrete_types") + qualifier = Forward()("qualifier") + subtype_constraint_body = Forward()("subtype_constraint_body") + function_call = Forward()("function_call") + bound_spec = Forward()("bound_spec") + derive_clause = Forward()("derive_clause") + supertype_factor << (((supertype_term + ZeroOrMore((AND + supertype_term))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="supertype_factor")) + interval_item << (simple_expression) + subtype_constraint << (((OF + CaselessLiteral("(") + supertype_expression + CaselessLiteral(")")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="subtype_constraint")) + repeat_stmt << (((REPEAT + repeat_control + CaselessLiteral(";") + stmt + ZeroOrMore(stmt) + END_REPEAT + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="repeat_stmt")) + subsuper << (((Optional(supertype_constraint) + Optional(subtype_declaration)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="subsuper")) + increment << (numeric_expression) + remark << (((embedded_remark | tail_remark))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="remark")) + increment_control << (((variable_id + CaselessLiteral(":=") + bound_1 + TO + bound_2 + Optional((BY + increment))))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="increment_control")) + local_variable << (((variable_id + ZeroOrMore((CaselessLiteral(",") + variable_id)) + CaselessLiteral(":") + parameter_type + Optional((CaselessLiteral(":=") + expression)) + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="local_variable")) + until_control << (((UNTIL + logical_expression))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="until_control")) + while_control << (((WHILE + logical_expression))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="while_control")) + parameter << (expression) + width << (numeric_expression) + string_type << (((STRING + Optional(width_spec)))).setParseAction(StringType) + array_type << (((ARRAY + bound_spec + OF + Optional(OPTIONAL) + Optional(UNIQUE) + instantiable_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="array_type")) + if_stmt << (((IF + logical_expression + THEN + stmt + ZeroOrMore(stmt) + Optional((ELSE + stmt + ZeroOrMore(stmt))) + END_IF + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="if_stmt")) + index << (numeric_expression) + repetition << (numeric_expression) + index_qualifier << (((CaselessLiteral("[") + index_1 + Optional((CaselessLiteral(":") + index_2)) + CaselessLiteral("]")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="index_qualifier")) + bound_1 << (numeric_expression) + procedure_decl << (((procedure_head + algorithm_head + ZeroOrMore(stmt) + END_PROCEDURE + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="procedure_decl")) + entity_constructor << (((entity_ref + CaselessLiteral("(") + Optional((expression + ZeroOrMore((CaselessLiteral(",") + expression)))) + CaselessLiteral(")")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="entity_constructor")) + inverse_clause << (((INVERSE + inverse_attr + ZeroOrMore(inverse_attr)))).setParseAction(AttributeList) + function_head << (((FUNCTION + function_id + Optional((CaselessLiteral("(") + formal_parameter + ZeroOrMore((CaselessLiteral(";") + formal_parameter)) + CaselessLiteral(")"))) + CaselessLiteral(":") + parameter_type + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="function_head")) + formal_parameter << (((parameter_id + ZeroOrMore((CaselessLiteral(",") + parameter_id)) + CaselessLiteral(":") + parameter_type))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="formal_parameter")) + interval_high << (simple_expression) + entity_decl << (((entity_head + entity_body + END_ENTITY + CaselessLiteral(";")))).setParseAction(EntityDeclaration) + abstract_supertype_declaration << (((ABSTRACT + SUPERTYPE + Optional(subtype_constraint)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="abstract_supertype_declaration")) + index_1 << (index) + general_aggregation_types << (((general_array_type | general_bag_type | general_list_type | general_set_type))).setParseAction(AggregationType) + real_type << (((REAL + Optional((CaselessLiteral("(") + precision_spec + CaselessLiteral(")")))))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="real_type")) + type_decl << (((TYPE + type_id + CaselessLiteral("=") + underlying_type + CaselessLiteral(";") + Optional(where_clause) + END_TYPE + CaselessLiteral(";")))).setParseAction(TypeDeclaration) + stmt << (((alias_stmt | assignment_stmt | case_stmt | compound_stmt | escape_stmt | if_stmt | null_stmt | procedure_call_stmt | repeat_stmt | return_stmt | skip_stmt))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="stmt")) + declaration << (((entity_decl | function_decl | procedure_decl | subtype_constraint_decl | type_decl))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="declaration")) + explicit_attr << (((attribute_decl + ZeroOrMore((CaselessLiteral(",") + attribute_decl)) + CaselessLiteral(":") + Optional(OPTIONAL) + parameter_type + CaselessLiteral(";")))).setParseAction(ExplicitAttribute) + compound_stmt << (((BEGIN + stmt + ZeroOrMore(stmt) + END + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="compound_stmt")) + aggregation_types << (((array_type | bag_type | list_type | set_type))).setParseAction(AggregationType) + simple_factor << (((aggregate_initializer | interval | query_expression | (Optional(unary_op) + ((CaselessLiteral("(") + expression + CaselessLiteral(")")) | primary)) | entity_constructor | enumeration_reference))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="simple_factor")) + where_clause << (((WHERE + domain_rule + CaselessLiteral(";") + ZeroOrMore((domain_rule + CaselessLiteral(";")))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="where_clause")) + entity_head << (((ENTITY + entity_id + subsuper + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="entity_head")) + underlying_type << (((constructed_types | concrete_types))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="underlying_type")) + subtype_constraint_decl << (((subtype_constraint_head + subtype_constraint_body + END_SUBTYPE_CONSTRAINT + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="subtype_constraint_decl")) + logical_expression << (expression) + case_label << (expression) + expression << (((simple_expression + Optional((rel_op_extended + simple_expression))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="expression")) + general_list_type << (((LIST + Optional(bound_spec) + OF + Optional(UNIQUE) + parameter_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="general_list_type")) + actual_parameter_list << (((CaselessLiteral("(") + Optional(parameter) + ZeroOrMore((CaselessLiteral(",") + parameter)) + CaselessLiteral(")")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="actual_parameter_list")) + width_spec << (((CaselessLiteral("(") + width + CaselessLiteral(")") + Optional(FIXED)))).setParseAction(WidthSpec) + selector << (expression) + syntax << (((schema_decl + ZeroOrMore(schema_decl)))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="syntax")) + aggregate_source << (simple_expression) + return_stmt << (((RETURN + Optional((CaselessLiteral("(") + expression + CaselessLiteral(")"))) + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="return_stmt")) + embedded_remark << (((CaselessLiteral("(*") + Optional(remark_tag) + ZeroOrMore(((not_paren_star + ZeroOrMore(not_paren_star)) | lparen_then_not_lparen_star | (CaselessLiteral("*") + ZeroOrMore(CaselessLiteral("*"))) | not_rparen_star_then_rparen | embedded_remark)) + CaselessLiteral("*)")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="embedded_remark")) + parameter_type << (((generalized_types | simple_types | named_types))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="parameter_type")) + term << (((factor + ZeroOrMore((multiplication_like_op + factor))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="term")) + derived_attr << (((attribute_decl + CaselessLiteral(":") + parameter_type + CaselessLiteral(":=") + expression + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="derived_attr")) + repeat_control << (((Optional(increment_control) + Optional(while_control) + Optional(until_control)))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="repeat_control")) + assignment_stmt << (((general_ref + ZeroOrMore(qualifier) + CaselessLiteral(":=") + expression + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="assignment_stmt")) + bag_type << (((BAG + Optional(bound_spec) + OF + instantiable_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="bag_type")) + inverse_attr << (((attribute_decl + CaselessLiteral(":") + Optional(((SET | BAG) + Optional(bound_spec) + OF)) + entity_ref + FOR + Optional((entity_ref + CaselessLiteral("."))) + attribute_ref + CaselessLiteral(";")))).setParseAction(InverseAttribute) + constant_body << (((constant_id + CaselessLiteral(":") + instantiable_type + CaselessLiteral(":=") + expression + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="constant_body")) + precision_spec << (numeric_expression) + general_bag_type << (((BAG + Optional(bound_spec) + OF + parameter_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="general_bag_type")) + qualifiable_factor << (((function_call | attribute_ref | constant_factor | general_ref | population))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="qualifiable_factor")) + bound_2 << (numeric_expression) + instantiable_type << (((concrete_types | entity_ref))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="instantiable_type")) + general_set_type << (((SET + Optional(bound_spec) + OF + parameter_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="general_set_type")) + supertype_rule << (((SUPERTYPE + subtype_constraint))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="supertype_rule")) + factor << (((simple_factor + Optional((CaselessLiteral("**") + simple_factor))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="factor")) + list_type << (((LIST + Optional(bound_spec) + OF + Optional(UNIQUE) + instantiable_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="list_type")) + one_of << (((ONEOF + CaselessLiteral("(") + supertype_expression + ZeroOrMore((CaselessLiteral(",") + supertype_expression)) + CaselessLiteral(")")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="one_of")) + aggregate_type << (((AGGREGATE + Optional((CaselessLiteral(":") + type_label)) + OF + parameter_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="aggregate_type")) + entity_body << (((ZeroOrMore(explicit_attr) + Optional(derive_clause) + Optional(inverse_clause) + Optional(unique_clause) + Optional(where_clause)))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="entity_body")) + generalized_types << (((aggregate_type | general_aggregation_types | generic_entity_type | generic_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="generalized_types")) + case_stmt << (((CASE + selector + OF + ZeroOrMore(case_action) + Optional((OTHERWISE + CaselessLiteral(":") + stmt)) + END_CASE + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="case_stmt")) + binary_type << (((BINARY + Optional(width_spec)))).setParseAction(BinaryType) + local_decl << (((LOCAL + local_variable + ZeroOrMore(local_variable) + END_LOCAL + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="local_decl")) + alias_stmt << (((ALIAS + variable_id + FOR + general_ref + ZeroOrMore(qualifier) + CaselessLiteral(";") + stmt + ZeroOrMore(stmt) + END_ALIAS + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="alias_stmt")) + simple_expression << (((term + ZeroOrMore((add_like_op + term))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="simple_expression")) + general_array_type << (((ARRAY + Optional(bound_spec) + OF + Optional(OPTIONAL) + Optional(UNIQUE) + parameter_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="general_array_type")) + interval << (((CaselessLiteral("{") + interval_low + interval_op + interval_item + interval_op + interval_high + CaselessLiteral("}")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="interval")) + procedure_head << (((PROCEDURE + procedure_id + Optional((CaselessLiteral("(") + Optional(VAR) + formal_parameter + ZeroOrMore((CaselessLiteral(";") + Optional(VAR) + formal_parameter)) + CaselessLiteral(")"))) + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="procedure_head")) + function_decl << (((function_head + algorithm_head + stmt + ZeroOrMore(stmt) + END_FUNCTION + CaselessLiteral(";")))).setParseAction(FunctionDeclaration) + supertype_expression << (((supertype_factor + ZeroOrMore((ANDOR + supertype_factor))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="supertype_expression")) + set_type << (((SET + Optional(bound_spec) + OF + instantiable_type))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="set_type")) + primary << (((literal | (qualifiable_factor + ZeroOrMore(qualifier))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="primary")) + procedure_call_stmt << ((((built_in_procedure | procedure_ref) + actual_parameter_list + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="procedure_call_stmt")) + simple_types << (((binary_type | boolean_type | integer_type | logical_type | number_type | real_type | string_type))).setParseAction(SimpleType) + query_expression << (((QUERY + CaselessLiteral("(") + variable_id + CaselessLiteral("<*") + aggregate_source + CaselessLiteral("|") + logical_expression + CaselessLiteral(")")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="query_expression")) + index_2 << (index) + constant_decl << (((CONSTANT + constant_body + ZeroOrMore(constant_body) + END_CONSTANT + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="constant_decl")) + case_action << (((case_label + ZeroOrMore((CaselessLiteral(",") + case_label)) + CaselessLiteral(":") + stmt))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="case_action")) + schema_body << (((ZeroOrMore(interface_specification) + Optional(constant_decl) + ZeroOrMore((declaration | rule_decl))))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="schema_body")) + element << (((expression + Optional((CaselessLiteral(":") + repetition))))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="element")) + numeric_expression << (simple_expression) + aggregate_initializer << (((CaselessLiteral("[") + Optional((element + ZeroOrMore((CaselessLiteral(",") + element)))) + CaselessLiteral("]")))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="aggregate_initializer")) + schema_decl << (((SCHEMA + schema_id + Optional(schema_version_id) + CaselessLiteral(";") + schema_body + END_SCHEMA + CaselessLiteral(";")))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="schema_decl")) + supertype_term << (((one_of | (CaselessLiteral("(") + supertype_expression + CaselessLiteral(")")) | entity_ref))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="supertype_term")) + algorithm_head << (((ZeroOrMore(declaration) + Optional(constant_decl) + Optional(local_decl)))).setParseAction(lambda s, loc, t: ListNode(s, loc, t, rule="algorithm_head")) + supertype_constraint << (((abstract_supertype_declaration | abstract_entity_declaration | supertype_rule))).setParseAction(SuperTypeExpression) + interval_low << (simple_expression) + domain_rule << (((Optional((rule_label_id + CaselessLiteral(":"))) + expression))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="domain_rule")) + rule_decl << (((rule_head + algorithm_head + ZeroOrMore(stmt) + where_clause + END_RULE + CaselessLiteral(";")))).setParseAction(RuleDeclaration) + concrete_types << (((aggregation_types | simple_types | type_ref))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="concrete_types")) + qualifier << (((attribute_qualifier | group_qualifier | index_qualifier))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="qualifier")) + subtype_constraint_body << (((Optional(abstract_supertype) + Optional(total_over) + Optional((supertype_expression + CaselessLiteral(";")))))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="subtype_constraint_body")) + function_call << ((((built_in_function | function_ref) + actual_parameter_list))).setParseAction(lambda s, loc, t: Node(s, loc, t, rule="function_call")) + bound_spec << (((CaselessLiteral("[") + bound_1 + CaselessLiteral(":") + bound_2 + CaselessLiteral("]")))).setParseAction(BoundSpecification) + derive_clause << (((DERIVE + derived_attr + ZeroOrMore(derived_attr)))).setParseAction(AttributeList) + + syntax.ignore("--" + restOfLine) + syntax.ignore(Regex(r"\((?:\*(?:[^*]*\*+)+?\))")) + ast = syntax.parseFile(fn) + s = schema.Schema(ast) + m = mapping.Mapping(s) + + with open(cache_file, "wb") as f: + pickle.dump(m, f, protocol=0) + return m + +if __name__ == "__main__": + m = parse(sys.argv[1]) + import importlib + for output in sys.argv[2:]: + mdl = importlib.import_module(output) + mdl.Generator(m).emit() + sys.stdout.write(m.schema.name) + diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header.py new file mode 100644 index 0000000000000000000000000000000000000000..4cc8c8ea844a90fd48a292e114bdcc2b9d89293d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header.py @@ -0,0 +1,263 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import operator +import itertools + +import codegen +import templates +import documentation + +from collections import defaultdict + +USE_VIRTUAL_INHERITANCE = True + +class Header(codegen.Base): + def __init__(self, mapping): + declarations = [] + + case_lookup = lambda nm: [k for k in mapping.schema.keys if k.lower() == nm.lower()][0] + case_normalize = lambda nm: nm if nm.startswith("IfcUtil::") else case_lookup(nm) + create_supertype_statement = lambda nms: ", ".join( + "public %s %s" % ("" if c.startswith("IfcUtil::") else "", c) for c in nms + ) + + write = lambda str, **kwargs: declarations.append( + str + % dict({"documentation": templates.multi_line_comment(documentation.description(kwargs["name"]))}, **kwargs) + ) + + forward_names = list(mapping.schema.entities.keys()) + list(mapping.schema.simpletypes.keys()) + forward_definitions = "".join(["class %s; " % n for n in forward_names]) + + select_super_types = defaultdict(list) + + for name, type in mapping.schema.selects.items(): + for nm in type.values: + select_super_types[str(nm).lower()].append(name) + write(templates.select_virtual if USE_VIRTUAL_INHERITANCE else templates.select_plain, name=name) + + def get_select_super_types(nm, bases=[]): + x = list(select_super_types[nm.lower()]) + for y in x: + x.extend(get_select_super_types(y)) + return sorted(set(x) - set(itertools.chain.from_iterable(map(get_select_super_types, bases)))) + + for name, type in mapping.schema.enumerations.items(): + short_name = name[:-4] if name.endswith("Enum") else name + write(templates.enumeration, name=name, values=", ".join(["%s_%s" % (short_name, v) for v in type.values])) + + emitted_simpletypes = set() + while len(emitted_simpletypes) < len(mapping.schema.simpletypes): + for name, type in mapping.schema.simpletypes.items(): + + if name.lower() in emitted_simpletypes: + continue + + type_str = mapping.make_type_string(mapping.flatten_type_string(type)) + attr_type = mapping.make_argument_type(type) + superclass = mapping.simple_type_parent(name) + + superclasses = [] + all_superclasses = [] + if superclass is not None: + superclasses.append(superclass) + while superclass: + all_superclasses.append(superclass) + superclass = mapping.simple_type_parent(superclass) + else: + superclasses.append("IfcUtil::IfcBaseType") + + if USE_VIRTUAL_INHERITANCE: + superclasses.extend(get_select_super_types(name, bases=all_superclasses)) + + is_emitted = ( + lambda nm: nm == "IfcUtil::IfcBaseType" + or nm in mapping.schema.selects + or nm.lower() in emitted_simpletypes + ) + if not all(map(is_emitted, superclasses)): + continue + + superclasses = list(map(case_normalize, superclasses)) + + emitted_simpletypes.add(name.lower()) + + superclass_statement = create_supertype_statement(superclasses) + + write( + templates.simpletype, name=name, type=type_str, attr_type=attr_type, superclass=superclass_statement + ) + + class_definitions = [] + + write = lambda str, **kwargs: class_definitions.append( + str + % dict({"documentation": templates.multi_line_comment(documentation.description(kwargs["name"]))}, **kwargs) + ) + + emitted_entities = set() + while len(emitted_entities) < len(mapping.schema.entities): + for name, type in mapping.schema.entities.items(): + if name.lower() in emitted_entities: + continue + + if len(type.supertypes) == 0 or set(map(str.lower, type.supertypes)) <= emitted_entities: + attr_lines = [] + + def write_method(attr): + attr_lines.extend( + ["/// %s" % d for d in documentation.description(".".join((name, attr.name)))] + ) + type_str = mapping.get_parameter_type(attr) + if mapping.make_argument_type(attr) != "IfcUtil::Argument_UNKNOWN": + attr_lines.append("%s %s() const;" % (type_str, attr.name)) + attr_lines.append("void set%s(%s v);" % (attr.name, type_str)) + + [write_method(attr) for attr in type.attributes] + + inv_lines = [] + + def write_inverse(attr): + inv_lines.append( + templates.inverse_attr + % {"name": attr.name, "entity": attr.entity, "attribute": attr.attribute} + ) + + if type.inverse: + [write_inverse(attr) for attr in type.inverse] + + attributes = "\n".join(["%s%s" % (" " * 4, a) for a in attr_lines]) + if len(attributes): + attributes += "\n" + + inverse = "\n".join(["%s%s" % (" " * 4, a) for a in inv_lines]) + if len(inverse): + inverse += "\n" + + all_supertypes = [] + tt = type + while len(tt.supertypes): + all_supertypes.append(tt.supertypes[0]) + tt = mapping.schema.entities[tt.supertypes[0]] + + supertypes = list(type.supertypes) if len(type.supertypes) else ["IfcUtil::IfcBaseEntity"] + if USE_VIRTUAL_INHERITANCE: + supertypes.extend(get_select_super_types(name, bases=all_supertypes)) + supertypes = list(map(case_normalize, supertypes)) + superclass = create_supertype_statement(supertypes) + + argument_count = mapping.argument_count(type) + + argument_start = argument_count - len(type.attributes) + + argument_name_function_body_switch_stmt = ( + " switch (i) {%s}" + % ( + "".join( + [ + 'case %d: return "%s"; ' % (i + argument_start, attr.name) + for i, attr in enumerate(type.attributes) + ] + ) + ) + if len(type.attributes) + else "" + ) + argument_name_function_body_tail = ( + (" return %s::getArgumentName(i); " % type.supertypes[0]) + if len(type.supertypes) == 1 + else ' (void)i; throw IfcParse::IfcAttributeOutOfRangeException("Argument index out of range"); ' + ) + + argument_name_function_body = ( + argument_name_function_body_switch_stmt + argument_name_function_body_tail + ) + + derived = mapping.derived_in_supertype(type) + attribute_names = list(map(operator.attrgetter("name"), mapping.arguments(type))) + derived_in_supertype = set(derived) & set(attribute_names) + derived_in_supertype_indices = sorted(attribute_names.index(nm) for nm in derived_in_supertype) + attribute_type_cases = [ + "case %d: return IfcUtil::Argument_DERIVED; " % idx for idx in derived_in_supertype_indices + ] + attribute_type_cases += [ + "case %d: return %s; " % (i + argument_start, mapping.make_argument_type(attr)) + for i, attr in enumerate(type.attributes) + ] + argument_type_function_body_switch_stmt = ( + " switch (i) {%s}" % ("".join(attribute_type_cases)) if len(type.attributes) else "" + ) + argument_type_function_body_tail = ( + (" return %s::getArgumentType(i); " % type.supertypes[0]) + if len(type.supertypes) == 1 + else ' (void)i; throw IfcParse::IfcAttributeOutOfRangeException("Argument index out of range"); ' + ) + + argument_type_function_body = ( + argument_type_function_body_switch_stmt + argument_type_function_body_tail + ) + + argument_entity_function_body_switch_stmt = ( + " switch (i) {%s}" + % ( + "".join( + [ + "case %d: return %s; " % (i + argument_start, mapping.make_argument_entity(attr)) + for i, attr in enumerate(type.attributes) + ] + ) + ) + if len(type.attributes) + else "" + ) + argument_entity_function_body_tail = ( + (" return %s::getArgumentEntity(i); " % type.supertypes[0]) + if len(type.supertypes) == 1 + else ' (void)i; throw IfcParse::IfcAttributeOutOfRangeException("Argument index out of range"); ' + ) + + argument_entity_function_body = ( + argument_entity_function_body_switch_stmt + argument_entity_function_body_tail + ) + + constructor_arguments = ", ".join( + "%(full_type)s v%(index)d_%(name)s" % a for a in mapping.get_assignable_arguments(type) + ) + + write(templates.entity, **locals()) + emitted_entities.add(name) + + self.str = templates.header % { + "schema_name_upper": mapping.schema.name.upper(), + "schema_name": mapping.schema.name.capitalize(), + "declarations": "".join(declarations), + "forward_definitions": forward_definitions, + "class_definitions": "".join(class_definitions), + } + + self.schema_name = mapping.schema.name.capitalize() + + self.file_name = "%s.h" % self.schema_name + + def __repr__(self): + return self.str + + +Generator = Header diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header_schema.exp b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header_schema.exp new file mode 100644 index 0000000000000000000000000000000000000000..0dba8dba60bdbf8e092c5d3e99983ec12cd51544 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/header_schema.exp @@ -0,0 +1,28 @@ +SCHEMA header_section_schema; + +TYPE time_stamp_text = STRING(256); +END_TYPE; + +TYPE schema_name = STRING(1024); +END_TYPE; + +ENTITY file_name; + name : STRING (256); + time_stamp : time_stamp_text; + author : LIST [1:?] OF STRING (256); + organization : LIST [1:?] OF STRING (256); + preprocessor_version : STRING (256); + originating_system : STRING (256); + authorisation : STRING (256); +END_ENTITY; + +ENTITY file_description; + description : LIST [1:?] OF STRING (256); + implementation_level : STRING (256); +END_ENTITY; + +ENTITY file_schema; + schema_identifiers : LIST [1:?] OF UNIQUE schema_name; +END_ENTITY; + +END_SCHEMA; diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/implementation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/implementation.py new file mode 100644 index 0000000000000000000000000000000000000000..248bbd6e86db2d900acacf67e2b5812028d4a655 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/implementation.py @@ -0,0 +1,428 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import codegen +import templates + +from schema import OrderedCaseInsensitiveDict + +from header import USE_VIRTUAL_INHERITANCE + + +class Implementation(codegen.Base): + def __init__(self, mapping): + enumeration_functions = [] + entity_implementations = [] + schema_entity_statements = [] + + schema_name = mapping.schema.name.capitalize() + schema_name_upper = mapping.schema.name.upper() + + stringify = lambda s: '"%s"' % s + cat = lambda vs: "".join(vs) + catc = lambda vs: ", ".join(vs) + catnl = lambda vs: "\n".join(vs) + cator = lambda vs: " || ".join(vs) + nl = lambda s: "%s\n" % s if len(s) else s + + write = lambda str, **kwargs: enumeration_functions.append(str % kwargs) + + collections_by_type = ( + ("entity", mapping.schema.entities), + ("type_declaration", mapping.schema.simpletypes), + ("select_type", mapping.schema.selects), + ("enumeration_type", mapping.schema.enumerations), + ) + self.names = [] + for _, collection in collections_by_type: + self.names.extend(collection.keys()) + self.names.sort(key=str.lower) + + for name, enum in mapping.schema.enumerations.items(): + short_name = name[:-4] if name.endswith("Enum") else name + context = locals() + write( + templates.enumeration_function, + max_id=len(enum.values), + name=name, + schema_name=schema_name, + schema_name_upper=schema_name_upper, + index_in_schema=self.names.index(str(name)), + values=catc(map(stringify, enum.values)), + from_string_statements=catnl( + templates.enum_from_string_stmt % dict(context, **locals()) for value in enum.values + ), + ) + + if USE_VIRTUAL_INHERITANCE: + for name, enum in mapping.schema.selects.items(): + write( + templates.select_function, + name=name, + schema_name=schema_name, + schema_name_upper=schema_name_upper, + index_in_schema=self.names.index(str(name)), + ) + + write = lambda str, **kwargs: entity_implementations.append(str % kwargs) + + for name, type in mapping.schema.entities.items(): + parent_type_test = ( + "" + if not type.supertypes or len(type.supertypes) != 1 + else templates.parent_type_test % (type.supertypes[0]) + ) + + constructor_arguments = mapping.get_assignable_arguments(type, include_derived=True) + constructor_arguments_str = catc( + "%(full_type)s v%(index)d_%(name)s" % a for a in constructor_arguments if not a["is_derived"] + ) + attributes = [] + constructor_implementations = [] + write_attr = lambda str, **kwargs: attributes.append(str % kwargs) + for arg in constructor_arguments: + if not arg["is_inherited"] and not arg["is_derived"]: + + def find_template(arg): + simple = mapping.schema.is_simpletype(arg["list_instance_type"]) + select = arg["list_instance_type"] == "IfcUtil::IfcBaseClass" + express = ( + mapping.flatten_type_string(arg["list_instance_type"]) in mapping.express_to_cpp_typemapping + ) + if arg["is_enum"]: + return templates.get_attr_stmt_enum + elif arg["is_nested"] and arg["is_templated_list"]: + return templates.get_attr_stmt_nested_array + elif arg["is_templated_list"] and not (select or simple or express): + return templates.get_attr_stmt_array + elif arg["non_optional_type"].endswith("*"): + return templates.get_attr_stmt_entity + else: + return templates.get_attr_stmt + + null_check = "" + if arg["is_optional"]: + attr_check = ( + "if(get_attribute_value(%d).isNull()) { return %%s; }" + % (arg["index"] - 1,) + ) + if "boost::optional" in arg["full_type"]: + null_check = attr_check % "boost::none" + else: + null_check = attr_check % "nullptr" + + tmpl = find_template(arg) + write_attr( + templates.const_function, + class_name=name, + name=arg["name"], + arguments="", + schema_name=schema_name, + schema_name_upper=schema_name_upper, + return_type=arg["full_type"], + body=tmpl + % { + "index": arg["index"] - 1, + "type": arg["full_type"].replace("::Value", ""), + "non_optional_type": arg["non_optional_type"].replace("::Value", ""), + "non_optional_type_no_pointer": arg["non_optional_type"] + .replace("::Value", "") + .replace("*", ""), + "list_instance_type": arg["list_instance_type"], + "null_check": null_check, + }, + ) + + def find_template(arg): + simple = mapping.schema.is_simpletype(arg["list_instance_type"]) + select = arg["list_instance_type"] == "IfcUtil::IfcBaseClass" + express = arg["list_instance_type"] in mapping.express_to_cpp_typemapping + if arg["is_enum"]: + return templates.set_attr_stmt_enum + elif arg["is_templated_list"] and not (select or simple or express): + return templates.set_attr_stmt_array + elif arg["full_type"].endswith('*'): + return templates.set_attr_instance + else: + return templates.set_attr_stmt + + tmpl = find_template(arg) + write_attr( + templates.function, + class_name=name, + name="set%s" % arg["name"], + arguments="%s v" % arg["full_type"], + return_type="void", + schema_name=schema_name, + schema_name_upper=schema_name_upper, + body=tmpl + % { + "index": arg["index"] - 1, + "type": arg["full_type"].replace("::Value", ""), + "non_optional_type": arg["non_optional_type"].replace("::Value", ""), + "star_if_optional": "*" if "boost::optional" in arg["full_type"] else "", + "check_optional_set_begin": "if (v) {" if "boost::optional" in arg["full_type"] else "", + "check_optional_set_else": "} else {" if "boost::optional" in arg["full_type"] else "if constexpr (false)", + "check_optional_set_end": "}" if "boost::optional" in arg["full_type"] else "", + }, + ) + + if arg["is_derived"]: + constructor_implementations.append(templates.constructor_stmt_derived % {"index": arg["index"] - 1}) + else: + is_optional_non_naked_ptr = arg["is_optional"] and not arg["non_optional_type"].endswith("*") + arg_name = "v%(index)d_%(name)s" % arg + deref_name = ("*%s" % arg_name) if is_optional_non_naked_ptr else arg_name + + tmpl = ( + templates.constructor_stmt_array + if arg["is_templated_list"] + else templates.constructor_stmt_enum + if arg["is_enum"] + else templates.constructor_stmt_instance + if arg["full_type"].endswith('*') + else templates.constructor_stmt + ) + impl = tmpl % { + "name": deref_name, + "index": arg["index"] - 1, + "type": arg["non_optional_type"].replace("::Value", ""), + } + if is_optional_non_naked_ptr: + impl = templates.constructor_stmt_optional % { + "name": arg_name, + "index": arg["index"] - 1, + "stmt": impl, + } + constructor_implementations.append(impl) + + def get_attribute_index(entity, attr_name): + related_entity = mapping.schema.entities[entity] + return [ + a["name"].lower() for a in mapping.get_assignable_arguments(related_entity, include_derived=True) + ].index(attr_name.lower()) + + inverse = [ + templates.const_function + % { + "class_name": name, + "schema_name": schema_name, + "schema_name_upper": schema_name_upper, + "name": i.name, + "arguments": "", + "return_type": "::%s::%s::list::ptr" % (schema_name, i.entity), + "body": templates.get_inverse + % { + "type": i.entity, + "type_index": self.names.index(i.entity), + "index": get_attribute_index(i.entity, i.attribute), + "schema_name": schema_name, + "schema_name_upper": schema_name_upper, + }, + } + for i in type.inverse + ] + + superclass = ( + "%s(std::move(e))" % type.supertypes[0] + if len(type.supertypes) == 1 + else "IfcUtil::IfcBaseEntity(std::move(e))" + ) + + superclass_num_attrs = ( + "%s(IfcEntityInstanceData(in_memory_attribute_storage(%%d)))" % type.supertypes[0] + if len(type.supertypes) == 1 + else "IfcUtil::IfcBaseEntity(IfcEntityInstanceData(in_memory_attribute_storage(%d)))" + ) % len(constructor_arguments) + + write( + templates.entity_implementation, + name=name, + parent_type_test=parent_type_test, + constructor_arguments=constructor_arguments_str, + constructor_implementation=cat(constructor_implementations), + attributes=nl(catnl(attributes)), + inverse=nl(catnl(inverse)), + superclass=superclass, + superclass_num_attrs=superclass_num_attrs, + schema_name=schema_name, + schema_name_upper=schema_name_upper, + index_in_schema=self.names.index(str(name)), + ) + + selectable_simple_types = sorted( + set(sum([b.values for a, b in mapping.schema.selects.items()], [])) + & set(map(str, mapping.schema.types.keys())) + ) + schema_entity_statements += [ + templates.schema_entity_stmt % locals() for name, type in mapping.schema.simpletypes.items() + ] + schema_entity_statements += [ + templates.schema_entity_stmt % locals() for name, type in mapping.schema.enumerations.items() + ] + schema_entity_statements += [ + templates.schema_entity_stmt % locals() for name, type in mapping.schema.entities.items() + ] + + enumerable_types = sorted( + set( + [name for name, type in mapping.schema.types.items()] + + [name for name, type in mapping.schema.entities.items()] + ) + ) + max_len = max(map(len, enumerable_types)) + type_name_strings = catc(map(stringify, enumerable_types)) + string_map_statements = [ + templates.string_map_statement + % {"uppercase_name": name.upper(), "name": name, "padding": " " * (max_len - len(name))} + for name in enumerable_types + ] + + enumeration_index_by_str = OrderedCaseInsensitiveDict((j, i) for i, j in enumerate(enumerable_types)) + + def get_parent_id(s): + e = mapping.schema.entities.get(s) + if e and e.supertypes: + return enumeration_index_by_str[e.supertypes[0]] + else: + return -1 + + parent_type_statements = ",".join(map(str, map(get_parent_id, enumerable_types))) + + max_id = len(enumerable_types) + + simple_type_statements = cator("v == Type::%s" % name for name in selectable_simple_types) + + simple_type_impl = [] + for class_name, type in mapping.schema.simpletypes.items(): + type_str = mapping.make_type_string(mapping.flatten_type_string(type)) + attr_type = mapping.make_argument_type(type) + superclass = mapping.simple_type_parent(class_name) or "IfcUtil::IfcBaseType" + + simpletype_impl_is = ( + templates.simpletype_impl_is_with_supertype + if superclass + else templates.simpletype_impl_is_without_supertype + ) + + constructor = templates.constructor_single_initlist# if superclass else templates.constructor + + simpletype_impl_cast = ( + templates.simpletype_impl_cast_templated + if mapping.is_templated_list(type) + else templates.simpletype_impl_cast + ) + + simpletype_impl_constructor = ( + templates.simpletype_impl_constructor_templated + if mapping.is_templated_list(type) + else templates.simpletype_impl_constructor + ) + + def compose(params, schema_name=schema_name, schema_name_upper=schema_name_upper): + class_name, attr_type, superclass, superclass_init, name, tmpl, return_type, args, body = params + index_in_schema = self.names.index(str(class_name)) + underlying_type = mapping.list_instance_type(type) + arguments = ",".join(args) + body = body % locals() + return tmpl % locals() + + simple_type_impl.append(templates.simpletype_impl_comment % {"name": class_name}) + simple_type_impl.extend( + map( + compose, + map( + lambda x: (class_name, attr_type, superclass) + x, + ( + ( + "", + "Class", + templates.function, + "const IfcParse::type_declaration&", + (), + templates.simpletype_impl_class, + ), + ( + "", + "declaration", + templates.const_function, + "const IfcParse::type_declaration&", + (), + templates.simpletype_impl_declaration, + ), + ( + "std::move(e)", + "", + constructor, + "", + ("IfcEntityInstanceData&& e",), + "", + ), + ("", "", constructor, "", ("%s v" % type_str,), ("set_attribute_value(0, v%s);" % ("->generalize()" if mapping.is_templated_list(type) else ""))) if mapping.simple_type_parent(class_name) is None else \ + ("v", "", constructor, "", ("%s v" % type_str,), ""), + ("", "", templates.cast_function, type_str, (), simpletype_impl_cast), + ), + ), + ) + ) + simple_type_impl.append("") + + """ + external_definitions = ( + [("extern entity* %s_%%s_type;" % schema_name_upper) % n for n in mapping.schema.entities.keys()] + + [ + ("extern type_declaration* %s_%%s_type;" % schema_name_upper) % n + for n in mapping.schema.simpletypes.keys() + ] + + [ + ("extern enumeration_type* %s_%%s_type;" % schema_name_upper) % n + for n in mapping.schema.enumerations.keys() + ] + + [ + ("extern select_type* %s_%%s_type;" % schema_name_upper) % n + for n in mapping.schema.selects.keys() + ] + ) + """ + external_definitions = ["extern declaration* %s_types[%d];" % (schema_name_upper, len(self.names))] + + self.str = templates.implementation % { + "schema_name_upper": schema_name_upper, + "schema_name": schema_name, + "max_id": max_id, + "enumeration_functions": cat(enumeration_functions), + "schema_entity_statements": catnl(schema_entity_statements), + "type_name_strings": type_name_strings, + "string_map_statements": catnl(string_map_statements), + "simple_type_statement": simple_type_statements, + "parent_type_statements": parent_type_statements, + "entity_implementations": catnl(entity_implementations), + "simple_type_impl": catnl(simple_type_impl), + "external_definitions": catnl(external_definitions), + } + + self.schema_name = mapping.schema.name.capitalize() + + self.file_name = "%s.cpp" % self.schema_name + + def __repr__(self): + return self.str + + +Generator = Implementation diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/mapping.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..7ebac2478b04749465a87e3ba9c11d474ca2d4f3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/mapping.py @@ -0,0 +1,294 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from __future__ import annotations +import sys +import nodes +import templates +import schema + +from header import USE_VIRTUAL_INHERITANCE + +class Mapping: + + express_to_cpp_typemapping = { + "boolean": "bool", + "logical": "boost::logic::tribool", + "integer": "int", + "real": "double", + "number": "double", + "string": "std::string", + "binary": "boost::dynamic_bitset<>", + } + + supported_argument_types = set( + [ + "INT", + "BOOL", + "LOGICAL", + "DOUBLE", + "STRING", + "BINARY", + "ENUMERATION", + "ENTITY_INSTANCE", + "AGGREGATE_OF_INT", + "AGGREGATE_OF_DOUBLE", + "AGGREGATE_OF_STRING", + "AGGREGATE_OF_BINARY", + "AGGREGATE_OF_ENTITY_INSTANCE", + "AGGREGATE_OF_AGGREGATE_OF_INT", + "AGGREGATE_OF_AGGREGATE_OF_DOUBLE", + "AGGREGATE_OF_AGGREGATE_OF_ENTITY_INSTANCE", + ] + ) + + def __init__(self, schema: schema.Schema): + self.schema = schema + + def flatten_type_string(self, type): + return self.flatten_type_string(self.schema.types[type].type) if self.schema.is_simpletype(type) else type + + def flatten_type(self, type): + res = self.flatten_type(self.schema.types[type].type) if self.schema.is_simpletype(type) else type + return res + + def simple_type_parent(self, type): + parent = self.schema.types[type].type + if isinstance(parent, (nodes.AggregationType, nodes.StringType)) or ( + isinstance(parent, nodes.SimpleType) and isinstance(parent.type, nodes.StringType) + ): + return None + if str(parent) in self.express_to_cpp_typemapping: + return None + return str(parent) + + def make_type_string(self, type): + if isinstance(type, nodes.StringType) or ( + isinstance(type, nodes.SimpleType) and isinstance(type.type, nodes.StringType) + ): + type = "string" + if isinstance(type, (str, nodes.BinaryType, nodes.SimpleType, nodes.NamedType)): + return self.express_to_cpp_typemapping.get(str(type), "::%s::%s" % (self.schema.name.capitalize(), type)) + else: + if type.bounds is None: + import pdb + + pdb.set_trace() + is_list = self.schema.is_entity(type.type) + is_nested_list = isinstance(type.type, nodes.AggregationType) + tmpl = ( + templates.list_list_type if is_nested_list else templates.list_type if is_list else templates.array_type + ) + return tmpl % { + "instance_type": self.make_type_string(self.flatten_type_string(type.type)), + "lower": type.bounds.lower, + "upper": type.bounds.upper, + } + + def is_array(self, type): + if isinstance(type, nodes.AggregationType): + return True + elif isinstance(type, str) and self.schema.is_type(type): + return self.is_array(self.schema.types[type].type) + else: + return False + + def make_argument_entity(self, attr): + type = attr.type if hasattr(attr, "type") else attr + while isinstance(type, nodes.AggregationType): + type = type.type + if str(type) in self.express_to_cpp_typemapping: + return "Type::UNDEFINED" + else: + return "Type::%s" % type + + def make_argument_type(self, attr): + def _make_argument_type(type): + if isinstance(type, nodes.SimpleType): + type = type.type + if self.schema.is_entity(type) or isinstance(type, nodes.SelectType): + return "ENTITY_INSTANCE" + elif isinstance(type, nodes.BinaryType): + return "BINARY" + elif isinstance(type, nodes.StringType): + return "STRING" + elif isinstance(type, nodes.EnumerationType): + return "ENUMERATION" + elif isinstance(type, nodes.AggregationType): + ty = _make_argument_type(type.type) + if ty == "UNKNOWN": + return "UNKNOWN" + return "AGGREGATE_OF_" + ty + elif str(type) in self.express_to_cpp_typemapping: + return self.express_to_cpp_typemapping.get(str(type), type).split("::")[-1].upper() + elif self.schema.is_type(type): + return _make_argument_type(self.schema.types[type].type) + else: + raise ValueError("Unable to map type %r for attribute %r" % (type, attr)) + + ty = _make_argument_type(attr.type if hasattr(attr, "type") else attr) + if ty == "TRIBOOL": + ty = "LOGICAL" + + if ty not in self.supported_argument_types: + import pdb + + pdb.set_trace() + print("Attribute %r mapped as 'unknown'" % (attr), file=sys.stderr) + ty = "UNKNOWN" + return "IfcUtil::Argument_%s" % ty + + def get_type_dep(self, type): + if isinstance(type, str): + return self.express_to_cpp_typemapping.get(str(type), type) + else: + return self.get_type_dep(type.type) + + def get_parameter_type(self, attr, allow_optional=True): + attr_type = self.flatten_type(attr.type) + + if (isinstance(attr_type, nodes.SimpleType) and isinstance(attr_type.type, nodes.StringType)) or isinstance( + attr_type, nodes.StringType + ): + type_str = self.express_to_cpp_typemapping["string"] + else: + type_str = self.express_to_cpp_typemapping.get(str(attr_type), attr_type) + + is_ptr = False + + if self.schema.is_enumeration(attr_type): + type_str = "::%s::%s::Value" % (self.schema.name.capitalize(), attr_type) + elif isinstance(type_str, nodes.AggregationType): + is_nested_list = isinstance(attr_type.type, nodes.AggregationType) + ty = self.get_parameter_type(attr_type.type if is_nested_list else attr_type) + # We do not use pointers in aggregate_of. aggregate_of has member vector + ty = ty.replace("*", "") + + # https://github.com/IfcOpenShell/IfcOpenShell/issues/2805 + # We do support statically typed select types as aggregates when USE_VIRTUAL_INHERITANCE=True + + if not USE_VIRTUAL_INHERITANCE and self.schema.is_select(attr_type.type): + type_str = templates.untyped_list + elif self.schema.is_simpletype(ty) or str(ty) in self.express_to_cpp_typemapping.values(): + tmpl = templates.nested_array_type if is_nested_list else templates.array_type + bounds = (attr_type.bounds.lower, attr_type.bounds.upper) if attr_type.bounds else (-1, -1) + type_str = tmpl % {"instance_type": ty, "lower": bounds[0], "upper": bounds[1]} + else: + tmpl = templates.list_list_type if is_nested_list else templates.list_type + type_str = tmpl % {"instance_type": ty} + elif self.schema.is_entity(type_str) or self.schema.is_select(type_str): + type_str = "::%s::%s*" % (self.schema.name.capitalize(), attr_type) + is_ptr = True + if allow_optional and attr.optional and not is_ptr: + # pointers are still handled with nullptr for the time being + type_str = "boost::optional< %s >" % type_str + return type_str + + def argument_count(self, t): + c = sum([self.argument_count(self.schema.entities[s]) for s in t.supertypes]) + return c + len(t.attributes) + + def arguments(self, t): + c = sum([self.arguments(self.schema.entities[s]) for s in t.supertypes], []) + return c + t.attributes + + def derived_in_supertype(self, t): + c = sum([self.derived_in_supertype(self.schema.entities[s]) for s in t.supertypes], []) + derived = c + t.derive + return [d[0][1] for d in derived if isinstance(d[0], tuple)] + + def list_instance_type(self, attr): + attr_type = attr.type if isinstance(attr, nodes.ExplicitAttribute) else attr + if isinstance(attr_type, str): + return None + + def f(v): + v = self.flatten_type(v) + if isinstance(v, (nodes.AggregationType, nodes.StringType)) or ( + isinstance(v, nodes.SimpleType) and isinstance(v.type, nodes.StringType) + ): + return "string" + if not USE_VIRTUAL_INHERITANCE and self.schema.is_select(v): + return "IfcUtil::IfcBaseClass" + if str(v) in self.schema.types or str(v) in self.schema.entities: + return "::%s::%s" % (self.schema.name.capitalize(), v) + else: + return str(v) + + if self.is_array(attr_type): + if not isinstance(attr_type, str) and self.is_array(attr_type.type): + if isinstance(attr_type.type, str): + return f(attr_type.type) + else: + return f(attr_type.type.type) + else: + if isinstance(attr_type, str): + return f(attr_type) + else: + return f(attr_type.type) + return None + + def is_templated_list(self, attr): + attr_type = attr.type if isinstance(attr, nodes.ExplicitAttribute) else attr + if isinstance(attr, str): + return False + ty = self.list_instance_type(attr) + if ty is None: + return False + arr = self.is_array(attr_type) + simple = self.schema.is_simpletype(ty) + express = self.flatten_type_string(ty) in self.express_to_cpp_typemapping + select = ty == "IfcUtil::IfcBaseClass" + return arr and not simple and not express and not select + + def get_assignable_arguments(self, t, include_derived=False): + count = self.argument_count(t) + num_inherited = count - len(t.attributes) + derived = set(self.derived_in_supertype(t)) + attrs = enumerate(self.arguments(t)) + + def include(attr): + not_derived = include_derived or (attr.name not in derived) + supported = self.make_argument_type(attr) != "IfcUtil::Argument_UNKNOWN" + return not_derived and supported + + return [ + { + "index": i + 1, + "name": attr.name, + "full_type": self.get_parameter_type(attr), + "specialized_type": self.get_parameter_type(attr), + "non_optional_type": self.get_parameter_type(attr, allow_optional=False), + "list_instance_type": self.list_instance_type(attr), + "is_optional": attr.optional, + "is_inherited": i < num_inherited, + "is_enum": attr.type in self.schema.enumerations, + "is_array": self.is_array(attr.type), + "is_nested": self.is_array(attr.type) + and not isinstance(attr.type, str) + and self.is_array(attr.type.type), + "is_derived": attr.name in derived, + "is_templated_list": self.is_templated_list(attr), + "argument_type_enum": self.make_argument_type(attr), + "argument_entity": self.make_argument_entity(attr), + "argument_type": attr.type, + } + for i, attr in attrs + if include(attr) + ] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/nodes.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/nodes.py new file mode 100644 index 0000000000000000000000000000000000000000..34d3ef747b3007da1141e215af1f126d2021c554 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/nodes.py @@ -0,0 +1,585 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import io +import string +import operator +import collections +import bootstrap + +class Node: + def __init__(self, s, loc, tokens, rule=None): + self.rule = rule or (type(self).__name__) + self.tokens = tokens.asDict() + self.flat = sum([getattr(t, "flat", [t]) for t in tokens.asList()], []) + if rule is None: + self.init() + + def __repr__(self): + return "%s(%s)" % (self.rule, ",".join("%s:%s" % i for i in self.tokens.items())) + + def __getattr__(self, k): + return self.tokens.get(k) + + def __getstate__(self): + return self.__dict__ + + def __setstate__(self, d): + self.__dict__.update(d) + + def init(self): + pass + + def any(self): + return next(iter(self.tokens.values())) + + +class ListNode: + def __init__(self, s, loc, tokens, rule=None): + self.rule = rule or (type(self).__name__) + self.tokens = tokens.asList() + self.dict_tokens = collections.defaultdict(list) + + rules_as_list = set() + for t in self.tokens: + r = getattr(t, 'rule', None) + if r: + rules_as_list.add(r) + self.dict_tokens[r].append(t) + + for r, t in tokens.asDict().items(): + if r not in rules_as_list: + self.dict_tokens[r].append(t) + + self.flat = sum([getattr(t, "flat", [t]) for t in self.tokens], []) + + def __repr__(self): + return "%s[%s]" % (self.rule, ",".join("%s" % i for i in self.tokens)) + + def __iter__(self): + return iter(self.tokens) + + # Somehow indexing messes up the pyparsing results, so instead of x[0] use list(x)[0] + # def __getitem__(self, i): + # return self.tokens[i] + + def init(self): + pass + + +class SimpleType(Node): + def get_type(self): + t = self.any() + if type(t) == Node: + return t.any() + else: + t = t[0] + if type(t) == Node: + return t.any().any() + else: + return t + + type = property(get_type) + + def __repr__(self): + return str(self.type) + + +def format_clause(exp): + def whitespace(t): + if t in {"=", "|", "<*", "or", "in", "<>", "and"}: + return " %s " % t + return t + + return "".join(whitespace(term) for term in exp.flat) + + +class TypeDeclaration(Node): + name = property(lambda self: self.type_id[0]) + utype = property(lambda self: self.underlying_type.any().any()) + type = property(lambda self: self.utype[0] if isinstance(self.utype, list) else self.utype) + + def init(self): + + assert hasattr(self, "TYPE") + + self.where = [] + clause = self.where_clause + if clause: + clause = list(clause[0]) + + self.where = [(r.simple_id, format_clause(r.expression[0])) for r in clause[1::2]] + + def __repr__(self): + s = "TYPE %s = %s;\n" % (self.name, self.type) + if self.where: + s += " WHERE\n" + for nm_exp in self.where: + s += " %s : %s;\n" % nm_exp + s += "END_TYPE;" + return s + + +class EntityDeclaration(Node): + name = property(lambda self: self.entity_head[0].entity_id[0]) + supertype = property(lambda self: self.entity_head[0].subsuper[0].supertype_constraint) + subtype = property(lambda self: self.entity_head[0].subsuper[0].subtype_declaration) + supertypes = property(lambda self: [self.subtype.super_type] if self.subtype else []) + + def get_abstract(self): + if self.entity_head[0].subsuper[0].supertype_constraint: + return self.entity_head[0].subsuper[0].supertype_constraint.abstract + else: + return False + + abstract = property(get_abstract) + + def init(self): + def redeclared_attribute(a): + try: + return ( + a.attribute_decl.redeclared_attribute.qualified_attribute.group_qualifier.simple_id, + a.attribute_decl.redeclared_attribute.qualified_attribute.attribute_qualifier.simple_id, + ) + except: + return a.attribute_decl.simple_id + + assert self.flat[0] == "entity" + + self.attributes = [a for a in self.entity_body[0] if isinstance(a, ExplicitAttribute)] + self.inverse = [] + alist = [x for x in self.entity_body[0] if isinstance(x, AttributeList) and x.type == "inverse"] + if alist: + self.inverse = alist[0] + + self.derive = [] + alist = [x for x in self.entity_body[0] if isinstance(x, AttributeList) and x.type == "derive"] + if alist: + alist = alist[0] + self.derive = [(redeclared_attribute(a), format_clause(a.expression[0])) for a in alist] + + self.where = [] + clause = [r for r in self.entity_body[0] if r.rule == "where_clause"] + if clause: + clause = list(clause[0]) + + self.where = [(r.simple_id, format_clause(r.expression[0])) for r in clause[1::2]] + + self.unique = [] + clause = [r for r in self.entity_body[0] if r.rule == "unique_clause"] + if clause: + clause = clause[0] + self.unique = [(r[0], r[2].simple_id) for r in map(list, list(clause)[1::2])] + + def __repr__(self): + strm = io.StringIO() + + print("ENTITY %s" % self.name, file=strm) + + if self.supertype: + print("", self.supertype, file=strm) + if self.subtype: + print("", self.subtype, file=strm) + + strm.seek(strm.tell() - 1) + print(";", file=strm) + + for a in self.attributes: + print(" ", a, ";", file=strm, sep="") + + if self.derive: + print(" DERIVE", file=strm) + for nm, exp in self.derive: + if isinstance(nm, tuple): + nm = "SELF\\%s.%s" % nm + print(" %s : %s;" % (nm, exp), file=strm) + + if self.inverse: + print(" INVERSE", file=strm) + print(self.inverse, file=strm) + + if self.where: + print(" WHERE", file=strm) + for nm_exp in self.where: + print(" %s : %s;" % nm_exp, file=strm) + + if self.unique: + print(" UNIQUE", file=strm) + for nm_exp in self.unique: + print(" %s : %s;" % nm_exp, file=strm) + + print("END_ENTITY;", file=strm) + return strm.getvalue() + + +class EnumerationType(Node): + values = property(lambda self: list(self.enumeration_type[2])[1::2]) + + def __repr__(self): + return "ENUMERATION OF (" + ",".join(self.values) + ")" + + +class NamedType(Node): + type = property(lambda self: self.simple_id) + + def __repr__(self): + return self.type + + +def do_try(fn): + try: + return fn() + except: pass + + +def get_rule_id(x): + if not isinstance(x, str): + x = type(x).__name__ + matches = [k for k, v in bootstrap.actions.items() if v == x] + if matches: + return matches[0] + +rule_dependencies = { + k: list(map(operator.attrgetter('contents'), bootstrap.reduce(lambda x, y: x | y, (bootstrap.find_bytype(e, bootstrap.Keyword) for e in [v])))) \ + for k, v in bootstrap.express +} + +all_rules = [k for k, e in bootstrap.express] + +rule_definitions = {k: v for k, v in bootstrap.express} + +def to_tree(x, key=None): + + def prune(di): + # translate class names back to grammar rules if nested actions are encountered + di = {get_rule_id(k) or k: v for k, v in di.items()} + + def replace_synonyms(x): + for y in x: + yield y + if False: # y in di: + # production element from grammar is found in parsed data, + # return that. + + # we now always explore other synonym, because more often than not we loose data otherwise + yield y + else: + # lookup rule + rule = [e for k, e in bootstrap.express if k == y][0] + + def is_synonym(rl): + if isinstance(rl, bootstrap.Term) and isinstance(rl.contents, bootstrap.Keyword): + return rl.contents.contents + + # is this a synonym? then processs that + if S := is_synonym(rule): + yield S + # Do this recursively + yield from replace_synonyms([S]) + + # is this a concatenation with zero or more synonyms? then also processs that + # @todo catches: + # - simple_expression = term { add_like_op term } . + # but should probably also work on + # - a = b { b } + # in which case the second Concat would be eliminated + elif isinstance(rule, bootstrap.Concat) and \ + len(rule.contents) == 2 and \ + is_synonym(rule.contents[0]) and \ + isinstance(rule.contents[1].contents, bootstrap.Repeated) and \ + isinstance(rule.contents[1].contents.contents[0], bootstrap.Concat) and \ + str(rule.contents[1].contents.contents[0].contents[1]) == str(rule.contents[0]): + S = is_synonym(rule.contents[0]) + yield S + # Do this recursively + yield from replace_synonyms([S]) + + subrules = list(replace_synonyms(rule_dependencies[key])) + + if key == "aggregation_types": + # hack hack hack apparently the parser can't distinguish these + subrules += list(replace_synonyms(rule_dependencies["general_aggregation_types"])) + + if rule_dependencies[key] and not subrules: + # sometimes an intermediate production rule is missing + # from the pyparsing output, e.g from parameter to simple_expression + # directly. Recover from this. + subrules = sum(map(rule_dependencies.__getitem__, rule_dependencies[key]), []) + + if not isinstance(rule_definitions[key], bootstrap.Union): + # Filter out terminals when not a union. E.g no + # reason to retain TYPE, END_TYPE, but operators + # such as IN, LIKE should be retained. + subrules = list(filter(str.islower, subrules)) + + vs = list(di.values()) + + return {k: v for k, v in di.items() if k in subrules or (k == key and len(vs) == 1 and vs[0] not in all_rules)} + + def simplify(di): + if isinstance(di, list): + if set(map(type, di)) == {str} and set(map(len, di)) == {1}: + return "".join(di) + return [simplify(v) for v in di] + elif isinstance(di, dict) and len(di) == 1 and next(iter(di.values())) == {}: + return next(iter(di.keys())) + elif isinstance(di, dict): + return {k: simplify(v) for k, v in di.items()} + else: + return di + + if isinstance(x, ListNode): + d = to_tree(x.dict_tokens, key=get_rule_id(x) or key) + + if key == 'if_stmt': + # The definition of if statement if (roughy): + # 'if' expr 'then' stmt+ 'else' stmt+ + # this causes stmt to be joined under the same + # dict key. The code below creates an artifical + # `else_stmt` that collects the second group + # of stmts. + + statements = x.dict_tokens['stmt'] + + else_index = None + if_nesting = 0 + for i, tk in enumerate(x.flat): + if tk == 'if': if_nesting += 1 + if tk == 'end_if': if_nesting -= 1 + if tk == 'else' and if_nesting == 1: + else_index = i + + if else_index: + indices = [] + for s in statements: + for i in range(max(indices, default=0), len(x.flat)): + if x.flat[i:i+len(s.flat)] == s.flat: + indices.append(i) + break + + assert len(indices) == len(statements) + before_else = [i < else_index for i in indices] + + else_stmt = [st for b, st in zip(before_else, d['stmt']) if not b] + d['stmt'] = [st for b, st in zip(before_else, d['stmt']) if b] + + if else_stmt: + d['else_stmt'] = else_stmt + + if key == 'formal_parameter': + # Not so pretty hack to fix the overwriting of simple_id-like + # ast nodes. The full solution would probably to register parse + # actions. And directly reassign. + pid = d['parameter_id'][0][0] + d['parameter_id'][0] = x.flat[:x.flat.index(pid)+1:2] + + if key is None: + return {get_rule_id(x): d} + return d + elif isinstance(x, Node): + d = to_tree(x.tokens, key=get_rule_id(x) or key) + if key is None: + return {get_rule_id(x): d} + return d + elif isinstance(x, dict): + # d = {k: to_tree(v, key=k) for k, v in x.items()} + # not fully understood, but when finding specific node Types and production rules, prioritize the former + d = {get_rule_id(k) or k: to_tree(v, key=k) for k, v in sorted(x.items(), key=lambda p: get_rule_id(p[0]) is not None)} + return simplify(prune(d)) + elif isinstance(x, list): + return [to_tree(v, key=key) for v in x] + else: + return x + + +class AggregationType(Node): + aggregate_type = property(lambda self: self.flat[0]) + bounds = property(lambda self: (list(self.tokens.values())[0][0].bound_spec or [None])[0]) + unique = property(lambda self: list(self.tokens.values())[0][0].UNIQUE is not None) + + def get_type(self): + v = list(self.tokens.values())[0][0] + if v.instantiable_type: + try: + return v.instantiable_type.concrete_types.simple_id or v.instantiable_type.concrete_types.simple_types + except: + return v.instantiable_type + elif v.parameter_type.simple_types: + return v.parameter_type.simple_types + elif v.parameter_type.named_types: + return v.parameter_type.named_types + elif v.parameter_type.generalized_types.general_aggregation_types: + return v.parameter_type.generalized_types.general_aggregation_types + elif do_try(lambda: v.parameter_type.generalized_types.generic_type.generic_type[0].GENERIC): + return do_try(lambda: v.parameter_type.generalized_types.generic_type.generic_type[0].GENERIC) + else: + import pdb + + pdb.set_trace() + raise ValueError() + + type = property(get_type) + + def init(self): + assert self.bounds is None or isinstance(self.bounds, BoundSpecification) + + def __repr__(self): + return "%s%s of %s%s" % (self.aggregate_type, self.bounds, "unique " if self.unique else "", self.type) + + +class SelectType(Node): + values = property(lambda self: list(self.select_type[1])[1::2]) + + def __repr__(self): + return "SELECT (" + ",".join(map(str, self.values)) + ")" + + +class SuperTypeExpression(Node): + abstract = property(lambda self: self.abstract_supertype_declaration is not None) + + def get_sub_types(self): + if self.abstract: + constraint = self.abstract_supertype_declaration[0] + else: + constraint = self.supertype_rule[0] + return [ + list(list(s)[0])[0].simple_id for s in list(list(list(constraint.subtype_constraint[0].supertype_expression[0])[0])[0].one_of[0])[2::2] + ] + + sub_types = property(get_sub_types) + + def __repr__(self): + return "%sSUPERTYPE OF(ONEOF(%s))" % ("ABSTRACT " if self.abstract else "", ",".join(self.sub_types)) + + +class SubTypeExpression(Node): + super_type = property(lambda self: self.entity_ref[0]) + + def __repr__(self): + return "SUBTYPE OF(%s)" % self.super_type + + +class AttributeList(ListNode): + type = property(lambda self: self.flat[0] if self.flat[0] in {"inverse", "derive"} else "explicit") + + def __repr__(self): + return "\n".join([" %s;" % s for s in self.tokens[1:]]) + + def __iter__(self): + return iter(self.tokens[1:]) + + def __len__(self): + return len(self.tokens[1:]) + + +class InverseAttribute(Node): + name = property(lambda self: self.attribute_decl.simple_id) + type = property(lambda self: self.flat[2] if self.flat[2] != self.flat[-4] else None) + bounds = property(lambda self: self.bound_spec[0] if self.bound_spec else None) + entity = property(lambda self: self.entity_ref[0]) + attribute = property(lambda self: self.attribute_ref[0]) + + def __repr__(self): + def _(): + yield self.name + yield ":" + if self.type: + yield self.type.upper() + yield "OF" + if self.bounds: + yield self.bounds + yield self.entity + yield "FOR" + yield self.attribute + + return " ".join(map(str, _())) + + +""" +class DerivedAttribute(Node): + def init(self): + return + name_index = list(self.tokens).index(':') - 1 + self.name = self.tokens[name_index] + def __repr__(self): + return str(self.name) +""" + + +class BinaryType(Node): + def __repr__(self): + return "binary" + + +class BoundSpecification(Node): + lower = property(lambda self: self.flat[1]) + upper = property(lambda self: self.flat[3]) + + def __repr__(self): + return "[%s:%s]" % (self.lower, self.upper) + + +class ExplicitAttribute(Node): + name = property(lambda self: self.attribute_decl.simple_id) + optional = property(lambda self: self.OPTIONAL is not None) + + def get_type(self): + v = next(iter(self.parameter_type.tokens.values())) + if v.general_aggregation_types: + return v.general_aggregation_types + else: + return v + + type = property(get_type) + + def __repr__(self): + return "%s : %s%s" % (self.name, "optional " if self.optional else "", self.type) + + +class WidthSpec(Node): + fixed = property(lambda self: self.FIXED is not None) + + def init(self): + self.width = int("".join(list(self.width)[0].flat)) + + def __repr__(self): + return "(%d)%s" % (self.width, " fixed" if self.fixed else "") + + +class StringType(Node): + width = property(lambda self: self.width_spec[0] if self.width_spec else None) + + def __repr__(self): + s = "string" + if self.width: + s += " " + repr(self.width) + return s + + +class ProcedureDeclaration(ListNode): + @property + def name(self): + return self.flat[1] + + +class FunctionDeclaration(ProcedureDeclaration): + pass + +class RuleDeclaration(ProcedureDeclaration): + pass diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_compiler.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_compiler.py new file mode 100644 index 0000000000000000000000000000000000000000..ab6caf93f86f740350a7e29ff417038a0df6ca30 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_compiler.py @@ -0,0 +1,1063 @@ +import ast +import os +import re +import sys +import json +import hashlib +import operator +import functools +import itertools + +import ifcopenshell.express +import ifcopenshell.express.express_parser + +import networkx as nx + +from codegen import indent + +DEBUG = False + + +def to_graph(tree): + g = nx.DiGraph() + + # Convert + def write_to_graph(val, name=None): + if isinstance(val, list): + pairs = ((None, v) for v in val) + elif isinstance(val, dict): + pairs = val.items() + else: + assert name + g.add_edge(name, name + "_value") + return g.add_node(name + "_value", label=val) + + for i, (k, v) in enumerate(pairs): + i = f"{i:03d}" + nid = f"{name or 'root'}/{k or i}" + g.add_node(nid, label=k) + if name: + g.add_edge(name, nid) + write_to_graph(v, nid) + + write_to_graph(tree) + + to_remove = set() + + # Remove intermediate anonymous nodes. Often the result of ZeroOrMore() productions in + # bootstrap.py that result in an intermediate list index node in to_tree() + + # Start with the intermediate nodes and filter out root (needs to have predecessors) + intermediate = [ + n + for n in g.nodes + if g.nodes[n].get("label") is None and list(g.predecessors(n)) + ] + + for n in intermediate: + pr = list(g.predecessors(n)) + if len(pr) == 1 and g.nodes[pr[0]].get("label"): + # when eliminating a grouping node with heterogeneous content + # rather copy the predecessor node label to the grouping node + # and later delete the predecessor + sc = list(g.successors(n)) + if len(sc) > 1: + sc_labels = list(map(lambda x: g.nodes[x].get("label"), sc)) + if len(set(sc_labels)) > 1 and None not in sc_labels: + g.nodes[n]["label"] = g.nodes[pr[0]].get("label") + to_remove.add(pr[0]) + continue + + for ab in itertools.product(g.predecessors(n), g.successors(n)): + g.add_edge(*ab) + g.remove_node(n) + + # The removal process above can decide to not fold the anonymous node, but rather + # the predecessor of it, in which case it is deleted in this step. + for n in to_remove: + for ab in itertools.product(g.predecessors(n), g.successors(n)): + g.add_edge(*ab) + g.remove_node(n) + + for n in g.nodes: + if ( + len(list(g.successors(n))) == 0 + and g.nodes[n].get("label") + not in ifcopenshell.express.express_parser.all_rules + ): + g.nodes[n]["is_terminal"] = True + + return g + + +def write_dot(fn, g): + + with open(fn, "w") as f: + + def w(*args, **kwargs): + print(*args, file=f, **kwargs) + + w("digraph", "{") + + def nodename(n): + return "N" + hashlib.md5(n.encode()).hexdigest() + + def format(di): + Q = '"' + inner = ",".join( + f"{k}={'' if v.startswith('<') else Q}{v}{'' if v.startswith('<') else Q}" + for k, v in di.items() + ) + if inner: + inner = f"[{inner}]" + return inner + + for n in g.nodes: + lbl = g.nodes[n].get("label") + if lbl: + attrs = {"label": lbl} + else: + attrs = {"label": n} + + if g.nodes[n].get("is_terminal"): + attrs["shape"] = "rect" + attrs["label"] = f"\\\"{attrs['label']}\\\"" + else: + attrs["shape"] = "none" + + w(nodename(n), format(attrs), ";", sep="") + + for a, b in g.edges: + w(nodename(a), "->", nodename(b), ";") + + w("}", flush=True) + + +from pyparsing import * + +SLASH = Suppress("/") +identifier = Word(alphanums + "_") +rule = identifier + (ZeroOrMore(SLASH + identifier)) + + +def paths(G, root, length): + if length == 1: + yield (G.nodes[root].get("label"),) + return + + sd = dict(nx.bfs_successors(G, root, depth_limit=length - 1)) + + def r(x, p=None): + if p and len(p) == length: + yield tuple(map(lambda n: G.nodes[n].get("label"), p)) + else: + for y in sd.get(x, []): + yield from r(y, (p or [x]) + [y]) + + yield from r(root) + + +class context: + def __init__(self, graph, rules): + self.graph = graph + self.rules = rules + + def __getattr__(self, k): + def inner(): + for r in self.rules: + label_id_pairs = map( + lambda n: (self.graph.nodes[n].get("label"), n), + # itertools.chain.from_iterable( + # dict(nx.bfs_successors(self.graph, r)).values() + # ) + self.graph.successors(r), + ) + matching = filter(lambda p: p[0] == k, label_id_pairs) + yield from map(operator.itemgetter(1), matching) + + return context(self.graph, list(inner())) + + def has_inverse(self, a): + for r in self.rules: + if a in map( + lambda n: self.graph.nodes[n].get("label"), self.graph.predecessors(r) + ): + return True + return False + + def __iter__(self): + for r in self.rules: + yield context(self.graph, [r]) + + def descendants(self): + return [ + b.rules[0][len(self.rules[0]) + 1 :] + for b in self.branches(allow_multiple=True) + ] + + def __repr__(self): + try: + s = "\n\n" + str(self) + except: + s = "" + return f"{s}" + + def __str__(self): + assert len(self.rules) == 1 + nodes = itertools.chain( + self.rules, + itertools.chain.from_iterable( + dict(nx.bfs_successors(self.graph, self.rules[0])).values() + ), + ) + terminals_or_values = list( + filter( + lambda n: self.graph.nodes[n].get("is_terminal") + or self.graph.nodes[n].get("value"), + nodes, + ) + ) + # assert len(terminals) == 1 + attrs = [self.graph.nodes[tv] for tv in terminals_or_values] + attrs = [a.get("value", a["label"]) for a in attrs] + attr_types = list(map(type, attrs)) + if empty in attr_types[0:1]: + return "" + attrs = list(filter(lambda s: isinstance(s, str), attrs)) + return attrs[0] + + def __eq__(self, other): + return self.graph == other.graph and self.rules == other.rules + + def __hash__(self): + return hash(self.rules) + + def branches(self, allow_multiple=False, exclude=()): + if not allow_multiple: + assert len(self.rules) == 1 + combined = sum( + [ + sorted( + (context(self.graph, [n]) for n in self.graph.successors(R)), + key=lambda c: c.rules[0] if c.rules else "", + ) + for R in self.rules + ], + [], + ) + return [c for c in combined if c not in exclude] + + def parent(self): + assert len(self.rules) == 1 + return context(self.graph, list(self.graph.predecessors(self.rules[0]))) + + def branch(self, i): + return self.branches()[i] + + def __len__(self): + return len(self.rules) + + def __getitem__(self, k): + return list(self)[k] + + def key(self): + parts = list( + map( + lambda s: tuple(map(lambda p: "n" if p.isdigit() else p, s.split("/"))), + self.rules, + ) + ) + assert len(set(parts)) == 1 + return [x for x in parts[0][::-1] if x != "n"][0] + + +# @todo +context_class = context + + +class codegen_rule: + def __init__(self, pattern, fn): + self.pattern = tuple(rule.parseString(pattern)) + self.fn = fn + if not hasattr(codegen_rule, "all_rules"): + codegen_rule.all_rules = [] + codegen_rule.all_rules.append(self) + + def __call__(self, graph, node): + # try: + v = self.fn(context(graph, [node])) + # except: + # v = "ERROR!!" + graph.nodes[node]["value"] = v + return v + + @staticmethod + def apply(G): + v = None + for n in reversed(list(nx.topological_sort(G))): + for r in codegen_rule.all_rules: + if r.pattern in paths(G, n, len(r.pattern)): + v = r(G, n) + return v + + +def process_rule_decl(context): + return f""" +class {context.rule_head.rule_id}: + SCOPE = "file" + + @staticmethod + def __call__(file): + {context.rule_head.entity_ref} = file.by_type("{context.rule_head.entity_ref}") +{indent(8, context.algorithm_head.local_decl)} +{indent(8, context.stmt.branches()) if context.stmt else ''} +{indent(8, context.where_clause.domain_rule)} +""" + + +class empty: + pass + + +wb = r"\b" + + +def process_type_decl(scope, context): + class_name = context.type_id if scope == "type" else context.entity_head.entity_id + + attributes = [] + + if scope == "entity": + + def get_attributes(nm): + ent = schema.entities[nm] + if ent.supertypes: + yield from get_attributes(ent.supertypes[0]) + yield from [a.name for a in ent.attributes] + yield from [a.name for a in ent.inverse] + # redeclared do not need to be printed, because they're emitted + # as part of supertype + yield from [a[0] for a in ent.derive if isinstance(a[0], str)] + + # @todo derived and inverse attributes + attributes = list(get_attributes(class_name)) + + def format_rule(domain_rule): + return f""" +class {class_name}_{domain_rule.rule_label_id}: + SCOPE = "{scope}" + TYPE_NAME = "{class_name}" + RULE_NAME = "{domain_rule.rule_label_id}" + + @staticmethod + def __call__(self): +{indent(8, (f"{a.lower()} = self.{a}" for a in attributes if re.search(f'{wb}{a.lower()}{wb}', str(domain_rule))))} +{indent(8, domain_rule)} +""" + + rule_parent = context if scope == "type" else context.entity_body + + statements = [] + + if rule_parent.where_clause: + # @todo should we not try to maintain a 1-1 correspondence? + statements.extend(map(format_rule, rule_parent.where_clause.branches())) + + if scope == "entity": + + def format_derived(derived_attr): + slash = "\\" + return f""" +def calc_{class_name}_{str(derived_attr.attribute_decl.redeclared_attribute.qualified_attribute.attribute_qualifier)[1:] if derived_attr.attribute_decl.redeclared_attribute else derived_attr.attribute_decl}(self): +{indent(4, (f"{a.lower()} = self.{a}" for a in attributes if re.search(f'{wb}{a.lower()}{wb}', str(derived_attr.expression))))} +{indent(4, f"return {slash}")} +{indent(4, derived_attr.expression)} +""" + + if context.entity_body.derive_clause: + statements.extend( + map(format_derived, context.entity_body.derive_clause.branches()) + ) + + return "\n\n".join(statements) + + +def process_domain_rule(context): + return f""" +assert ({context.expression}) is not False +""" + + +def wrap_parens(s): + s = str(s) + if " " in s: + s = "(%s)" % s + return s + + +def process_expression(context): + def concat(a, b, **kwargs): + return " ".join( + map( + str, + sum( + zip( + [None] + a.branches(**kwargs), + map(wrap_parens, b.branches(**kwargs)), + ), + (), + )[1:], + ) + ) + + if context.rel_op_extended: + if context.term: + # IfcSameValue + return concat( + context.rel_op_extended, + context, + allow_multiple=True, + exclude=[context.rel_op_extended], + ) + else: + if len(context.simple_expression.branches()) == 2 and str(context.rel_op_extended) == 'in': + # IfcBlobTexture + try: + is_literal_str_list = set(map(type, ast.literal_eval(str(context.simple_expression.branches()[1])))) == {str} + except: + is_literal_str_list = False + if is_literal_str_list: + a, b = map(str, context.simple_expression.branches()) + return f"{a}.lower() {str(context.rel_op_extended)} {b}" + return concat(context.rel_op_extended, context.simple_expression) + elif context.multiplication_like_op: + if str(context.multiplication_like_op.branches()[0]) == "||": + all_args = {} + most_concrete_type = None + most_concrete_type_inheritance_chain_length = -1 + + for s in context.factor.branches(): + typename, args = str(s).split("(", 1) + args = args[:-1] + + break_points = [[0]] + bracket_nesting = 0 + for i, tk in enumerate(args): + if tk in "[(": + bracket_nesting += 1 + if tk in ")]": + bracket_nesting -= 1 + if tk == "," and bracket_nesting == 0: + break_points[-1].append(i) + break_points.append([i + 1]) + + break_points[-1].append(len(args)) + + # @todo don't depend on registered schema + S = ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema.name) + entity = S.declaration_by_name(typename) + entity_attributes = entity.attributes() + + def count_chain_length(ent): + length = 0 + while ent: + ent = ent.supertype() + length += 1 + return length + + args = [args[slice(*x)] for x in break_points] + + for i, arg in filter(lambda p: p[1], enumerate(args)): + all_args[entity_attributes[i].name()] = arg + + cl = count_chain_length(entity) + if cl > most_concrete_type_inheritance_chain_length: + most_concrete_type = entity.name() + most_concrete_type_inheritance_chain_length = cl + + return f"{most_concrete_type}({', '.join(f'{a[0]}={a[1]}' for a in all_args.items())})" + else: + return concat(context.multiplication_like_op, context.factor) + elif context.add_like_op: + if context.factor or len(context.term) > 1: + # @todo now sure why this is required (in IfcCrossProduct) + # @todo not sure what's going on here, why we have both factor and term as direct child productions of simple_expression (in IfcDotProduct) + return concat( + context.add_like_op, + context, + allow_multiple=True, + exclude=[context.add_like_op], + ) + else: + return concat(context.add_like_op, context.term) + + +def process_interval(context): + op0, op1 = context.interval_op.branches() + return " ".join( + map( + str, + ( + context.interval_low, + op0, + context.interval_item, + op1, + context.interval_high, + ), + ) + ) + + +def simple_concat(context): + # simple_factor: + # only to join unary op (-) with number literal + # primary: + # only to join index with qualifyable operand + + def qualifier_position(s): + # @todo this is a really ugly hack, can we not depend on stable branch order and why? + + # unary operators + if s in ("-", "+", "not"): + return -1 + + # qualifiers + if s and s[0] in (".", "["): + return 1 + + # default + return 0 + + branches = sorted(map(str, context.branches()), key=qualifier_position) + + # sorting no longer necessary as we sort in branches() now + # correction: still necessary, apparently. + # branches = list(map(str, context.branches())) + + if len(branches) == 2 and branches[0] == "not": + return f"{branches[0]} {wrap_parens(branches[1])}" + else: + v = "".join(branches) + + return v + + +def process_rel_op(context): + # @todo the distinction between value comparison and instance comparison + if str(context) == "<>" or str(context) == ":<>:": + return "!=" + elif str(context) == "=" or str(context) == ":=:": + return "==" + + +def process_if_stmt(context): + s = f"if {context.logical_expression if context.logical_expression.branches() else context.expression}:\n{indent(4, context.stmt.branches())}" + if context.else_stmt: + s += f"\nelse:\n{indent(4, context.else_stmt.branches())}" + return s + + +def process_repeat_stmt(context): + ic = context.repeat_control.increment_control + return f"for {ic.variable_id} in range({ic.bound_1}, {ic.bound_2} + 1):\n{indent(4, context.stmt.branches())}" + + +def process_function_decl(context): + arguments = map( + str.lower, + map( + str, + context.function_head.formal_parameter.parameter_id.branches( + allow_multiple=True + ), + ), + ) + return f"def {context.function_head.function_id}({', '.join(arguments)}):\n{indent(4, context.algorithm_head.local_decl)}\n{indent(4, context.stmt.branches())}" + + +def process_query(context): + return f"[{str(context.variable_id).lower()} for {str(context.variable_id).lower()} in {context.aggregate_source} if {context.logical_expression if context.logical_expression and context.logical_expression.branches() else context.expression}]" + + +def process_local_variable(context): + if context.expression: + expr = str(context.expression) + if ( + context.parameter_type.generalized_types.general_aggregation_types.general_set_type + ): + expr = re.sub(r"(\[[^\]]*\])", "express_set(\\1)", expr) + + return "%s = %s" % (str(context.variable_id).lower(), expr) + else: + return empty() + + +def process_function_call(context): + nm = f"{context.built_in_function if context.built_in_function else context.function_ref}" + args = f"{context.actual_parameter_list if context.actual_parameter_list and context.actual_parameter_list.branches() else ''}" + if nm == "exists" and "[" in args: + # exists check if it receives a callable to catch IndexError, because express semantics + # dictate that out of bounds index returned unknown (IfcTypeObject_WR1) + wrap = "lambda: " + else: + wrap = "" + return f"{nm}({wrap}{args})" + + +def make_lowercase(context): + return str(context).lower() + + +def make_lowercase_if(fn): + def inner(context): + if fn(context): + return make_lowercase(context) + + return inner + + +def process_assignment(context): + lhs = str(context.general_ref) + if context.qualifier: + lhs += str(context.qualifier) + if m := re.match(r"^([^\[]+)\[([^\[]+)\]$", lhs): + # @todo ugly regex hack + aggr, index = m.groups() + return ( + f"temp = list({aggr})\ntemp[{index}] = {context.expression}\n{aggr} = temp" + ) + else: + return "%s = %s" % (lhs, context.expression) + + +def process_case_action(context): + first = context.parent().branches().index(context) + pred = "elif" if first else "if" + if re.match(r"^'[a-z0-9]+'$", str(context.expression)): + # @todo this is yet again an ugly hack + lower = ".lower()" + else: + lower = "" + return f"{pred} {context.parent().expression}{lower} == {context.expression}:\n{indent(4, context.stmt.branches())}" + + +def process_case_statement(context): + branches = context.branches( + exclude=[ + getattr(context, v) + for v in context.descendants() + if not v.startswith("case_action") + ] + ) + if context.stmt and context.stmt.branches(): + branches += [f"else:\n{indent(4, context.stmt)}"] + return "\n".join(map(str, branches)) + + +def process_aggregate_initializer(context): + if context.element.repetition: + return "([%s] * %s)" % (context.element.expression, context.element.repetition) + else: + return "[%s]" % ",".join( + map(str, context.element.branches() if context.element else ()) + ) + + +def process_index(context): + if context.parent().key() == "index_qualifier": + return context + else: + return "[%s - EXPRESS_ONE_BASED_INDEXING]" % context + + +# implemented sizeof() function in generated code +# codegen_rule("built_in_function/SIZEOF", lambda context: f"len") +# @todo +codegen_rule("function_call", process_function_call) +codegen_rule( + "actual_parameter_list", + lambda context: ",".join( + map(str, context.expression.branches() if context.expression else []) + ), +) +codegen_rule("entity_decl", functools.partial(process_type_decl, "entity")) +codegen_rule("rule_decl", process_rule_decl) +codegen_rule("type_decl", functools.partial(process_type_decl, "type")) +codegen_rule("function_decl", process_function_decl) +codegen_rule("domain_rule", process_domain_rule) +codegen_rule("expression", process_expression) +codegen_rule("simple_expression", process_expression) +codegen_rule("logical_expression", process_expression) +codegen_rule("term", process_expression) +codegen_rule("query_expression", process_query) +codegen_rule("aggregate_initializer", process_aggregate_initializer) +codegen_rule("interval", process_interval) +codegen_rule("simple_factor", simple_concat) +codegen_rule("primary", simple_concat) +codegen_rule("qualifier", simple_concat) +codegen_rule("return_stmt", lambda context: "return %s" % context) +codegen_rule( + "compound_stmt", lambda context: "\n".join(map(str, context.stmt.branches())) +) +codegen_rule("if_stmt", process_if_stmt) +codegen_rule("repeat_stmt", process_repeat_stmt) +# codegen_rule("index", lambda context: '**express_index(%s)' % context) +codegen_rule("index", process_index) +codegen_rule("index_qualifier", process_index) +codegen_rule("group_qualifier", lambda context: empty()) +codegen_rule("attribute_qualifier", lambda context: ".%s" % context) +codegen_rule("rel_op", process_rel_op) +codegen_rule( + "built_in_constant", lambda context: "None" if str(context) == "?" else str(context) +) +codegen_rule("assignment_stmt", process_assignment) +codegen_rule("local_variable", process_local_variable) +codegen_rule("local_decl", lambda context: "\n".join(map(str, context.branches()))) +codegen_rule("general_ref/parameter_ref", make_lowercase) +codegen_rule( + "qualifiable_factor/attribute_ref", + make_lowercase_if( + lambda context: str(context) + not in set(map(str, schema.all_declarations.keys())) + ), +) +codegen_rule("case_action", process_case_action) +codegen_rule("case_stmt", process_case_statement) +codegen_rule("escape_stmt", lambda context: "break") + +codegen_rule("XOR", lambda context: "^") +codegen_rule("MOD", lambda context: "%") +codegen_rule("TRUE", lambda context: "True") +codegen_rule("FALSE", lambda context: "False") + + +class AttributeGetattrTransformer(ast.NodeTransformer): + def visit_Attribute(self, node): + parents = [] + n = node + while n := getattr(n, "parent", 0): + parents.append(n) + + custom_funcs = "is_entity", "usedin", "express_len", "express_getitem", "typeof" + function_defs = [p.name for p in parents if isinstance(p, ast.FunctionDef)] + if any(fn in function_defs for fn in custom_funcs): + return node + + # Check if the Attribute node is the target of an assignment statement + if isinstance(node.ctx, ast.Store): + return node + + if node.attr == "create_entity": + return node + + new_value = self.visit(node.value) + + # Replace the Attribute node with a call to the built-in `getattr` function + return ast.copy_location( + ast.Call( + func=ast.Name(id="getattr", ctx=ast.Load()), + args=[ + new_value, + ast.Str(s=node.attr), + ast.Name(id="INDETERMINATE", ctx=ast.Load()), + ], + keywords=[], + ), + node, + ) + + def visit_Subscript(self, node): + parents = [] + n = node + while n := getattr(n, "parent", 0): + parents.append(n) + + custom_funcs = "is_entity", "usedin", "express_len", "express_getitem", "typeof" + function_defs = [p.name for p in parents if isinstance(p, ast.FunctionDef)] + if any(fn in function_defs for fn in custom_funcs): + return node + + # Check if the Attribute node is the target of an assignment statement + if isinstance(node.ctx, ast.Store): + return node + + assert ( + isinstance(node.slice, ast.Name) + or isinstance(node.slice, ast.Constant) + or isinstance(node.slice, ast.BinOp) + ) + + new_value = self.visit(node.value) + + # Replace the Attribute node with a call to the built-in `getattr` function + return ast.copy_location( + ast.Call( + func=ast.Name(id="express_getitem", ctx=ast.Load()), + args=[ + new_value, + node.slice, + ast.Name(id="INDETERMINATE", ctx=ast.Load()), + ], + keywords=[], + ), + node, + ) + + def assign_parent_refs(self, tree): + for node in ast.walk(tree): + for child in ast.iter_child_nodes(node): + child.parent = node + + +if __name__ == "__main__": + import io + import sys + import shutil + import subprocess + + schema = ifcopenshell.express.express_parser.parse(sys.argv[1]).schema + + try: + ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema.name) + except: + # @nb note the difference here between: + # + # - ifcopenshell.express.express_parser.parse + # - ifcopenshell.express.parse.parse + # + # First generates a pyparsing AST + # + # Second populates a latebound schema + # that can be registered in C++. + builder = ifcopenshell.express.parse(sys.argv[1]) + ifcopenshell.register_schema(builder) + + try: + ofn = sys.argv[2] + except IndexError as e: + ofn = os.path.join(os.path.dirname(__file__), "rules", f"{schema.name}.py") + output = io.StringIO() + + print("import ifcopenshell", file=output, sep="\n") + + print( + """ +def exists(v): + if callable(v): + try: return v() is not None + except IndexError as e: return False + else: return v is not None +""", + "\n", + file=output, + sep="\n", + ) + print( + "def nvl(v, default): return v if v is not None else default", + "\n", + file=output, + sep="\n", + ) + + print( + """ +def is_entity(inst): + if isinstance(inst, ifcopenshell.entity_instance): + schema_name = inst.is_a(True).split('.')[0].lower() + decl = ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(inst.is_a()) + return isinstance(decl, ifcopenshell.ifcopenshell_wrapper.entity) + return False + +def express_len(v): + if isinstance(v, ifcopenshell.entity_instance) and not is_entity(v): + v = v[0] + elif v is None or v is INDETERMINATE: + return INDETERMINATE + return len(v) + +old_range = range + +def range(*args): + if INDETERMINATE in args: + return + yield from old_range(*args) + +sizeof = express_len +hiindex = express_len +blength = express_len +""", + file=output, + sep="\n", + ) + + print("loindex = lambda x: 1", file=output, sep="\n") + print("from math import *", file=output, sep="\n") + + # @todo this will get us in trouble when evaluating the truthness + print("unknown = 'UNKNOWN'", file=output, sep="\n") + + print( + """ +def usedin(inst, ref_name): + if inst is None: + return [] + _, __, attr = ref_name.split('.') + def filter(): + for ref, attr_idx in inst.wrapped_data.file.get_inverse(inst, allow_duplicate=True, with_attribute_indices=True): + if ref.wrapped_data.get_attribute_names()[attr_idx].lower() == attr: + yield ref + return list(filter()) + + +class express_set(set): + def __mul__(self, other): + return express_set(set(other) & self) + __rmul__ = __mul__ + def __add__(self, other): + def make_list(v): + # Comply with 12.6.3 Union operator + if isinstance(v, (list, tuple, set, express_set)): + return list(v) + else: + return [v] + return express_set(list(self) + make_list(other)) + __radd__ = __add__ + def __repr__(self): + return repr(set(self)) + def __getitem__(self, k): + # @todo this is obviously not stable, but should be good enough? + return list(self)[k] + + +def express_getitem(aggr, idx, default): + if aggr is None: return default + if isinstance(aggr, ifcopenshell.entity_instance) and not is_entity(aggr): + aggr = aggr[0] + try: return aggr[idx] + except IndexError as e: return None + + +EXPRESS_ONE_BASED_INDEXING = 1 + + +def typeof(inst): + if not inst: + # If V evaluates to indeterminate (?), an empty set is returned. + return express_set([]) + schema_name = inst.is_a(True).split('.')[0].lower() + def inner(): + decl = ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema_name).declaration_by_name(inst.is_a()) + while decl: + yield '.'.join((schema_name, decl.name().lower())) + if isinstance(decl, ifcopenshell.ifcopenshell_wrapper.entity): + decl = decl.supertype() + else: + decl = decl.declared_type() + while isinstance(decl, ifcopenshell.ifcopenshell_wrapper.named_type): + decl = decl.declared_type() + if not isinstance(decl, ifcopenshell.ifcopenshell_wrapper.type_declaration): + break + return express_set(inner()) + +class indeterminate_type: + def __bool__(self): + return False + def bop(self, *other): + return self + __lt__= bop + __le__= bop + __eq__= bop + __ne__= bop + __gt__= bop + __ge__= bop + __add__= bop + __radd__= bop + __sub__= bop + __rsub__= bop + __mul__= bop + __rmul__= bop + __truediv__= bop + __floordiv__= bop + __rtruediv__= bop + __rfloordiv__= bop + __mod__= bop + __rmod__= bop + __pow__= bop + __rpow__= bop + __neg__= bop + __pos__= bop + __getitem__ = bop + __getattr__ = bop + def __iter__(self): + return iter(()) + +INDETERMINATE = indeterminate_type() + +""", + file=output, + sep="\n", + ) + + print( + "class enum_namespace:\n def __getattr__(self, k):\n return k.upper()", + "\n", + file=output, + sep="\n", + ) + + for k, v in schema.enumerations.items(): + print(f"{k} = enum_namespace()", "\n", file=output, sep="\n") + + for vi in v.values: + print(f"{vi.lower()} = {k}.{vi}", "\n", file=output, sep="\n") + + for k in schema.entities.keys(): + print( + f"def {k}(*args, **kwargs): return ifcopenshell.create_entity({k!r}, {schema.name!r}, *args, **kwargs)", + "\n", + file=output, + sep="\n", + ) + + for nm in schema.all_declarations.keys(): + print(nm) + + tree = ifcopenshell.express.express_parser.to_tree(schema[nm]) + + if DEBUG: + with open(f"{nm}.json", "w") as f: + json.dump(tree, f, indent=2) + + G = to_graph(tree) + rule_code = codegen_rule.apply(G) + + if DEBUG: + for n in G.nodes.values(): + if v := n.get("value"): + if isinstance(v, str): + nl = "\n" + es = "\\n" + n[ + "label" + ] = f'<
    {n.get("label")}
    {v.replace("<", "<").replace(">", ">").replace(nl, "
    ")}
    >' + elif isinstance(v, empty): + n[ + "label" + ] = f'<
    {n.get("label")}
    ---
    >' + + fn = f"{nm}.dot" + write_dot(fn, G) + subprocess.call([shutil.which("dot") or "dot", fn, "-O", "-Tpng"]) + + print(rule_code, "\n", file=output, sep="\n") + + tree = ast.parse(output.getvalue()) + trsf = AttributeGetattrTransformer() + trsf.assign_parent_refs(tree) + trsf.visit(tree) + + if ofn == "-": + print(ast.unparse(tree)) + else: + with open(ofn, "w") as f: + f.write(ast.unparse(tree)) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_executor.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_executor.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf8ac439cd0366f2e8226987554eef2e2bef3aa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/rule_executor.py @@ -0,0 +1,287 @@ +import os +import re +import ast +import collections +import ifcopenshell +from logging import Logger +from dataclasses import dataclass +from codegen import indent + + +def reverse_compile(s): + return re.sub( + r"\s*\-\s*EXPRESS_ONE_BASED_INDEXING", + "", + re.sub( + ", )?+.(, INDETERMINATE)\\"[::-1], + "]\\1[", + re.sub( + r", '(\w+)', INDETERMINATE\)", + ".\\1", + s.strip() + .replace("len(", "SIZEOF(") + .replace("assert ", "") + .replace(" is not False", "") + .replace("getattr(", "") + .replace("express_getitem(", ""), + )[::-1], + )[::-1], + ) + + +@dataclass +class error(Exception): + rule_name: str + rule_definition: str + violation: str + instance: ifcopenshell.entity_instance = None + + def __str__(self): + inst = "" + if self.instance: + inst = f"On instance:\n{indent(4, str(self.instance))}\n" + if self.rule_name: + return f"{inst}Rule {self.rule_name}:\n{indent(4, self.rule_definition)}\nViolated by:\n{indent(4, self.violation)}" + else: + if inst: + inst = f"\n\n{inst}" + return f"{self.rule_definition}\n\nViolated by:\n{indent(4, self.violation)}{inst}" + + +def fix_type(v): + if isinstance(v, (list, tuple)): + # 1-based indexing: + # + # @todo this is not the best way, because it still allows to index the 0-th element, + # but given the existing body of rules this should be sufficient. + # return type(v)([None]) + type(v)(map(fix_type, v)) + + # We don't do this anymore, because it doesn't fix instance attribute lookups + # We now instead perform a -1 on the index qualifier in the code generation + pass + # @todo enrich entity instances with code to evaluate derived attributes + return v + + +def run(f: ifcopenshell.file, logger: Logger) -> None: + from _pytest import assertion + + if hasattr(logger, "set_instance"): + # when using the json logger, we notify it of the relevant instance + pre_annotate_instance = lambda instance: logger.set_state('instance', instance) if hasattr(logger, 'set_state') else None + post_annotate_instance = lambda instance: instance + pre_annotate_attribute = lambda attribute: logger.set_state('attribute', attribute) if hasattr(logger, 'set_state') else None + post_annotate_attribute = lambda attribute: None + else: + # when using the normal text logger the instance is appended to the method + pre_annotate_instance = lambda instance: None + post_annotate_instance = lambda instance: instance + pre_annotate_attribute = lambda attribute: None + post_annotate_attribute = lambda attribute: attribute + + orig = ifcopenshell.settings.unpack_non_aggregate_inverses + ifcopenshell.settings.unpack_non_aggregate_inverses = True + + fn = os.path.join(os.path.dirname(__file__), "rules", f"{f.schema_identifier}.py") + try: + source = open(fn, "r").read() + except FileNotFoundError as e: + import sys + import time + import subprocess + + current_dir_files = {fn.lower(): fn for fn in os.listdir('.')} + schema_name = str(f.schema_identifier).split(' ')[-1].lower() + schema_path = current_dir_files.get(schema_name + '.exp') + fn = schema_path[:-4] + '.py' + if not os.path.exists(fn): + subprocess.run([sys.executable, "-m", "ifcopenshell.express.rule_compiler", schema_path, fn], check=True) + time.sleep(1.) + source = open(fn, "r").read() + + a = ast.parse(source) + assertion.rewrite.rewrite_asserts(mod=a, source=source) + cd = compile(a, f"{f.schema_identifier}.py", "exec") + scope = {} + exec(cd, scope) + S = ifcopenshell.ifcopenshell_wrapper.schema_by_name(f.schema_identifier) + + rules = list(filter(lambda x: hasattr(x, "SCOPE"), scope.values())) + + if hasattr(logger, 'set_state'): + logger.set_state('type', 'global_rule') + + for R in [r for r in rules if r.SCOPE == "file"]: + try: + R()(f) + except Exception as e: + ln = e.__traceback__.tb_next.tb_lineno + pre_annotate_attribute(R.__name__) + logger.error( + str( + error( + post_annotate_attribute(R.__name__), + reverse_compile(source.split("\n")[ln - 1]), + reverse_compile(e.args[0]), + ) + ) + ) + + if hasattr(logger, 'set_state'): + logger.set_state('type', 'simpletype_rule') + + types = {} + subtypes = collections.defaultdict(list) + for d in S.declarations(): + if isinstance(d, ifcopenshell.ifcopenshell_wrapper.type_declaration): + types[d.name()] = d + if isinstance( + d.declared_type(), ifcopenshell.ifcopenshell_wrapper.named_type + ): + subtypes[d.declared_type().declared_type().name()].append(d.name()) + + D = collections.defaultdict(list) + for r in rules: + if r.SCOPE == "type": + + def visit(nm): + D[nm].append(r) + for nm2 in subtypes[nm]: + visit(nm2) + + visit(r.TYPE_NAME) + + def type_name(ty): + if isinstance(ty, ifcopenshell.ifcopenshell_wrapper.named_type): + return type_name(ty.declared_type()) + elif isinstance(ty, ifcopenshell.ifcopenshell_wrapper.aggregation_type): + # breakpoint() + pass + elif isinstance(ty, ifcopenshell.ifcopenshell_wrapper.simple_type): + pass + else: + return ty.name() + + def check(value, type, instance): + if value is None: + return + + if type_name(type) in D: + for R in D[type_name(type)]: + try: + R()(fix_type(value)) + except Exception as e: + ln = e.__traceback__.tb_next.tb_lineno + pre_annotate_instance(instance) + pre_annotate_attribute(f"{R.TYPE_NAME}.{R.RULE_NAME}") + logger.error( + str( + error( + post_annotate_attribute(f"{R.TYPE_NAME}.{R.RULE_NAME}"), + reverse_compile(source.split("\n")[ln - 1]), + reverse_compile(e.args[0]), + post_annotate_instance(instance), + ) + ) + ) + + # @nb something can be a named type with rules and still be an aggregation. + # case in point IfcCompoundPlaneAngleMeasure. Therefore only unpack named + # type references from this point onwards. + while isinstance( + type, + ( + ifcopenshell.ifcopenshell_wrapper.named_type, + ifcopenshell.ifcopenshell_wrapper.type_declaration, + ), + ): + type = type.declared_type() + + if isinstance(value, (list, tuple)): + if isinstance(type, ifcopenshell.ifcopenshell_wrapper.aggregation_type): + ty = type.type_of_element() + for v in value: + check(v, ty, instance=inst) + else: + # Let's hope a schema validation error was reported for this case + pass + + elif isinstance(value, ifcopenshell.entity_instance): + if isinstance( + S.declaration_by_name(value.is_a()), + ifcopenshell.ifcopenshell_wrapper.entity, + ): + # top level entity instances will be checked on their own + pass + else: + # unpack the type instance + check(value[0], S.declaration_by_name(value.is_a()), instance=inst) + + for inst in f: + try: + values = list(inst) + except Exception as e: + if hasattr(logger, "set_state"): + logger.error(str(e)) + else: + logger.error("For instance:\n %s\n%s", inst, e) + continue + entity = S.declaration_by_name(inst.is_a()) + attrs = entity.all_attributes() + for i, (attr, val, is_derived) in enumerate( + zip(attrs, values, entity.derived()) + ): + if is_derived: + # @todo + pass + else: + check(val, attr.type_of_attribute(), instance=inst) + + if hasattr(logger, 'set_state'): + logger.set_state('type', 'entity_rule') + + for R in [r for r in rules if r.SCOPE == "entity"]: + for inst in f.by_type(R.TYPE_NAME): + try: + R()(inst) + except Exception as e: + ln = e.__traceback__.tb_next.tb_lineno + pre_annotate_instance(inst) + pre_annotate_attribute(f"{R.TYPE_NAME}.{R.RULE_NAME}") + logger.error( + str( + error( + post_annotate_attribute(f"{R.TYPE_NAME}.{R.RULE_NAME}"), + reverse_compile(source.split("\n")[ln - 1]), + reverse_compile(e.args[0]), + post_annotate_instance(inst), + ) + ) + ) + + ifcopenshell.settings.unpack_non_aggregate_inverses = orig + + +if __name__ == "__main__": + import sys + import json + import logging + import ifcopenshell + from ifcopenshell.validate import json_logger + + filenames = [x for x in sys.argv[1:] if not x.startswith("--")] + flags = set(x for x in sys.argv[1:] if x.startswith("--")) + + for fn in filenames: + if "--json" in flags: + logger = json_logger() + else: + logger = logging.getLogger("validate") + logger.setLevel(logging.DEBUG) + + f = ifcopenshell.open(fn) + + run(f, logger) + + if "--json" in flags: + print("\n".join(json.dumps(x, default=str) for x in logger.statements)) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/run.bat b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/run.bat new file mode 100644 index 0000000000000000000000000000000000000000..96fd58973d8a60fc2a6046d83c1fbbdc0f92aacf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/run.bat @@ -0,0 +1,185 @@ +@ECHO OFF + +:: python bootstrap.py express.bnf > express_parser.py + +IF EXIST IFC2X3_TC1.exp ( + python express_parser.py IFC2X3_TC1.exp header implementation schema_class definitions + + IF EXIST Ifc2x3-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc2x3.cpp txt/header_ifc2x3.txt Ifc2x3.cpp + python cat.py -o ..\..\..\ifcparse\Ifc2x3.h txt/header_ifc2x3.txt Ifc2x3.h + python cat.py -o ..\..\..\ifcparse\Ifc2x3-schema.cpp txt/header_ifc2x3.txt Ifc2x3-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc2x3-definitions.h txt/header_ifc2x3.txt Ifc2x3-definitions.h + ) ELSE ( + :: v0.5.0 + python cat.py -o ..\..\..\ifcparse\Ifc2x3.cpp txt/header_ifc2x3.txt txt/ifndef_ifc4.txt Ifc2x3.cpp txt/endif.txt + python cat.py -o ..\..\..\ifcparse\Ifc2x3.h txt/header_ifc2x3.txt Ifc2x3.h + python cat.py -o ..\..\..\ifcparse\Ifc2x3enum.h txt/header_ifc2x3.txt Ifc2x3enum.h + python cat.py -o ..\..\..\ifcparse\Ifc2x3-latebound.cpp txt/header_ifc2x3.txt txt/ifndef_ifc4.txt Ifc2x3-latebound.cpp txt/endif.txt + python cat.py -o ..\..\..\ifcparse\Ifc2x3-latebound.h txt/header_ifc2x3.txt Ifc2x3-latebound.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4_ADD2TC1.exp ( + python express_parser.py IFC4_ADD2TC1.exp header implementation schema_class definitions + + IF EXIST Ifc4-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4.cpp txt/header_ifc4.txt Ifc4.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4.h txt/header_ifc4.txt Ifc4.h + python cat.py -o ..\..\..\ifcparse\Ifc4-schema.cpp txt/header_ifc4.txt Ifc4-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4-definitions.h txt/header_ifc4.txt Ifc4-definitions.h + ) ELSE ( + :: v0.5.0 + python cat.py -o ..\..\..\ifcparse\Ifc4.cpp txt/header_ifc4.txt txt/ifdef_ifc4.txt Ifc4.cpp txt/endif.txt + python cat.py -o ..\..\..\ifcparse\Ifc4.h txt/header_ifc4.txt Ifc4.h + python cat.py -o ..\..\..\ifcparse\Ifc4enum.h txt/header_ifc4.txt Ifc4enum.h + python cat.py -o ..\..\..\ifcparse\Ifc4-latebound.cpp txt/header_ifc4.txt txt/ifdef_ifc4.txt Ifc4-latebound.cpp txt/endif.txt + python cat.py -o ..\..\..\ifcparse\Ifc4-latebound.h txt/header_ifc4.txt Ifc4-latebound.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x1.exp ( + python express_parser.py IFC4x1.exp header implementation schema_class definitions + + IF EXIST Ifc4x1-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x1.cpp txt/header_ifc4x1.txt Ifc4x1.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x1.h txt/header_ifc4x1.txt Ifc4x1.h + python cat.py -o ..\..\..\ifcparse\Ifc4x1-schema.cpp txt/header_ifc4x1.txt Ifc4x1-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x1-definitions.h txt/header_ifc4x1.txt Ifc4x1-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x2.exp ( + python express_parser.py IFC4x2.exp header implementation schema_class definitions + + IF EXIST Ifc4x2-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x2.cpp txt/header_ifc4x2.txt Ifc4x2.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x2.h txt/header_ifc4x2.txt Ifc4x2.h + python cat.py -o ..\..\..\ifcparse\Ifc4x2-schema.cpp txt/header_ifc4x2.txt Ifc4x2-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x2-definitions.h txt/header_ifc4x2.txt Ifc4x2-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x3_RC1.exp ( + python express_parser.py IFC4x3_RC1.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_rc1-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc1.cpp txt/header_ifc4x3_rc1.txt Ifc4x3_rc1.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc1.h txt/header_ifc4x3_rc1.txt Ifc4x3_rc1.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc1-schema.cpp txt/header_ifc4x3_rc1.txt Ifc4x3_rc1-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc1-definitions.h txt/header_ifc4x3_rc1.txt Ifc4x3_rc1-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x3_RC2.exp ( + python express_parser.py IFC4x3_RC2.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_rc2-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc2.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc2.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc2.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc2.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc2-schema.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc2-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc2-definitions.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc2-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x3_RC3.exp ( + python express_parser.py IFC4x3_RC3.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_rc3-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc3.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc3.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc3.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc3.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc3-schema.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc3-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc3-definitions.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc3-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4x3_RC4.exp ( + python express_parser.py IFC4x3_RC4.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_rc4-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc4.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc4.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc4.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc4.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc4-schema.cpp txt/header_ifc4x3_rc2.txt Ifc4x3_rc4-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_rc4-definitions.h txt/header_ifc4x3_rc2.txt Ifc4x3_rc4-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4X3.exp ( + python express_parser.py IFC4X3.exp header implementation schema_class definitions + + IF EXIST Ifc4x3-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3.cpp txt/header_ifc4x3_rc2.txt Ifc4x3.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3.h txt/header_ifc4x3_rc2.txt Ifc4x3.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3-schema.cpp txt/header_ifc4x3_rc2.txt Ifc4x3-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3-definitions.h txt/header_ifc4x3_rc2.txt Ifc4x3-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4X3_TC1.exp ( + python express_parser.py IFC4X3_TC1.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_tc1-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_tc1.cpp txt/header_ifc4x3_tc1.txt Ifc4x3_tc1.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_tc1.h txt/header_ifc4x3_tc1.txt Ifc4x3_tc1.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_tc1-schema.cpp txt/header_ifc4x3_tc1.txt Ifc4x3_tc1-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_tc1-definitions.h txt/header_ifc4x3_tc1.txt Ifc4x3_tc1-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4X3_ADD1.exp ( + python express_parser.py IFC4X3_ADD1.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_add1-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add1.cpp txt/header_ifc4x3_add1.txt Ifc4x3_add1.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add1.h txt/header_ifc4x3_add1.txt Ifc4x3_add1.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add1-schema.cpp txt/header_ifc4x3_add1.txt Ifc4x3_add1-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add1-definitions.h txt/header_ifc4x3_add1.txt Ifc4x3_add1-definitions.h + ) + + del *.cpp *.h +) + +IF EXIST IFC4X3_ADD2.exp ( + python express_parser.py IFC4X3_ADD2.exp header implementation schema_class definitions + + IF EXIST Ifc4x3_add2-schema.cpp ( + :: v0.6.0 + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add2.cpp txt/header_ifc4x3_add2.txt Ifc4x3_add2.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add2.h txt/header_ifc4x3_add2.txt Ifc4x3_add2.h + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add2-schema.cpp txt/header_ifc4x3_add2.txt Ifc4x3_add2-schema.cpp + python cat.py -o ..\..\..\ifcparse\Ifc4x3_add2-definitions.h txt/header_ifc4x3_add2.txt Ifc4x3_add2-definitions.h + ) + + del *.cpp *.h +) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb050d1ae5603592d1cedaca21f17432db439b0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema.py @@ -0,0 +1,123 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import nodes +import platform +import collections +import pyparsing + +if tuple(map(int, platform.python_version_tuple())) < (2, 7): + import ordereddict + + collections.OrderedDict = ordereddict.OrderedDict + +# According to ISO 10303-11 7.1.2: Letters: "... The case of +# letters is significant only within explicit string literals." +class OrderedCaseInsensitiveDict_KeyObject(str): + def __eq__(self, other): + return self.lower() == other.lower() + + def __hash__(self): + return hash(self.lower()) + + +class OrderedCaseInsensitiveDict(collections.OrderedDict): + def __init__(self, *args, **kwargs): + collections.OrderedDict.__init__(self) + for key, value in collections.OrderedDict(*args, **kwargs).items(): + self[OrderedCaseInsensitiveDict_KeyObject(key)] = value + + def __setitem__(self, key, value): + return collections.OrderedDict.__setitem__(self, OrderedCaseInsensitiveDict_KeyObject(key), value) + + def __getitem__(self, key): + return collections.OrderedDict.__getitem__(self, OrderedCaseInsensitiveDict_KeyObject(key)) + + def get(self, key, *args, **kwargs): + return collections.OrderedDict.get(self, OrderedCaseInsensitiveDict_KeyObject(key), *args, **kwargs) + + def __contains__(self, key): + return collections.OrderedDict.__contains__(self, OrderedCaseInsensitiveDict_KeyObject(key)) + + def __delitem__(self, key): + return collections.OrderedDict.__delitem__(self, OrderedCaseInsensitiveDict_KeyObject(key)) + + +class Schema: + def is_enumeration(self, v): + return str(v) in self.enumerations + + def is_select(self, v): + return str(v) in self.selects + + def is_simpletype(self, v): + return str(v) in self.simpletypes + + def is_type(self, v): + return str(v) in self.types + + def is_entity(self, v): + return str(v) in self.entities + + def __len__(self): + return len(self.keys) + + def __iter__(self): + return iter(self.keys) + + def __getitem__(self, key): + return self.all_declarations[OrderedCaseInsensitiveDict_KeyObject(key)] + + def __init__(self, parsetree: pyparsing.ParseResults): + self.tree = parsetree + schema = next(iter(parsetree.syntax[0])) + self.name = schema.simple_id + schema_declarations = list(schema.schema_body[0]) + + sort = lambda d: OrderedCaseInsensitiveDict(sorted(d)) + + declarations = [ + d.any()[0] + for d in schema_declarations + if d.rule == "declaration" + ] + [ + d + for d in schema_declarations + if d.rule == "RuleDeclaration" + ] + + self.types = sort([(t.name, t) for t in declarations if isinstance(t, nodes.TypeDeclaration)]) + self.entities = sort([(t.name, t) for t in declarations if isinstance(t, nodes.EntityDeclaration)]) + self.rules = sort([(t.name, t) for t in declarations if isinstance(t, nodes.RuleDeclaration)]) + self.functions = sort([(t.name, t) for t in declarations if isinstance(t, nodes.FunctionDeclaration)]) + + self.keys = list(self.types.keys()) + list(self.entities.keys()) + list(self.rules.keys()) + list(self.functions.keys()) + self.all_declarations = {k: v for d in (self.types, self.entities, self.rules, self.functions) for k, v in d.items()} + + of_type = lambda *types: sort( + [(a, b.type) for a, b in self.types.items() if any(isinstance(b.type, ty) for ty in types)] + ) + + self.enumerations = of_type(nodes.EnumerationType) + self.selects = of_type(nodes.SelectType) + self.simpletypes = of_type( + str, nodes.AggregationType, nodes.BinaryType, nodes.StringType, nodes.SimpleType, nodes.NamedType + ) + + assert len(self.enumerations) + len(self.selects) + len(self.simpletypes) == len(self.types) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema_class.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema_class.py new file mode 100644 index 0000000000000000000000000000000000000000..50a4e50c5dfa729a2ce7c913100df8ff384e6a0e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/schema_class.py @@ -0,0 +1,568 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from __future__ import annotations +import operator +import re + +import nodes +import codegen +import templates +import mapping + +from collections import defaultdict + +try: + import ifcopenshell.ifcopenshell_wrapper as w +except: + pass + + +class LateBoundSchemaInstantiator: + def __init__(self, schema_name): + self.schema_name = schema_name + self.schema_name_title = schema_name.capitalize() + self.declarations = {} + self.names = [] + # We need to make sure anonymous types are not gc'ed. + self.cache = [] + + def aggregation_type(self, aggr_type, bound1, bound2, decl_type): + self.cache.append( + w.aggregation_type(getattr(w.aggregation_type, aggr_type + "_type"), bound1, bound2, decl_type) + ) + return self.cache[-1] + + def simple_type(self, type): + self.cache.append(w.simple_type(getattr(w.simple_type, type + "_type"))) + return self.cache[-1] + + def named_type(self, type): + self.cache.append(w.named_type(self.declarations[str(type)])) + return self.cache[-1] + + def declare(self, definition_type, name): + self.names.append(str(name)) + + def begin_schema(self): + self.names.sort(key=str.lower) + + def typedef(self, name, declared_type): + index_in_schema = self.names.index(str(name)) + self.declarations[str(name)] = w.type_declaration(name, index_in_schema, declared_type) + + def enumeration(self, name, enum): + schema_name = self.schema_name + index_in_schema = self.names.index(str(name)) + self.declarations[str(name)] = w.enumeration_type(name, index_in_schema, enum.values) + + def entity(self, name, type): + index_in_schema = self.names.index(str(name)) + supertype = None if len(type.supertypes) == 0 else self.declarations[str(type.supertypes[0])] + self.declarations[str(name)] = w.entity(name, type.abstract, index_in_schema, supertype) + + def select(self, name, type): + index_in_schema = self.names.index(str(name)) + children = [self.declarations[str(v)] for v in type.values] + self.declarations[str(name)] = w.select_type(name, index_in_schema, children) + + def entity_attributes(self, name, attribute_definitions, is_derived): + attributes = [] + for attr_name, decl_type, optional in attribute_definitions: + attributes.append(w.attribute(attr_name, decl_type, optional)) + self.declarations[str(name)].set_attributes(attributes, is_derived) + self.cache.extend(attributes) + + def inverse_attributes(self, name, inv_attrs): + attributes = [] + for attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index in inv_attrs: + en = self.declarations[str(entity_ref)] + attributes.append( + w.inverse_attribute( + attr_name, + getattr(w.inverse_attribute, aggr_type + "_type"), + bound1, + bound2, + en, + en.attributes()[attribute_entity_index], + ) + ) + self.cache.extend(attributes) + self.declarations[str(name)].set_inverse_attributes(attributes) + + def entity_subtypes(self, name, tys): + self.declarations[str(name)].set_subtypes([self.declarations[str(v)] for v in tys]) + + def finalize(self, can_be_instantiated_set, override_schema_name=None): + self.schema = w.schema_definition( + override_schema_name or self.schema_name, list(self.declarations.values()), None + ) + + def disown(self): + for elem in self.cache + list(self.declarations.values()): + elem.this.disown() + + +class string_pool: + def __init__(self, fn): + self.di = {} + self.fn = fn + def append(self, v): + def _(): + if i := self.di.get(v): + return i + else: + i = len(self.di) + self.di[v] = i + return i + return self.fn(_()) + def __iter__(self): + return iter(self.di.keys()) + + +class EarlyBoundCodeWriter: + def __init__(self, schema_name): + self.strings = string_pool(lambda i: "strings[%d]" % i) + self.schema_name = schema_name + self.schema_name_title = schema_name.capitalize() + + self.statements = [ + "", + '#include "../ifcparse/IfcSchema.h"', + '#include "../ifcparse/%(schema_name_title)s.h"' % self.__dict__, + '#include ', + "", + 'using namespace std::string_literals;', + "using namespace IfcParse;", + "", + ] + + self.names = [] + + def aggregation_type(self, aggr_type, bound1, bound2, decl_type): + return ( + "new aggregation_type(aggregation_type::%(aggr_type)s_type, %(bound1)d, %(bound2)d, %(decl_type)s)" + % locals() + ) + + def simple_type(self, type): + return "new simple_type(simple_type::%s_type)" % type + + def named_type(self, type): + return "new named_type(%s_%s_type)" % (self.schema_name, type) + + def declare(self, definition_type, name): + schema_name = self.schema_name + # self.statements.append("%(definition_type)s* %(schema_name)s_%(name)s_type = 0;" % locals()) + self.names.append(name) + + def begin_schema(self): + self.names.sort(key=str.lower) + schema_name = self.schema_name.upper() + num_names = len(self.names) + self.statements.append("declaration* %(schema_name)s_types[%(num_names)d] = {nullptr};" % locals()) + + self.statements.append("{factory_placeholder}") + +# self.statements.append( +# """ +# #if defined(__clang__) +# __attribute__((optnone)) +# #elif defined(__GNUC__) || defined(__GNUG__) +# #pragma GCC push_options +# #pragma GCC optimize ("O0") +# #elif defined(_MSC_VER) +# #pragma optimize("", off) +# #endif +# """ +# ) + self.statements.append("IfcParse::schema_definition* %s_populate_schema() {" % self.schema_name.upper()) + self.statements.append("{string_pool_placeholder}") + + def typedef(self, name, declared_type): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + ref = self.strings.append(name) + self.statements.append( + ' %(schema_name)s_types[%(index_in_schema)d] = new type_declaration(%(ref)s, %(index_in_schema)d, %(declared_type)s);' + % locals() + ) + + def enumeration(self, name, enum): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + ref = self.strings.append(name) + items = ",".join(self.strings.append(v) for v in enum.values) + self.statements.append( + ' %(schema_name)s_types[%(index_in_schema)d] = new enumeration_type(%(ref)s, %(index_in_schema)d, {%(items)s});' + % locals() + ) + + def entity(self, name, type): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + ref = self.strings.append(name) + supertype = "0" if len(type.supertypes) == 0 else "%s_types[%d]" % (self.schema_name, self.names.index(type.supertypes[0])) + is_abstract = "true" if type.abstract else "false" + self.statements.append( + ' %(schema_name)s_types[%(index_in_schema)d] = new entity(%(ref)s, %(is_abstract)s, %(index_in_schema)d, (entity*) %(supertype)s);' + % locals() + ) + + def select(self, name, type): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + ref = self.strings.append(name) + items = ",".join( + map(lambda v: "%s_types[%d]" % (self.schema_name, self.names.index(v)), sorted(map(str, type.values))) + ) + self.statements.append( + ' %(schema_name)s_types[%(index_in_schema)d] = new select_type(%(ref)s, %(index_in_schema)d, {%(items)s});' + % locals() + ) + + def entity_attributes(self, name, attribute_definitions, is_derived): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + def _(): + index_in_schema = self.names.index(name) + schema_name = self.schema_name + for attr_name, decl_type, optional in attribute_definitions: + attr_name_ref = self.strings.append(attr_name) + optional_cpp = str(optional).lower() + yield 'new attribute(%(attr_name_ref)s, %(decl_type)s, %(optional_cpp)s)' % locals() + attributes = ",".join(_()) + derived = ",".join(map(lambda b: str(b).lower(), is_derived)) + self.statements.append(" ((entity*)%(schema_name)s_types[%(index_in_schema)d])->set_attributes({%(attributes)s}, {%(derived)s});" % locals()) + + def inverse_attributes(self, name, inv_attrs): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + def _(): + schema_name = self.schema_name + index_in_schema = self.names.index(name) + for attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index in inv_attrs: + attr_name_ref = self.strings.append(attr_name) + opposite_index_in_schema = self.names.index(entity_ref) + opposite1 = '%(schema_name)s_types[%(opposite_index_in_schema)d]' % locals() + opposite_index_in_schema = self.names.index(attribute_entity) + opposite2 = '%(schema_name)s_types[%(opposite_index_in_schema)d]' % locals() + yield 'new inverse_attribute(%(attr_name_ref)s, inverse_attribute::%(aggr_type)s_type, %(bound1)d, %(bound2)d, ((entity*) %(opposite1)s), ((entity*) %(opposite2)s)->attributes()[%(attribute_entity_index)d])' % locals() + attributes = ",".join(_()) + self.statements.append(" ((entity*) %(schema_name)s_types[%(index_in_schema)d])->set_inverse_attributes({%(attributes)s});" % locals()) + + def entity_subtypes(self, name, tys): + schema_name = self.schema_name.upper() + index_in_schema = self.names.index(name) + subtypes = ",".join(map(lambda t: ("((entity*) %%(schema_name)s_types[%d])" % self.names.index(t)), tys)) % locals() + self.statements.append(" ((entity*) %(schema_name)s_types[%(index_in_schema)d])->set_subtypes({%(subtypes)s});" % locals()) + + def finalize(self, can_be_instantiated_set): + schema_name = self.schema_name.upper() + schema_name_title = self.schema_name.capitalize() + def _(): + schema_name = self.schema_name.upper() + schema_name_title = self.schema_name.capitalize() + for type_name in self.names: + index_in_schema = self.names.index(type_name) + yield "%(schema_name)s_types[%(index_in_schema)d]" % locals() + declarations = ",".join(_()) + schema_name_ref = self.strings.append(schema_name) + self.statements.append( + ' return new schema_definition(%(schema_name_ref)s, {%(declarations)s}, new %(schema_name)s_instance_factory());' + % locals() + ) + self.statements.append("}"); + +# self.statements.append( +# """ +# #if defined(__clang__) +# #elif defined(__GNUC__) || defined(__GNUG__) +# #pragma GCC pop_options +# #elif defined(_MSC_VER) +# #pragma optimize("", on) +# #endif +# """ +# ) + + self.statements.extend( + ( + "static std::unique_ptr schema;", + "", + "void %s::clear_schema() {" % schema_name_title, + " schema.reset();", + "}", + "", + ) + ) + + self.statements.extend( + ( + "const schema_definition& %s::get_schema() {" % schema_name_title, + " if (!schema) {", + " schema.reset(%(schema_name)s_populate_schema());" % locals(), + " }", + " return *schema;", + "}", + "", + "", + ) + ) + + def can_be_instantiated(idx_name): + name = idx_name[1] + return name in can_be_instantiated_set + + instance_mapping = """switch(decl->index_in_schema()) { + %s + default: throw IfcParse::IfcException(decl->name() + " cannot be instantiated"); + } +""" % "\n ".join( + map( + lambda tup: ("case %%d: return new ::%s::%%s(std::move(data));" % schema_name_title) % tup, + filter(can_be_instantiated, enumerate(self.names)), + ) + ) + + self.statements[self.statements.index("{factory_placeholder}")] = ( + """ +class %(schema_name)s_instance_factory : public IfcParse::instance_factory { + virtual IfcUtil::IfcBaseClass* operator()(const IfcParse::declaration* decl, IfcEntityInstanceData&& data) const { + %(instance_mapping)s + } +}; +""" + % locals() + ) + + "" + self.statements[self.statements.index("{string_pool_placeholder}")] = ( + """ +const std::string strings[] = {%s}; +""" + % ",".join(map(lambda s: '"%s"s' % s, self.strings)) + ) + + def __str__(self): + return "\n".join(self.statements) + + +class SchemaClass(codegen.Base): + def __init__(self, mapping: mapping.Mapping, code=EarlyBoundCodeWriter): + class UnmetDependenciesException(Exception): + pass + + schema_name = mapping.schema.name + self.schema_name = schema_name_title = schema_name.capitalize() + + declared_types = [] + + x = code(schema_name) + + def transform_to_indexed(fn): + def wrapper(*args, **kwargs): + schema_name_upper = mapping.schema.name.upper() + declared_type = fn(*args, **kwargs) + if 'simple_type' in declared_type: + pass + else: + match = re.search(r'\((\w+?_[\w+]+?_\w+?)\)', declared_type) + if match: + old_decl = match.group(1) + name = old_decl.lower().replace(schema_name.lower() + '_', '').replace('_type', '') + idx = [n.lower() for n in x.names].index(name) + declared_type = declared_type.replace(old_decl, '%(schema_name_upper)s_types[%(idx)d]' % locals()) + return declared_type + return wrapper if code == EarlyBoundCodeWriter else fn + + @transform_to_indexed + def get_declared_type(type, emitted_names=None): + if isinstance(type, nodes.SimpleType): + type = type.type + if isinstance(type, nodes.NamedType): + type = str(type) + + if isinstance(type, nodes.AggregationType): + aggr_type = type.aggregate_type + make_bound = lambda b: -1 if b == "?" else int(b) + bound1, bound2 = map(make_bound, (type.bounds.lower, type.bounds.upper)) + decl_type = get_declared_type(type.type, emitted_names) + return x.aggregation_type(aggr_type, bound1, bound2, decl_type) + elif isinstance(type, nodes.BinaryType): + return x.simple_type("binary") + elif isinstance(type, nodes.StringType): + return x.simple_type("string") + elif isinstance(type, str): + if mapping.schema.is_type(type) or mapping.schema.is_entity(type): + if emitted_names is None or type.lower() in emitted_names: + return x.named_type(type) + else: + raise UnmetDependenciesException(type) + else: + return x.simple_type(type) + else: + raise ValueError("No declared type for <%r>" % type) + + def find_inverse_name_and_index(entity_name, attribute_name): + entity_name_orig = entity_name + attributes_per_subtype = [] + while True: + entity = mapping.schema.entities[entity_name] + attr_names = list(map(operator.attrgetter("name"), entity.attributes)) + if len(attr_names): + attributes_per_subtype.append((entity_name, attr_names)) + if len(entity.supertypes) != 1: + break + entity_name = entity.supertypes[0] + index = 0 + for et, attrs in attributes_per_subtype[::-1]: + try: + return et, attrs.index(attribute_name) + except: + pass + + else: + raise Exception("No attribute named %s.%s" % (entity_name_orig, attribute_name)) + + collections_by_type = ( + ("entity", mapping.schema.entities), + ("type_declaration", mapping.schema.simpletypes), + ("select_type", mapping.schema.selects), + ("enumeration_type", mapping.schema.enumerations), + ) + + for definition_type, collection in collections_by_type: + for name in collection.keys(): + x.declare(definition_type, name) + + declarations_by_index = [] + + x.begin_schema() + + emitted = set() + len_to_emit = len(mapping.schema) - len(mapping.schema.rules) - len(mapping.schema.functions) + + def write_simpletype(schema_name, name, type): + try: + declared_type = get_declared_type(type, emitted) + except UnmetDependenciesException: + # @todo? + # print("Unmet", repr(name)) + return False + + x.typedef(name, declared_type) + + def write_enumeration(schema_name, name, enum): + x.enumeration(name, enum) + + def write_entity(schema_name, name, type): + if len(type.supertypes) == 0 or set(map(lambda s: s.lower(), type.supertypes)) < emitted: + x.entity(name, type) + else: + return False + + def write_select(schema_name, name, type): + if set(map(lambda s: str(s).lower(), type.values)) < emitted: + x.select(name, type) + else: + return False + + def write(name): + if mapping.schema.is_simpletype(name): + fn = write_simpletype + elif mapping.schema.is_enumeration(name): + fn = write_enumeration + elif mapping.schema.is_entity(name): + fn = write_entity + elif mapping.schema.is_select(name): + fn = write_select + elif name in mapping.schema.rules: + return + elif name in mapping.schema.functions: + return + + decl = mapping.schema[name] + if isinstance(decl, nodes.TypeDeclaration): + decl = decl.type + return fn(schema_name, name, decl) is not False + + while len(emitted) < len_to_emit: + for name in mapping.schema: + if name.lower() in emitted: + continue + if write(name): + emitted.add(name.lower()) + declarations_by_index.append(name) + + num_declarations = len(emitted) + + for name, type in mapping.schema.entities.items(): + derived = set(mapping.derived_in_supertype(type)) + attribute_names = list(map(operator.attrgetter("name"), mapping.arguments(type))) + is_derived = [b in derived for b in attribute_names] + attribute_definitions = [] + for attr in type.attributes: + decl_type = get_declared_type(attr.type) + attribute_definitions.append((attr.name, decl_type, attr.optional)) + x.entity_attributes(name, attribute_definitions, is_derived) + + for name, type in mapping.schema.entities.items(): + if type.inverse: + inv_attrs = [] + for attr in type.inverse: + if attr.bounds: + make_bound = lambda b: -1 if b == "?" else int(b) + bound1, bound2 = map(make_bound, (attr.bounds.lower, attr.bounds.upper)) + else: + bound1, bound2 = -1, -1 + attr_name, aggr_type, entity_ref = attr.name, attr.type, attr.entity + if aggr_type is None: + aggr_type = "unspecified" + attribute_entity, attribute_entity_index = find_inverse_name_and_index(entity_ref, attr.attribute) + inv_attrs.append( + (attr_name, aggr_type, bound1, bound2, entity_ref, attribute_entity, attribute_entity_index) + ) + x.inverse_attributes(name, inv_attrs) + + subtypes = defaultdict(list) + + for name, type in mapping.schema.entities.items(): + for ty in type.supertypes: + subtypes[ty].append(name) + + for name, tys in subtypes.items(): + x.entity_subtypes(name, tys) + + can_be_instantiated_set = set( + list(mapping.schema.entities.keys()) + + list(mapping.schema.simpletypes.keys()) + + list(mapping.schema.enumerations.keys()) + ) + + x.finalize(can_be_instantiated_set) + + self.str = str(x) + self.file_name = "%s-schema.cpp" % self.schema_name + self.code = x + + def __repr__(self): + return self.str + + +Generator = SchemaClass diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/templates.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/templates.py new file mode 100644 index 0000000000000000000000000000000000000000..e0398fd58d8094194ee4b1192d29434d37f8089d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/express/templates.py @@ -0,0 +1,291 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +header = """ +#ifndef %(schema_name_upper)s_H +#define %(schema_name_upper)s_H + +#include +#include + +#include + +#include "../ifcparse/ifc_parse_api.h" + +#include "../ifcparse/aggregate_of_instance.h" +#include "../ifcparse/IfcBaseClass.h" +#include "../ifcparse/IfcSchema.h" +#include "../ifcparse/IfcException.h" +#include "../ifcparse/Argument.h" + +struct %(schema_name)s { + +IFC_PARSE_API static const IfcParse::schema_definition& get_schema(); + +IFC_PARSE_API static void clear_schema(); + +static const char* const Identifier; + +// Forward definitions +%(forward_definitions)s + +%(declarations)s + +%(class_definitions)s +}; + +#endif +""" + +enum_header = """ +#ifndef %(schema_name_upper)sENUM_H +#define %(schema_name_upper)sENUM_H + +#include "../ifcparse/ifc_parse_api.h" + +#include +#include + +#endif +""" + +lb_header = """""" + +implementation = """ +#include "../ifcparse/%(schema_name)s.h" +#include "../ifcparse/IfcSchema.h" +#include "../ifcparse/IfcException.h" +#include "../ifcparse/IfcFile.h" + +#include + +const char* const %(schema_name)s::Identifier = "%(schema_name_upper)s"; + +using namespace IfcParse; + +// External definitions +%(external_definitions)s + +%(enumeration_functions)s + +%(simple_type_impl)s + +%(entity_implementations)s +""" + +lb_implementation = """""" + +entity_descriptor = """ current = entity_descriptor_map[Type::%(type)s] = new IfcEntityDescriptor(Type::%(type)s,%(parent_statement)s); +%(entity_descriptor_attributes)s""" + +entity_descriptor_parent = "entity_descriptor_map.find(Type::%(type)s)->second" +entity_descriptor_attribute_without_entity = ' current->add("%(name)s",%(optional)s,%(type)s);' +entity_descriptor_attribute_with_entity = ' current->add("%(name)s",%(optional)s,%(type)s,Type::%(entity_name)s);' + +enumeration_descriptor = """ values.clear(); values.reserve(128); +%(enumeration_descriptor_values)s + enumeration_descriptor_map[Type::%(type)s] = new IfcEnumerationDescriptor(Type::%(type)s, values);""" + +enumeration_descriptor_value = ' values.push_back("%(name)s");' + +derived_field_statement = " {std::set idxs; %(statements)sderived_map[Type::%(type)s] = idxs;}" +derived_field_statement_attrs = "idxs.insert(%d); " + +simpletype = """%(documentation)s +class IFC_PARSE_API %(name)s : %(superclass)s { +public: + virtual const IfcParse::type_declaration& declaration() const; + static const IfcParse::type_declaration& Class(); + explicit %(name)s (IfcEntityInstanceData&& e); + %(name)s (%(type)s v); + operator %(type)s() const; +}; +""" + +simpletype_impl_comment = "// Function implementations for %(name)s" +simpletype_impl_argument_type = 'if (i == 0) { return %(attr_type)s; } else { throw IfcParse::IfcAttributeOutOfRangeException("Argument index out of range"); }' +simpletype_impl_argument = "return get_attribute_value(i);" +simpletype_impl_is_with_supertype = "return v == %(class_name)s_type || %(superclass)s::is(v);" +simpletype_impl_is_without_supertype = "return v == %(class_name)s_type;" +simpletype_impl_type = "return *((IfcParse::type_declaration*)%(schema_name_upper)s_types[%(index_in_schema)d]);" +simpletype_impl_class = "return *((IfcParse::type_declaration*)%(schema_name_upper)s_types[%(index_in_schema)d]);" +simpletype_impl_explicit_constructor = "data_ = e;" +simpletype_impl_constructor = ( + "data_ = new IfcEntityInstanceData(%(schema_name_upper)s_types[%(index_in_schema)d]); set_attribute_value(0, v);" +) +simpletype_impl_constructor_templated = "data_ = new IfcEntityInstanceData(%(schema_name_upper)s_types[%(index_in_schema)d]); set_attribute_value(0, v->generalize());" +simpletype_impl_cast = "return get_attribute_value(0);" +simpletype_impl_cast_templated = ( + "aggregate_of_instance::ptr es = get_attribute_value(0); return es->as< %(underlying_type)s >();" +) +simpletype_impl_declaration = "return *((IfcParse::type_declaration*)%(schema_name_upper)s_types[%(index_in_schema)d]);" + +select_virtual = """%(documentation)s +class IFC_PARSE_API %(name)s : public virtual IfcUtil::IfcBaseInterface { +public: + static const IfcParse::select_type& Class(); + typedef aggregate_of< %(name)s > list; +}; +""" + +select_plain = """%(documentation)s +typedef IfcUtil::IfcBaseClass %(name)s; +""" + +enumeration = """class IFC_PARSE_API %(name)s : public IfcUtil::IfcBaseType { +%(documentation)s +public: + typedef enum {%(values)s} Value; + static const char* ToString(Value v); + static Value FromString(const std::string& s); + + virtual const IfcParse::enumeration_type& declaration() const; + static const IfcParse::enumeration_type& Class(); + %(name)s (IfcEntityInstanceData&& e); + %(name)s (Value v); + %(name)s (const std::string& v); + operator Value() const; +}; +""" + +entity = """%(documentation)s +class IFC_PARSE_API %(name)s : %(superclass)s { +public: +%(attributes)s %(inverse)s virtual const IfcParse::entity& declaration() const; + static const IfcParse::entity& Class(); + %(name)s (IfcEntityInstanceData&& e); + %(name)s (%(constructor_arguments)s); + typedef aggregate_of< %(name)s > list; +}; +""" + +select_function = """ +const IfcParse::select_type& %(schema_name)s::%(name)s::Class() { return *((IfcParse::select_type*)%(schema_name_upper)s_types[%(index_in_schema)d]); } +""" + +enumeration_function = """ +const IfcParse::enumeration_type& %(schema_name)s::%(name)s::declaration() const { return *((IfcParse::enumeration_type*)%(schema_name_upper)s_types[%(index_in_schema)d]); } +const IfcParse::enumeration_type& %(schema_name)s::%(name)s::Class() { return *((IfcParse::enumeration_type*)%(schema_name_upper)s_types[%(index_in_schema)d]); } + +%(schema_name)s::%(name)s::%(name)s(IfcEntityInstanceData&& e) + : IfcBaseType(std::move(e)) +{} + +%(schema_name)s::%(name)s::%(name)s(Value v) { + set_attribute_value(0, EnumerationReference(&declaration(), static_cast(v))); +} + +%(schema_name)s::%(name)s::%(name)s(const std::string& v) { + set_attribute_value(0, EnumerationReference(&declaration(), declaration().lookup_enum_offset(v))); +} + +const char* %(schema_name)s::%(name)s::ToString(Value v) { + return %(schema_name)s::%(name)s::%(name)s::Class().lookup_enum_value((size_t)v); +} + +%(schema_name)s::%(name)s::Value %(schema_name)s::%(name)s::FromString(const std::string& s) { + return (%(schema_name)s::%(name)s::Value) %(schema_name)s::%(name)s::%(name)s::Class().lookup_enum_offset(s); +} + +%(schema_name)s::%(name)s::operator %(schema_name)s::%(name)s::Value() const { + return (%(schema_name)s::%(name)s::Value) ((EnumerationReference) get_attribute_value(0)).index(); +} +""" + +entity_implementation = """// Function implementations for %(name)s +%(attributes)s +%(inverse)s +const IfcParse::entity& %(schema_name)s::%(name)s::declaration() const { return *((IfcParse::entity*)%(schema_name_upper)s_types[%(index_in_schema)d]); } +const IfcParse::entity& %(schema_name)s::%(name)s::Class() { return *((IfcParse::entity*)%(schema_name_upper)s_types[%(index_in_schema)d]); } +%(schema_name)s::%(name)s::%(name)s(IfcEntityInstanceData&& e) : %(superclass)s { } +%(schema_name)s::%(name)s::%(name)s(%(constructor_arguments)s) : %(superclass_num_attrs)s { %(constructor_implementation)s; populate_derived(); } +""" + +# data_ = e; +# data_ = new IfcEntityInstanceData(%(schema_name_upper)s_types[%(index_in_schema)d]); + +optional_attribute_description = "/// Whether the optional attribute %s is defined for this %s" + +function = "%(return_type)s %(schema_name)s::%(class_name)s::%(name)s(%(arguments)s) { %(body)s }" +const_function = "%(return_type)s %(schema_name)s::%(class_name)s::%(name)s(%(arguments)s) const { %(body)s }" +constructor = "%(schema_name)s::%(class_name)s::%(class_name)s(%(arguments)s) { %(body)s }" +constructor_single_initlist = ( + "%(schema_name)s::%(class_name)s::%(class_name)s(%(arguments)s) : %(superclass)s(%(superclass_init)s) { %(body)s }" +) +cast_function = "%(schema_name)s::%(class_name)s::operator %(return_type)s() const { %(body)s }" + +array_type = "std::vector< %(instance_type)s > /*[%(lower)s:%(upper)s]*/" +nested_array_type = "std::vector< std::vector< %(instance_type)s > >" +list_type = "aggregate_of< %(instance_type)s >::ptr" +list_list_type = "aggregate_of_aggregate_of< %(instance_type)s >::ptr" +untyped_list = "aggregate_of_instance::ptr" +inverse_attr = "aggregate_of< %(entity)s >::ptr %(name)s() const; // INVERSE %(entity)s::%(attribute)s" + +enum_from_string_stmt = ' if (s == "%(value)s") return ::%(schema_name)s::%(name)s::%(short_name)s_%(value)s;' + +schema_entity_stmt = " case Type::%(name)s: return new %(name)s(e); break;" +string_map_statement = ' string_map["%(uppercase_name)s"%(padding)s] = Type::%(name)s;' +parent_type_stmt = " if(v==%(name)s%(padding)s) { return %(parent)s; }" + +parent_type_test = " || %s::is(v)" + +optional_attr_stmt = "return !get_attribute_value(%(index)d).isNull();" + +get_attr_stmt = "%(null_check)s %(non_optional_type)s v = get_attribute_value(%(index)d); return v;" +get_attr_stmt_enum = "%(null_check)s return %(non_optional_type)s::FromString(get_attribute_value(%(index)d));" +get_attr_stmt_entity = "%(null_check)s return ((IfcUtil::IfcBaseClass*)(get_attribute_value(%(index)d)))->as<%(non_optional_type_no_pointer)s>(true);" +get_attr_stmt_array = "%(null_check)s aggregate_of_instance::ptr es = get_attribute_value(%(index)d); return es->as< %(list_instance_type)s >();" +get_attr_stmt_nested_array = "%(null_check)s aggregate_of_aggregate_of_instance::ptr es = get_attribute_value(%(index)d); return es->as< %(list_instance_type)s >();" + +get_inverse = "if (!file_) { return nullptr; } return file_->getInverse(id_, %(schema_name_upper)s_types[%(type_index)d], %(index)d)->as<%(type)s>();" + +set_attr_stmt = ( + "%(check_optional_set_begin)sset_attribute_value(%(index)d, %(star_if_optional)sv);%(check_optional_set_else)sunset_attribute_value(%(index)d);%(check_optional_set_end)s" +) +set_attr_instance = ( + "%(check_optional_set_begin)sset_attribute_value(%(index)d, v->as());%(check_optional_set_else)sunset_attribute_value(%(index)d);%(check_optional_set_end)s" +) +set_attr_stmt_enum = "%(check_optional_set_begin)sset_attribute_value(%(index)d, EnumerationReference(&%(non_optional_type)s::Class(), (size_t) %(star_if_optional)sv));%(check_optional_set_else)sunset_attribute_value(%(index)d);%(check_optional_set_end)s" +set_attr_stmt_array = ( + "%(check_optional_set_begin)sset_attribute_value(%(index)d, (%(star_if_optional)sv)->generalize());%(check_optional_set_else)sunset_attribute_value(%(index)d);%(check_optional_set_end)s" +) + +constructor_stmt = ( + "set_attribute_value(%(index)d, (%(name)s));" +) +constructor_stmt_enum = ( + "set_attribute_value(%(index)d, (EnumerationReference(&%(type)s::Class(),(size_t)%(name)s)));" +) +constructor_stmt_array = ( + "set_attribute_value(%(index)d, (%(name)s)->generalize());" +) +constructor_stmt_derived = ( + "" +) +constructor_stmt_instance = ( + "set_attribute_value(%(index)d, %(name)s ? %(name)s->as() : (IfcUtil::IfcBaseClass*) nullptr);" +) + +constructor_stmt_optional = " if (%(name)s) {%(stmt)s }" + +inverse_implementation = ' inverse_map[Type::%(type)s].insert(std::make_pair("%(name)s", std::make_pair(Type::%(related_type)s, %(index)d)));' + + +def multi_line_comment(li): + return ("/// %s" % ("\n/// ".join(li))) if len(li) else "" diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..604e5b8e37126189739072bc9a930ae89be96b25 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/__init__.py @@ -0,0 +1,57 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Geometry processing and analysis + +IFC may define geometry explicitly (such as meshes) or implicitly (such as +parametric extrusions). This module provides methods to extract geometric +definitions in IFC into explicitly tessellated triangles or OpenCASCADE Breps +for further processing. + +This is typically needed when writing software to visualise or analyse +geometry. See also :mod:`ifcopenshell.util.shape` for deriving quantities. +""" + + +def _has_occ(): + # NOTE: All pythonocc versions since 7.4.0 are using OCC.Core. + # Previous versions (pythonocc<=0.17.3) are using just OCC. + + try: + import OCC.Core.BRepTools + + return True + except ImportError: + pass + + try: + import OCC.BRepTools + + return True + except ImportError: + pass + + return False + + +has_occ = _has_occ() + +if has_occ: + from . import occ_utils as utils + +from .main import * diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/app.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/app.py new file mode 100644 index 0000000000000000000000000000000000000000..aa11f18c1faddfa0c35ae9e476d539e81c929c16 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/app.py @@ -0,0 +1,698 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import os +import sys +import time +import operator +import functools +import multiprocessing +import ifcopenshell.ifcopenshell_wrapper as W + +try: + from OCC.Core import AIS + + USE_OCCT_HANDLE = False +except ImportError: + from OCC import AIS + + USE_OCCT_HANDLE = True + +from collections import defaultdict, OrderedDict +from collections.abc import Iterable + +try: + QString = unicode +except NameError: + # Python 3 + QString = str + +os.environ["QT_API"] = "pyqt5" +try: + from pyqode.qt import QtCore +except BaseException: + pass + +from PyQt5 import QtCore, QtGui, QtWidgets + +from .code_editor_pane import code_edit + +try: + from OCC.Display.pyqt5Display import qtViewer3d +except BaseException: + import OCC.Display + + try: + import OCC.Display.backend + except BaseException: + pass + + try: + OCC.Display.backend.get_backend("qt-pyqt5") + except BaseException: + OCC.Display.backend.load_backend("qt-pyqt5") + + from OCC.Display.qtDisplay import qtViewer3d + +from .main import settings, iterator +from .occ_utils import display_shape + +from .. import open as open_ifc_file +from .. import version as ifcopenshell_version + +if ifcopenshell_version < "0.6": + # not yet ported + from .. import get_supertype + + +class geometry_creation_signals(QtCore.QObject): + completed = QtCore.pyqtSignal("PyQt_PyObject") + progress = QtCore.pyqtSignal("PyQt_PyObject") + + +class geometry_creation_thread(QtCore.QThread): + def __init__(self, signals, settings, f): + QtCore.QThread.__init__(self) + self.signals = signals + self.settings = settings + self.f = f + + def run(self): + t0 = time.time() + + # detect concurrency from hardware, we need to have + # at least two threads because otherwise the interface + # is different + # is different + it = iterator(self.settings, self.f, max(2, multiprocessing.cpu_count())) + if not it.initialize(): + self.signals.completed.emit([]) + return + + def _(): + + old_progress = -1 + while True: + shape = it.get() + + if shape: + yield shape + + if not it.next(): + break + + self.signals.completed.emit((it, self.f, list(_()))) + + +class configuration: + def __init__(self): + try: + import ConfigParser + + Cfg = ConfigParser.RawConfigParser + except BaseException: + import configparser + + def Cfg(): + return configparser.ConfigParser(interpolation=None) + + conf_file = os.path.expanduser(os.path.join("~", ".ifcopenshell", "app", "snippets.conf")) + if conf_file.startswith("~"): + conf_file = None + return + + self.config_encode = lambda s: s.replace("\\", "\\\\").replace("\n", "\n|") + self.config_decode = lambda s: s.replace("\n|", "\n").replace("\\\\", "\\") + + if not os.path.exists(os.path.dirname(conf_file)): + os.makedirs(os.path.dirname(conf_file)) + + if not os.path.exists(conf_file): + config = Cfg() + config.add_section("snippets") + config.set( + "snippets", + "print all wall ids", + self.config_encode( + """ +########################################################################### +# A simple script that iterates over all walls in the current model # +# and prints their Globally unique IDs (GUIDS) to the console window # +########################################################################### + +for wall in model.by_type("IfcWall"): + print ("wall with global id: "+str(wall.GlobalId)) +""".lstrip() + ), + ) + + config.set( + "snippets", + "print properties of current selection", + self.config_encode( + """ +########################################################################### +# A simple script that iterates over all IfcPropertySets of the currently # +# selected object and prints them to the console # +########################################################################### + +# check if something is selected +if selection: + #get the IfcProduct that is stored in the global variable 'selection' + obj = selection + for relDefinesByProperties in obj.IsDefinedBy: + if not relDefinesByProperties.is_a("IfcRelDefinesByProperties"): + continue + print("[{0}]".format(relDefinesByProperties.RelatingPropertyDefinition.Name)) + if relDefinesByProperties.RelatingPropertyDefinition.is_a("IfcPropertySet"): + for prop in relDefinesByProperties.RelatingPropertyDefinition.HasProperties: + print ("{:<20} :{}".format(prop.Name,prop.NominalValue.wrappedValue)) + print ("\\n") +""".lstrip() + ), + ) + with open(conf_file, "w") as configfile: + config.write(configfile) + + self.config = Cfg() + self.config.read(conf_file) + + def options(self, s): + return OrderedDict([(k, self.config_decode(self.config.get(s, k))) for k in self.config.options(s)]) + + +class application(QtWidgets.QApplication): + """A pythonOCC, PyQt based IfcOpenShell application + with two tree views and a graphical 3d view""" + + class abstract_treeview(QtWidgets.QTreeWidget): + """Base class for the two treeview controls""" + + instanceSelected = QtCore.pyqtSignal([object]) + instanceVisibilityChanged = QtCore.pyqtSignal([object, int]) + instanceDisplayModeChanged = QtCore.pyqtSignal([object, int]) + + def __init__(self): + QtWidgets.QTreeView.__init__(self) + self.setColumnCount(len(self.ATTRIBUTES)) + self.setHeaderLabels(self.ATTRIBUTES) + self.children = defaultdict(list) + + def get_children(self, inst): + c = [inst] + i = 0 + while i < len(c): + c.extend(self.children[c[i]]) + i += 1 + return c + + def contextMenuEvent(self, event): + menu = QtWidgets.QMenu(self) + visibility = [menu.addAction("Show"), menu.addAction("Hide")] + displaymode = [menu.addAction("Solid"), menu.addAction("Wireframe")] + action = menu.exec_(self.mapToGlobal(event.pos())) + index = self.selectionModel().currentIndex() + inst = index.data(QtCore.Qt.UserRole) + if hasattr(inst, "toPyObject"): + inst = inst + if action in visibility: + self.instanceVisibilityChanged.emit(inst, visibility.index(action)) + elif action in displaymode: + self.instanceDisplayModeChanged.emit(inst, displaymode.index(action)) + + def clicked_(self, index): + inst = index.data(QtCore.Qt.UserRole) + if hasattr(inst, "toPyObject"): + inst = inst + if inst: + self.instanceSelected.emit(inst) + + def select(self, product): + itm = self.product_to_item.get(product) + if itm is None: + return + self.selectionModel().setCurrentIndex( + itm, QtCore.QItemSelectionModel.SelectCurrent | QtCore.QItemSelectionModel.Rows + ) + + class decomposition_treeview(abstract_treeview): + """Treeview with typical IFC decomposition relationships""" + + ATTRIBUTES = ["Entity", "GlobalId", "Name"] + + def parent(self, instance): + if instance.is_a("IfcOpeningElement"): + return instance.VoidsElements[0].RelatingBuildingElement + if instance.is_a("IfcElement"): + fills = instance.FillsVoids + if len(fills): + return fills[0].RelatingOpeningElement + containments = instance.ContainedInStructure + if len(containments): + return containments[0].RelatingStructure + if instance.is_a("IfcObjectDefinition"): + decompositions = instance.Decomposes + if len(decompositions): + return decompositions[0].RelatingObject + + def load_file(self, f, **kwargs): + products = list(f.by_type("IfcProduct")) + list(f.by_type("IfcProject")) + parents = list(map(self.parent, products)) + items = {} + skipped = 0 + ATTRS = self.ATTRIBUTES + while len(items) + skipped < len(products): + for product, parent in zip(products, parents): + if parent is None and not product.is_a("IfcProject"): + skipped += 1 + continue + if (parent is None or parent in items) and product not in items: + sl = [] + for attr in ATTRS: + if attr == "Entity": + sl.append(product.is_a()) + else: + sl.append(getattr(product, attr) or "") + itm = items[product] = QtWidgets.QTreeWidgetItem(items.get(parent, self), sl) + itm.setData(0, QtCore.Qt.UserRole, product) + self.children[parent].append(product) + self.product_to_item = dict(zip(items.keys(), map(self.indexFromItem, items.values()))) + self.clicked.connect(self.clicked_) + self.expandAll() + + class type_treeview(abstract_treeview): + """Treeview with typical IFC decomposition relationships""" + + ATTRIBUTES = ["Name"] + + def load_file(self, f, **kwargs): + products = list(f.by_type("IfcProduct")) + types = set(map(lambda i: i.is_a(), products)) + items = {} + for t in types: + + def add(t): + s = get_supertype(t) + if s: + add(s) + s2, t2 = map(QString, (s, t)) + if t2 not in items: + itm = items[t2] = QtWidgets.QTreeWidgetItem(items.get(s2, self), [t2]) + itm.setData(0, QtCore.Qt.UserRole, t2) + self.children[s2].append(t2) + + if ifcopenshell_version < "0.6": + add(t) + + for p in products: + t = QString(p.is_a()) + itm = items[p] = QtWidgets.QTreeWidgetItem(items.get(t, self), [p.Name or ""]) + itm.setData(0, QtCore.Qt.UserRole, t) + self.children[t].append(p) + + self.product_to_item = dict(zip(items.keys(), map(self.indexFromItem, items.values()))) + self.clicked.connect(self.clicked) + self.expandAll() + + class property_table(QtWidgets.QWidget): + def __init__(self): + QtWidgets.QWidget.__init__(self) + self.layout = QtWidgets.QVBoxLayout(self) + self.setLayout(self.layout) + self.scroll = QtWidgets.QScrollArea(self) + self.layout.addWidget(self.scroll) + self.scroll.setWidgetResizable(True) + self.scrollContent = QtWidgets.QWidget(self.scroll) + self.scrollLayout = QtWidgets.QVBoxLayout(self.scrollContent) + self.scrollContent.setLayout(self.scrollLayout) + self.scroll.setWidget(self.scrollContent) + self.prop_dict = {} + + # triggered by selection event in either component of parent + def select(self, product): + + # Clear the old contents if any + while self.scrollLayout.count(): + child = self.scrollLayout.takeAt(0) + if child is not None: + if child.widget() is not None: + child.widget().deleteLater() + + self.scroll = QtWidgets.QScrollArea() + self.scroll.setWidgetResizable(True) + + prop_sets = self.prop_dict.get(str(product)) + + if prop_sets is not None: + for k, v in prop_sets: + group_box = QtWidgets.QGroupBox() + + group_box.setTitle(k) + group_layout = QtWidgets.QVBoxLayout() + group_box.setLayout(group_layout) + + for name, value in v.items(): + prop_name = str(name) + + value_str = value + if hasattr(value_str, "wrappedValue"): + value_str = value_str.wrappedValue + + if isinstance(value_str, unicode): + value_str = value_str.encode("utf-8") + else: + value_str = str(value_str) + + if hasattr(value, "is_a"): + type_str = " (%s)" % value.is_a() + else: + type_str = "" + label = QtWidgets.QLabel("%s: %s%s" % (prop_name, value_str, type_str)) + group_layout.addWidget(label) + + group_layout.addStretch() + self.scrollLayout.addWidget(group_box) + + self.scrollLayout.addStretch() + else: + label = QtWidgets.QLabel("No IfcPropertySets associated with selected entity instance") + self.scrollLayout.addWidget(label) + + def load_file(self, f, **kwargs): + for p in f.by_type("IfcProduct"): + propsets = [] + + def process_pset(prop_def): + if prop_def is not None: + prop_set_name = prop_def.Name + props = {} + if prop_def.is_a("IfcElementQuantity"): + for q in prop_def.Quantities: + if q.is_a("IfcPhysicalSimpleQuantity"): + props[q.Name] = q[3] + elif prop_def.is_a("IfcPropertySet"): + for prop in prop_def.HasProperties: + if prop.is_a("IfcPropertySingleValue"): + props[prop.Name] = prop.NominalValue + else: + # Entity introduced in IFC4 + # prop_def.is_a("IfcPreDefinedPropertySet"): + for prop in range(4, len(prop_def)): + props[prop_def.attribute_name(prop)] = prop_def[prop] + return prop_set_name, props + + try: + for is_def_by in p.IsDefinedBy: + if is_def_by.is_a("IfcRelDefinesByProperties"): + propsets.append(process_pset(is_def_by.RelatingPropertyDefinition)) + elif is_def_by.is_a("IfcRelDefinesByType"): + type_psets = is_def_by.RelatingType.HasPropertySets + if type_psets is None: + continue + for propset in type_psets: + propsets.append(process_pset(propset)) + except Exception as e: + import traceback + + print("failed to load properties: {}".format(e)) + traceback.print_exc() + + if len(propsets): + self.prop_dict[str(p)] = propsets + + print("property set dictionary has {} entries".format(len(self.prop_dict))) + + class viewer(qtViewer3d): + + instanceSelected = QtCore.pyqtSignal([object]) + + # @staticmethod + # def ais_to_key(ais_handle): + # def yield_shapes(): + # ais = ais_handle.GetObject() + # if hasattr(ais, "Shape"): + # yield ais.Shape() + # return + # shp = OCC.AIS.Handle_AIS_Shape.DownCast(ais_handle) + # if not shp.IsNull(): + # yield shp.Shape() + # return + # mult = ais_handle + # if mult.IsNull(): + # shp = OCC.AIS.Handle_AIS_Shape.DownCast(ais_handle) + # if not shp.IsNull(): + # yield shp + # else: + # li = mult.GetObject().ConnectedTo() + # for i in range(li.Length()): + # shp = OCC.AIS.Handle_AIS_Shape.DownCast(li.Value(i + 1)) + # if not shp.IsNull(): + # yield shp + + # return tuple(shp.HashCode(1 << 24) for shp in yield_shapes()) + + def __init__(self, widget): + qtViewer3d.__init__(self, widget) + self.ais_to_product = {} + self.product_to_ais = {} + self.counter = 0 + self.window = widget + self.thread = None + + def initialize(self): + self.InitDriver() + self._display.Select = self.HandleSelection + + def finished(self, file_shapes): + it, f, shapes = file_shapes + v = self._display + + t = {0: time.time()} + + def update(dt=None): + t1 = time.time() + if dt is None or t1 - t[0] > dt: + v.FitAll() + v.Repaint() + t[0] = t1 + + for shape in shapes: + ais = display_shape(shape, viewer_handle=v) + product = f[shape.data.id] + + if USE_OCCT_HANDLE: + ais.GetObject().SetSelectionPriority(self.counter) + self.ais_to_product[self.counter] = product + self.product_to_ais[product] = ais + self.counter += 1 + + QtWidgets.QApplication.processEvents() + + if product.is_a() in {"IfcSpace", "IfcOpeningElement"}: + v.Context.Erase(ais, True) + + update(1.0) + + update() + + self.thread = None + + def load_file(self, f, setting=None): + + if self.thread is not None: + return + + if setting is None: + setting = settings() + setting.set("dimensionality", W.CURVES_SURFACES_AND_SOLIDS) + setting.set("use-python-opencascade", True) + + self.signals = geometry_creation_signals() + thread = self.thread = geometry_creation_thread(self.signals, setting, f) + self.window.window_closed.connect(lambda *args: thread.terminate()) + self.signals.completed.connect(self.finished) + self.thread.start() + + def select(self, product): + ais = self.product_to_ais.get(product) + if ais is None: + return + v = self._display.Context + v.ClearSelected(False) + v.SetSelected(ais, True) + + def toggle(self, product_or_products, fn): + if not isinstance(product_or_products, Iterable): + product_or_products = [product_or_products] + aiss = list(filter(None, map(self.product_to_ais.get, product_or_products))) + last = len(aiss) - 1 + for i, ais in enumerate(aiss): + fn(ais, i == last) + + def toggle_visibility(self, product_or_products, flag): + v = self._display.Context + if flag: + + def visibility(ais, last): + v.Erase(ais, last) + + else: + + def visibility(ais, last): + v.Display(ais, last) + + self.toggle(product_or_products, visibility) + + def toggle_wireframe(self, product_or_products, flag): + v = self._display.Context + if flag: + + def wireframe(ais, last): + if v.IsDisplayed(ais): + v.SetDisplayMode(ais, 0, last) + + else: + + def wireframe(ais, last): + if v.IsDisplayed(ais): + v.SetDisplayMode(ais, 1, last) + + self.toggle(product_or_products, wireframe) + + def HandleSelection(self, X, Y): + v = self._display.Context + v.Select() + v.InitSelected() + if v.MoreSelected(): + ais = v.SelectedInteractive() + inst = self.ais_to_product[ais.GetObject().SelectionPriority()] + self.instanceSelected.emit(inst) + + class window(QtWidgets.QMainWindow): + + TITLE = "IfcOpenShell IFC viewer" + + window_closed = QtCore.pyqtSignal([]) + + def __init__(self): + QtWidgets.QMainWindow.__init__(self) + self.setWindowTitle(self.TITLE) + self.menu = self.menuBar() + self.menus = {} + + def closeEvent(self, *args): + self.window_closed.emit() + + def add_menu_item(self, menu, label, callback, icon=None, shortcut=None): + m = self.menus.get(menu) + if m is None: + m = self.menu.addMenu(menu) + self.menus[menu] = m + + if icon: + a = QtWidgets.QAction(QtGui.QIcon(icon), label, self) + else: + a = QtWidgets.QAction(label, self) + + if shortcut: + a.setShortcut(shortcut) + + a.triggered.connect(callback) + m.addAction(a) + + def makeSelectionHandler(self, component): + def handler(inst): + for c in self.components: + if c != component: + c.select(inst) + + return handler + + def __init__(self, settings=None): + QtWidgets.QApplication.__init__(self, sys.argv) + self.window = application.window() + self.tree = application.decomposition_treeview() + self.tree2 = application.type_treeview() + self.propview = self.property_table() + self.canvas = application.viewer(self.window) + self.tabs = QtWidgets.QTabWidget() + self.window.resize(800, 600) + splitter = QtWidgets.QSplitter(QtCore.Qt.Horizontal) + splitter.addWidget(self.tabs) + self.tabs.addTab(self.tree, "Decomposition") + self.tabs.addTab(self.tree2, "Types") + self.tabs.addTab(self.propview, "Properties") + splitter2 = QtWidgets.QSplitter(QtCore.Qt.Vertical) + splitter2.addWidget(self.canvas) + self.editor = code_edit(self.canvas, configuration().options("snippets")) + splitter2.addWidget(self.editor) + splitter.addWidget(splitter2) + splitter.setSizes([200, 600]) + splitter2.setSizes([400, 200]) + self.window.setCentralWidget(splitter) + self.canvas.initialize() + self.components = [self.tree, self.tree2, self.canvas, self.propview, self.editor] + self.files = {} + + self.window.add_menu_item("File", "&Open", self.browse, shortcut="CTRL+O") + self.window.add_menu_item("File", "&Close", self.clear, shortcut="CTRL+W") + self.window.add_menu_item("File", "&Exit", self.window.close, shortcut="ALT+F4") + + self.tree.instanceSelected.connect(self.makeSelectionHandler(self.tree)) + self.tree2.instanceSelected.connect(self.makeSelectionHandler(self.tree2)) + self.canvas.instanceSelected.connect(self.makeSelectionHandler(self.canvas)) + for t in [self.tree, self.tree2]: + t.instanceVisibilityChanged.connect(functools.partial(self.change_visibility, t)) + t.instanceDisplayModeChanged.connect(functools.partial(self.change_displaymode, t)) + + self.settings = settings + + def change_visibility(self, tree, inst, flag): + insts = tree.get_children(inst) + self.canvas.toggle_visibility(insts, flag) + + def change_displaymode(self, tree, inst, flag): + insts = tree.get_children(inst) + self.canvas.toggle_wireframe(insts, flag) + + def start(self): + self.window.show() + sys.exit(self.exec_()) + + def browse(self): + filename = QtWidgets.QFileDialog.getOpenFileName( + self.window, "Open file", ".", "Industry Foundation Classes (*.ifc)" + )[0] + self.load(filename) + + def clear(self): + self.canvas._display.Context.RemoveAll() + self.tree.clear() + self.files.clear() + + def load(self, fn): + if fn in self.files: + return + f = open_ifc_file(str(fn)) + self.files[fn] = f + for c in self.components: + c.load_file(f, setting=self.settings) + + +if __name__ == "__main__": + application().start() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/code_editor_pane.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/code_editor_pane.py new file mode 100644 index 0000000000000000000000000000000000000000..f84f45a2347b30aafe02100af8ef599687844a51 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/code_editor_pane.py @@ -0,0 +1,162 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import os +import sys +import logging + +from code import InteractiveConsole +from PyQt5 import QtCore, QtGui, QtWidgets + +try: + from PyQt5 import QtWidgets +except BaseException: + QtWidgets = QtGui + +try: + from pyqode.core.panels import CheckerPanel + from pyqode.core import api + from pyqode.core import modes + from pyqode.core import panels + from pyqode.core.api import CodeEdit, ColorScheme + from pyqode.python.modes import PyAutoIndentMode, PythonSH + from pyqode.python.backend import server + from pyqode.python import modes as pymodes, panels as pypanels, widgets + from pyqode.python.widgets import PyInteractiveConsole + + has_pyqode = True +except BaseException: + has_pyqode = False + CodeEdit = QtWidgets.QPlainTextEdit + + +class StdoutRedirector: + """A class for redirecting stdout to this Text widget.""" + + def __init__(self, widget): + self.widget = widget + self.isError = False + + def write(self, myStr): + self.widget.moveCursor(QtGui.QTextCursor.End) + if self.isError: + self.widget.setTextColor(QtCore.Qt.red) + else: + self.widget.setTextColor(QtCore.Qt.white) + self.widget.insertPlainText(myStr) + self.widget.moveCursor(QtGui.QTextCursor.End) + + +class code_edit(QtWidgets.QWidget): + class Console(InteractiveConsole): + def __init__(*args): + InteractiveConsole.__init__(*args) + + def enter(self, source): + self.runcode(source) + + def runCode(self): + sys.stdout = StdoutRedirector(self.output) + sys.stderr = StdoutRedirector(self.output) + sys.stderr.isError = True + + if not self.model: + print("please load a model first", file=sys.stderr) + else: + self.c.enter(str(self.editor.toPlainText())) + + sys.stdout = sys.__stdout__ + sys.stderr = sys.__stderr__ + + def select(self, product): + self.c = self.Console({"model": self.model, "viewer": self.viewer, "selection": product}) + + def __init__(self, viewer, snippets=None): + self.model = None + self.viewer = viewer + QtWidgets.QWidget.__init__(self) + self.layout = QtWidgets.QVBoxLayout(self) + self.setLayout(self.layout) + self.c = None + self.tools = QtWidgets.QHBoxLayout(self) + self.layout.addLayout(self.tools) + self.runbutton = QtWidgets.QPushButton("Run") + width = self.runbutton.fontMetrics().boundingRect("Run").width() + 20 + self.runbutton.setMaximumWidth(width) + self.tools.addWidget(self.runbutton) + self.runbutton.clicked.connect(self.runCode) + + editor = CodeEdit() + if has_pyqode: + editor.backend.start(server.__file__) + editor.panels.append(panels.FoldingPanel()) + editor.panels.append(panels.LineNumberPanel()) + editor.panels.append(panels.SearchAndReplacePanel(), panels.SearchAndReplacePanel.Position.BOTTOM) + editor.panels.append(panels.EncodingPanel(), api.Panel.Position.TOP) + editor.add_separator() + editor.panels.append(pypanels.QuickDocPanel(), api.Panel.Position.BOTTOM) + sh = editor.modes.append(PythonSH(editor.document())) + editor.modes.append(modes.CaretLineHighlighterMode()) + editor.modes.append(modes.CodeCompletionMode()) + editor.modes.append(modes.ExtendedSelectionMode()) + editor.modes.append(modes.FileWatcherMode()) + editor.modes.append(modes.OccurrencesHighlighterMode()) + editor.modes.append(modes.RightMarginMode()) + editor.modes.append(modes.SmartBackSpaceMode()) + editor.modes.append(modes.SymbolMatcherMode()) + editor.modes.append(modes.ZoomMode()) + editor.modes.append(pymodes.CommentsMode()) + editor.modes.append(pymodes.CalltipsMode()) + auto = pymodes.PyAutoCompleteMode() + auto.logger.setLevel(logging.CRITICAL) + editor.modes.append(auto) + editor.modes.append(pymodes.PyAutoIndentMode()) + editor.modes.append(pymodes.PyIndenterMode()) + editor.show() + else: + editor.setStyleSheet("font-size: 10pt; font-family: Consolas, Courier;") + + self.editor = editor + self.snippets = snippets + if self.snippets: + self.list = QtWidgets.QComboBox(self) + self.replace_snippet(0) + for snip_name in self.snippets.keys(): + self.list.addItem(snip_name) + self.tools.addWidget(self.list) + self.list.currentIndexChanged[int].connect(self.replace_snippet) + + self.layout.addWidget(self.editor) + self.output = QtWidgets.QTextEdit() + self.output.setReadOnly(True) + self.output.setStyleSheet("font-size: 10pt; font-family: Consolas, Courier; background-color: #444;") + self.layout.addWidget(self.output) + + def replace_snippet(self, number=None): + snip = list(self.snippets.values())[number] + if has_pyqode: + self.editor.setPlainText(snip, "", "") + else: + self.editor.setPlainText(snip) + + def load_file(self, f, **kwargs): + output = [] + sys.stdout = StdoutRedirector(self.output) + self.model = f + self.c = self.Console({"model": self.model, "selection": None, "viewer": self.viewer}) + sys.stdout = sys.__stdout__ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/main.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/main.py new file mode 100644 index 0000000000000000000000000000000000000000..0800ac7763b6dcbb8b47b6f07bc20165548d0d00 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/main.py @@ -0,0 +1,720 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from __future__ import annotations +import os +import sys +import operator + +from .. import open, ifcopenshell_wrapper +from ..file import file +from ..entity_instance import entity_instance + +from . import has_occ + +from typing import TypeVar, Union, Optional, Any, Literal, overload, TYPE_CHECKING, cast +from collections.abc import Generator, Iterable + +if TYPE_CHECKING: + from OCC.Core import TopoDS + + IteratorOutput = Union["ShapeElementType", "utils.shape_tuple"] + +T = TypeVar("T") +ShapeElementType = Union[ + ifcopenshell_wrapper.BRepElement, ifcopenshell_wrapper.TriangulationElement, ifcopenshell_wrapper.SerializedElement +] +ShapeType = Union[ifcopenshell_wrapper.BRep, ifcopenshell_wrapper.Triangulation, ifcopenshell_wrapper.Serialization] + + +def wrap_shape_creation(settings, shape): + return shape + + +if has_occ: + from . import occ_utils as utils + + try: + from OCC.Core import TopoDS + except ImportError: + from OCC import TopoDS + + def wrap_shape_creation(settings: settings, shape: ifcopenshell_wrapper.Element): + if getattr(settings, "use_python_opencascade", False): + return utils.create_shape_from_serialization(shape) + else: + return shape + + +SETTING = Literal[ + "angle-unit", + "apply-default-materials", + "apply-offset", + "boolean-attempt-2d", + "building-local-placement", + "cache-shapes", + "cgal-original-edges", + "cgal-smooth-angle-degrees", + "circle-segments", + "compute-curvature", + "context-identifiers", + "context-ids", + "context-types", + "convert-back-units", + "debug", + "defer-processing-first-element", + "dimensionality", + "disable-boolean-result", + "disable-opening-subtractions", + "edge-arrows", + "element-hierarchy", + "enable-layerset-slicing", + "force-space-transparency", + "function-step-param", + "function-step-type", + "generate-uvs", + "iterator-output", + "keep-bounding-boxes", + "layerset-first", + "length-unit", + "max-offset-deviation", + "max-offset", + "mesher-angular-deflection", + "mesher-linear-deflection", + "model-offset", + "model-rotation", + "no-clean-triangulation", + "no-normals", + "no-parallel-mapping", + "no-wire-intersection-check", + "no-wire-intersection-tolerance", + "permissive-shape-reuse", + "precision-factor", + "precision", + "reorient-shells", + "site-local-placement", + "surface-colour", + "triangulation-type", + "unify-shapes", + "use-material-names", + "use-python-opencascade", + "use-world-coords", + "validate", + "weld-vertices", +] +SERIALIZER_SETTING = Literal[ + "base-uri", + "use-element-names", + "use-element-guids", + "use-element-step-ids", + "use-element-types", + "y-up", + "ecef", + "digits", + "wkt-use-section", +] + +# NOTE: hybrid-cgal-simple-opencascade is added just as an example +# It's possible to use any hybrid combination by the format below: +# "hybrid-library1-library2". +# List is updated from AbstractKernel.cpp. +GEOMETRY_LIBRARY = Literal["cgal", "cgal-simple", "opencascade", "hybrid-cgal-simple-opencascade"] + + +class missing_setting: + def __repr__(self): + return "-" + + +class settings_mixin: + """ + Pythonic interface mixin to the settings modules and + to provide an additional setting to enable pythonOCC + when available + """ + + def __init__(self, **kwargs): + super().__init__() + for k, v in kwargs.items(): + self.set(getattr(self, k), v) + + def __repr__(self): + def safe_get(x): + try: + return self.get(x) + except RuntimeError: + return missing_setting() + + fmt_pair = lambda x: "%s = %r" % (self.rname(x), safe_get(x)) + return "%s(%s)" % (type(self).__name__, ", ".join(map(fmt_pair, self.setting_names()))) + + @staticmethod + def name(k: str) -> Union[SETTING, SERIALIZER_SETTING]: + return k.lower().replace("_", "-") + + @staticmethod + def rname(k: Union[SETTING, SERIALIZER_SETTING]) -> str: + return k.upper().replace("-", "_") + + @overload + def set(self: settings, k: SETTING, v: Any) -> None: ... + @overload + def set(self: serializer_settings, k: SERIALIZER_SETTING, v: Any) -> None: ... + def set(self, k: SETTING, v: Any) -> None: + """ + Set value of the setting named `k` to `v`. + + :raises RuntimeError: If there is no setting with name `k`. + """ + k = self.name(k) + if isinstance(self, settings) and k == "use-python-opencascade": + if not has_occ: + raise AttributeError("Python OpenCASCADE is not installed") + if v: + self.set_("iterator-output", ifcopenshell_wrapper.SERIALIZED) + self.set_("use-world-coords", True) + self.use_python_opencascade = True + else: + self.set_(self.name(k), v) + + @overload + def get(self: settings, k: SETTING) -> Any: ... + @overload + def get(self: serializer_settings, k: SERIALIZER_SETTING) -> Any: ... + def get(self, k: str) -> Any: + """ + Return value of the setting named `k`. + + :raises RuntimeError: If there is no setting with name `k`. + """ + k = self.name(k) + if isinstance(self, settings) and k == "use-python-opencascade": + return self.use_python_opencascade + return self.get_(k) + + @overload + def setting_names(self: settings) -> tuple[SETTING, ...]: ... + @overload + def setting_names(self: serializer_settings) -> tuple[SERIALIZER_SETTING, ...]: ... + def setting_names(self) -> tuple[str, ...]: + setting_names = super().setting_names() + if isinstance(self, settings): + setting_names += ("use-python-opencascade",) + return setting_names + + @overload + def __getattr__(self: settings, k: str) -> SETTING: ... + @overload + def __getattr__(self: serializer_settings, k: str) -> SERIALIZER_SETTING: ... + def __getattr__(self, k: str) -> str: + # Swig wrapper will try to access "this", + # ensure we won't accidentally call any c-extension methods + # like .setting_names() until wrapper is not completely initialized. + # See #4861. + if k == "this": + raise AttributeError("Swig wrapper's 'this' is unset.") + if k in map(self.rname, self.setting_names()): + return k + else: + raise AttributeError("'Settings' object has no attribute '%s'" % k) + + def build_parser(self, parser) -> None: + """ + Accepts an argparse.ArgumentParser object, enumerates the settings in this container and + adds argument parser rules for each. + """ + type_factories = { + "bool": bool, + "int": int, + "double": float, + "std::string": str, + "std::set": lambda s: list(map(int, s.split(";"))), + "std::set": lambda s: s.split(";"), + "std::vector": lambda s: list(map(float, s.split(";"))), + "IteratorOutputOptions": int, + "FunctionStepMethod": int, + "OutputDimensionalityTypes": int, + "TriangulationMethod": int, + } + for nm in self.setting_names(): + if nm == "use-python-opencascade": + ty == "bool" + else: + ty = self.get_type(nm) + if ty == "bool": + group = parser.add_mutually_exclusive_group() + group.add_argument( + f"--{nm}", + dest=nm.replace("-", "_"), + action="store_true", + ) + group.add_argument( + f"--no-{nm}", + dest=nm.replace("-", "_"), + action="store_false", + ) + parser.set_defaults(**{nm.replace("-", "_"): None}) + else: + parser.add_argument(f"--{nm}", dest=nm.replace("-", "_"), type=type_factories[ty]) + + def apply_namespace(self, namespace) -> None: + """ + Accepts an argparse.Namespace object, enumerates over the values in this namespace and + writes them to the settings when available + """ + names = set(self.setting_names()) + for k, v in namespace._get_kwargs(): + if k.replace("_", "-") in names and v is not None: + self.set(k.replace("_", "-"), v) + + +class serializer_settings(settings_mixin, ifcopenshell_wrapper.SerializerSettings): + pass + + +class settings(settings_mixin, ifcopenshell_wrapper.Settings): + use_python_opencascade = False + + +class iterator(ifcopenshell_wrapper.Iterator): + def __init__( + self, + settings: settings, + file_or_filename: Union[file, str], + num_threads: int = 1, + include: Optional[Union[list[entity_instance], list[str]]] = None, + exclude: Optional[Union[list[entity_instance], list[str]]] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", + ): + self.settings = settings + if isinstance(file_or_filename, file): + self.file = file + file_or_filename = file_or_filename.wrapped_data + else: + file_or_filename = self.file = open(file_or_filename) + + if include is not None and exclude is not None: + raise ValueError("include and exclude cannot be specified simultaneously") + + if include is not None or exclude is not None: + # Couldn't get the typemaps properly applied using %extend so we + # replicate the SWIG-generated __init__ call on the output of a + # free function. + # @todo verify this works with SWIG 4 + + include_or_exclude = include if exclude is None else exclude + include_or_exclude_type = set(x.__class__.__name__ for x in include_or_exclude) + + if include_or_exclude_type == {"entity_instance"}: + include_or_exclude = cast(set[entity_instance], include_or_exclude) + + if not all((last_inst := inst).is_a("IfcProduct") for inst in include_or_exclude): + raise ValueError( + f"include and exclude need to be an aggregate of IfcProduct. Violating element: '{last_inst}'." + ) + + initializer = ifcopenshell_wrapper.construct_iterator_with_include_exclude_id + + include_or_exclude = [i.id() for i in include_or_exclude] + else: + initializer = ifcopenshell_wrapper.construct_iterator_with_include_exclude + + self.this = initializer( + geometry_library, self.settings, file_or_filename, include_or_exclude, include is not None, num_threads + ) + else: + self.this = ifcopenshell_wrapper.construct_iterator( + geometry_library, self.settings, file_or_filename, num_threads + ) + + if has_occ: + + def get(self): + return wrap_shape_creation(self.settings, ifcopenshell_wrapper.Iterator.get(self)) + + def __iter__(self) -> Generator[IteratorOutput, None, None]: + if self.initialize(): + while True: + yield self.get() + if not self.next(): + break + + def get_task_products(self): + return entity_instance.wrap_value(ifcopenshell_wrapper.Iterator.get_task_products(self), self.file) + + +ClashType = Literal["protrusion", "pierce", "collision", "clearance"] +CLASH_TYPE_ITEMS = ("protrusion", "pierce", "collision", "clearance") + + +class tree(ifcopenshell_wrapper.tree): + def __init__(self, file: Optional[file] = None, settings: Optional[settings] = None): + args = [self] + if file is not None: + args.append(file.wrapped_data) + if settings is not None: + args.append(settings) + ifcopenshell_wrapper.tree.__init__(*args) + + def add_file(self, file: file, settings: settings) -> None: + ifcopenshell_wrapper.tree.add_file(self, file.wrapped_data, settings) + + def add_iterator(self, iterator: iterator) -> None: + ifcopenshell_wrapper.tree.add_file(self, iterator) + + def select( + self, + value: Union[ + entity_instance, ifcopenshell_wrapper.BRepElement, tuple[float, float, float], TopoDS.TopoDS_Shape + ], + **kwargs, + ) -> list[entity_instance]: + def unwrap(value): + if isinstance(value, entity_instance): + return value.wrapped_data + elif all(map(lambda v: hasattr(value, v), "XYZ")): + return value.X(), value.Y(), value.Z() + return value + + args = [self, unwrap(value)] + if isinstance(value, (entity_instance, ifcopenshell_wrapper.BRepElement)): + args.append(kwargs.get("completely_within", False)) + if "extend" in kwargs: + args.append(kwargs["extend"]) + elif isinstance(value, (list, tuple)) and len(value) == 3 and set(map(type, value)) == {float}: + if "extend" in kwargs: + args.append(kwargs["extend"]) + elif has_occ: + if isinstance(value, TopoDS.TopoDS_Shape): + args[1] = utils.serialize_shape(value) + args.append(kwargs.get("completely_within", False)) + if "extend" in kwargs: + args.append(kwargs["extend"]) + return [entity_instance(e) for e in ifcopenshell_wrapper.tree.select(*args)] + + def select_box(self, value, **kwargs) -> list[entity_instance]: + def unwrap(value): + if isinstance(value, entity_instance): + return value.wrapped_data + elif hasattr(value, "Get"): + return value.Get()[:3], value.Get()[3:] + return value + + args = [self, unwrap(value)] + if "extend" in kwargs or "completely_within" in kwargs: + args.append(kwargs.get("completely_within", False)) + if "extend" in kwargs: + args.append(kwargs.get("extend", -1.0e-5)) + return [entity_instance(e) for e in ifcopenshell_wrapper.tree.select_box(*args)] + + def clash_intersection_many( + self, + set_a: Iterable[entity_instance], + set_b: Iterable[entity_instance], + tolerance: float = 0.002, + check_all: bool = True, + ) -> tuple[ifcopenshell_wrapper.clash, ...]: + args = [self, [e.wrapped_data for e in set_a], [e.wrapped_data for e in set_b], tolerance, check_all] + return ifcopenshell_wrapper.tree.clash_intersection_many(*args) + + def clash_collision_many( + self, set_a: Iterable[entity_instance], set_b: Iterable[entity_instance], allow_touching=False + ) -> tuple[ifcopenshell_wrapper.clash, ...]: + args = [self, [e.wrapped_data for e in set_a], [e.wrapped_data for e in set_b], allow_touching] + return ifcopenshell_wrapper.tree.clash_collision_many(*args) + + def clash_clearance_many( + self, + set_a: Iterable[entity_instance], + set_b: Iterable[entity_instance], + clearance: float = 0.05, + check_all: bool = False, + ) -> tuple[ifcopenshell_wrapper.clash, ...]: + args = [self, [e.wrapped_data for e in set_a], [e.wrapped_data for e in set_b], clearance, check_all] + return ifcopenshell_wrapper.tree.clash_clearance_many(*args) + + @staticmethod + def get_clash_type(clash_type_i: int) -> ClashType: + """Convert clash type index to a readable string format. + + :param clash_type_i: Type index that comes from ``clash.clash_type``. + """ + return CLASH_TYPE_ITEMS[clash_type_i] + + +def create_shape( + settings: settings, + inst: entity_instance, + repr: Optional[entity_instance] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", +) -> Union[ShapeType, ShapeElementType, ifcopenshell_wrapper.Transformation, utils.shape_tuple, TopoDS.TopoDS_Shape]: + """ + Returns a geometric interpretation of the IFC entity instance + + Note that in Python, you must store a reference to the element returned by this function to prevent garbage + collection when you access its children. See #1124. + + :raises RuntimeError: If failed to process shape. You can turn detailed logging to get more details. + + :return: + - `inst` is IfcProduct and `repr` provided / None -> ShapeElementType\n + - `inst` is IfcRepresentation and `repr` is None -> ShapeType\n + - `inst` is IfcRepresentationItem and `repr` is None -> ShapeType\n + - `inst` is IfcProfileDef and `repr` is None -> ShapeType\n + - `inst` is IfcPlacement / IfcObjectPlacement -> Transformation\n + - `inst` is IfcTypeProduct and `repr` is None -> None\n + - `inst` is IfcTypeProduct and `repr` is provided -> RuntimeError + (for IfcTypeProducts provide just IfcRepresentation as `inst`).\n + + If 'use-python-opencascade' is enabled in settings then\n + - instead of ShapeElementType it returns shape_tuple, \n + - instead of ShapeType it returns TopoDS.TopoDS_Shape. + + Example: + + .. code:: python + + settings = ifcopenshell.geom.settings() + settings.set("use-python-opencascade", True) + + ifc_file = ifcopenshell.open(file_path) + products = ifc_file.by_type("IfcProduct") + + for i, product in enumerate(products): + if product.Representation is not None: + try: + created_shape = geom.create_shape(settings, inst=product) + shape = created_shape.geometry # see #1124 + shape_gpXYZ = shape.Location().Transformation().TranslationPart() # These are methods of the TopoDS_Shape class from pythonOCC + print(shape_gpXYZ.X(), shape_gpXYZ.Y(), shape_gpXYZ.Z()) # These are methods of the gpXYZ class from pythonOCC + except: + print("Shape creation failed") + """ + return wrap_shape_creation( + settings, + ifcopenshell_wrapper.create_shape( + settings, inst.wrapped_data, repr.wrapped_data if repr is not None else None, geometry_library + ), + ) + + +def map_shape(settings: settings, inst: entity_instance) -> ifcopenshell_wrapper.item: + """ + Returns an interpretation of the geometry encoded as per IfcOpenShell's taxonomy layer. + In many cases this is somewhat equivalent to the raw IFC data (but schema-agnostic in C++), but + in other cases such as IfcParameterizedProfileDef the returned item is the equivalent + of an explicit composite curve. + + >>> point = ifc_file.by_type('IfcCartesianPoint')[0] + >>> ifcopenshell.geom.map_shape(ifcopenshell.geom.settings(), point).components + (0.0, 0.0, 0.0) + """ + return ifcopenshell_wrapper.map_shape(settings, inst.wrapped_data) + + +@overload +def consume_iterator(it: iterator, with_progress: Literal[False] = False) -> Generator[IteratorOutput, None, None]: ... +@overload +def consume_iterator( + it: iterator, with_progress: Literal[True] +) -> Generator[tuple[int, IteratorOutput], None, None]: ... +@overload +def consume_iterator( + it: iterator, with_progress: bool +) -> Generator[Union[IteratorOutput, tuple[int, IteratorOutput]], None, None]: ... +def consume_iterator( + it: iterator, with_progress: bool = False +) -> Generator[Union[IteratorOutput, tuple[int, IteratorOutput]], None, None]: + if it.initialize(): + while True: + if with_progress: + yield it.progress(), it.get() + else: + yield it.get() + if not it.next(): + break + + +# Overloads need to cover different return types +# based on `with_progress` argument. +@overload +def iterate( + settings: settings, + file_or_filename: Union[file, str], + num_threads: int = 1, + include: Optional[Union[list[entity_instance], list[str]]] = None, + exclude: Optional[Union[list[entity_instance], list[str]]] = None, + *, + with_progress: Literal[False] = False, + cache: Optional[str] = None, + serializer_settings: Optional[serializer_settings] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", +) -> Generator[IteratorOutput, None, None]: ... +@overload +def iterate( + settings: settings, + file_or_filename: Union[file, str], + num_threads: int = 1, + include: Optional[Union[list[entity_instance], list[str]]] = None, + exclude: Optional[Union[list[entity_instance], list[str]]] = None, + *, + with_progress: Literal[True] = True, + cache: Optional[str] = None, + serializer_settings: Optional[serializer_settings] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", +) -> Generator[tuple[int, IteratorOutput], None, None]: ... +@overload +def iterate( + settings: settings, + file_or_filename: Union[file, str], + num_threads: int = 1, + include: Optional[Union[list[entity_instance], list[str]]] = None, + exclude: Optional[Union[list[entity_instance], list[str]]] = None, + *, + with_progress: bool = False, + cache: Optional[str] = None, + serializer_settings: Optional[serializer_settings] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", +) -> Generator[Union[IteratorOutput, tuple[int, IteratorOutput]], None, None]: ... +def iterate( + settings: settings, + file_or_filename: Union[file, str], + num_threads: int = 1, + include: Optional[Union[list[entity_instance], list[str]]] = None, + exclude: Optional[Union[list[entity_instance], list[str]]] = None, + *, + with_progress: bool = False, + cache: Optional[str] = None, + serializer_settings: Optional[serializer_settings] = None, + geometry_library: GEOMETRY_LIBRARY = "opencascade", +) -> Generator[Union[IteratorOutput, tuple[int, IteratorOutput]], None, None]: + """Get a geometry iterator for the provided file. + + :param cache: .h5 cache filepath (might not exist, will be created). + :param serializer_settings: Settings for cache serializer. Required if `cache` is provided. + """ + it = iterator(settings, file_or_filename, num_threads, include, exclude, geometry_library) + if cache: + assert serializer_settings, "`serializer_settings` argument is not optional if `cache` is provided." + hdf5_cache = serializers.hdf5(cache, settings, serializer_settings) + it.set_cache(hdf5_cache) + yield from consume_iterator(it, with_progress=with_progress) + + +def make_shape_function(fn): + def entity_instance_or_none(e): + return None if e is None else entity_instance(e) + + if has_occ: + + def _(schema, string_or_shape, *args): + if isinstance(string_or_shape, TopoDS.TopoDS_Shape): + string_or_shape = utils.serialize_shape(string_or_shape) + return entity_instance_or_none(fn(schema, string_or_shape, *args)) + + else: + + def _(schema, string, *args): + return entity_instance_or_none(fn(schema, string, *args)) + + return _ + + +serialise = make_shape_function(ifcopenshell_wrapper.serialise) +tesselate = make_shape_function(ifcopenshell_wrapper.tesselate) + + +def transform_string(v: Union[str, serializers.buffer]) -> serializers.buffer: + if isinstance(v, str): + return ifcopenshell_wrapper.buffer(v) + return v + + +class serializers: + # Python does not have automatic casts. The C++ serializers accept a stream_or_filename + # which in C++ can be automatically constructed from a filename string. In Python we + # have to implement this cast/construction explicitly by transform_string. + @staticmethod + def obj( + out_filename: Union[str, serializers.buffer], + mtl_filename: Union[str, serializers.buffer], + geometry_settings: settings, + settings: serializer_settings, + ) -> ifcopenshell_wrapper.WaveFrontOBJSerializer: + out_filename = transform_string(out_filename) + mtl_filename = transform_string(mtl_filename) + return ifcopenshell_wrapper.WaveFrontOBJSerializer(out_filename, mtl_filename, geometry_settings, settings) + + @staticmethod + def svg( + out_filename: Union[str, serializers.buffer], geometry_settings: settings, settings: serializer_settings + ) -> ifcopenshell_wrapper.SvgSerializer: + out_filename = transform_string(out_filename) + return ifcopenshell_wrapper.SvgSerializer(out_filename, geometry_settings, settings) + + # Hdf- Xml- and glTF- serializers don't support writing to a buffer, only to filename + # so no wrap_buffer_creation() for these serializers + xml = ifcopenshell_wrapper.XmlSerializer + buffer = ifcopenshell_wrapper.buffer + # gltf, hdf5, collada and json availability depend on IfcOpenShell configuration settings + try: + gltf = ifcopenshell_wrapper.GltfSerializer + except: + pass + try: + hdf5 = ifcopenshell_wrapper.HdfSerializer + except: + pass + try: + collada = ifcopenshell_wrapper.ColladaSerializer + except: + pass + try: + json = ifcopenshell_wrapper.JsonSerializer + except: + pass + # ttl is always available since it doesn't depend on any C++ libraries, + # just people might be using an outdated binary + if hasattr(ifcopenshell_wrapper, "TtlWktSerializer"): + + @staticmethod + def ttl( + out_filename: Union[str, serializers.buffer], geometry_settings: settings, settings: serializer_settings + ) -> ifcopenshell_wrapper.SvgSerializer: + out_filename = transform_string(out_filename) + return ifcopenshell_wrapper.TtlWktSerializer(out_filename, geometry_settings, settings) + + @classmethod + def guess_from_extension(cls, filepath: str): + ext = filepath.split(".")[-1] + mapping = { + "glb": "gltf", + "hdf": "hdf5", + "h5": "hdf5", + "hdf5": "hdf5", + "obj": "obj", + "svg": "svg", + "ttl": "ttl", + "xml": "xml", + "dae": "collada", + } + serializer_name = mapping.get(ext) + if not serializer_name: + raise ValueError(f"No serializer available for .{ext} file") + return getattr(cls, serializer_name) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/occ_utils.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/occ_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9835b48696ada2c4cdf0b23737a40b35d5eb011c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/occ_utils.py @@ -0,0 +1,289 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from __future__ import annotations +import inspect +import random +import operator +import warnings +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper + +from typing import NamedTuple, Any, Union +from typing_extensions import assert_never +from collections.abc import Iterable + +import OCC + +try: + from OCC.Core import V3d, TopoDS, gp, AIS, Quantity, BRepTools, Graphic3d + + USE_OCCT_HANDLE = False +except ImportError: + from OCC import V3d, TopoDS, gp, AIS, Quantity, BRepTools, Graphic3d + + USE_OCCT_HANDLE = True + + +class shape_tuple(NamedTuple): + """A tuple containing IfcOpenShell serialized element/shape and pythonOCC shape.""" + + data: Union[ifcopenshell_wrapper.SerializedElement, ifcopenshell_wrapper.Serialization] + geometry: TopoDS.TopoDS_Shape + styles: tuple[tuple[float, float, float, float], ...] + style_ids: tuple[int, ...] + + +handle, main_loop, add_menu, add_function_to_menu = None, None, None, None + +DEFAULT_STYLES = { + "DEFAULT": (0.7, 0.7, 0.7), + "IfcSite": (0.75, 0.8, 0.65), + "IfcSlab": (0.4, 0.4, 0.4), + "IfcWallStandardCase": (0.9, 0.9, 0.9), + "IfcWall": (0.9, 0.9, 0.9), + "IfcWindow": (0.75, 0.8, 0.75, 0.3), + "IfcDoor": (0.55, 0.3, 0.15), + "IfcBeam": (0.75, 0.7, 0.7), + "IfcRailing": (0.65, 0.6, 0.6), + "IfcMember": (0.65, 0.6, 0.6), + "IfcPlate": (0.8, 0.8, 0.8), +} + + +def initialize_display(): + import OCC.Display.SimpleGui + + global handle, main_loop, add_menu, add_function_to_menu + handle, main_loop, add_menu, add_function_to_menu = OCC.Display.SimpleGui.init_display() + + def setup(): + viewer_handle = handle.GetViewer() + viewer = viewer_handle.GetObject() if hasattr(viewer_handle, "GetObject") else viewer_handle + + def lights(): + viewer.InitActiveLights() + for _ in range(2): + try: + active_light = viewer.ActiveLight() + except BaseException: + break + yield active_light + viewer.NextActiveLights() + + lights = list(lights()) + for l in lights: + viewer.DelLight(l) + + if hasattr(V3d, "V3d_TypeOfOrientation_Yup_AxoRight"): + dirs = [[V3d.V3d_TypeOfOrientation_Yup_AxoRight], [V3d.V3d_TypeOfOrientation_Zup_AxoRight]] + else: + dirs = [(3, 2, 1), (-1, -2, -3)] + + for dir in dirs: + if OCC.VERSION < "7.5": + light = V3d.V3d_DirectionalLight(viewer_handle) + light.SetDirection(*dir) + else: + light = V3d.V3d_DirectionalLight(*dir) + viewer.SetLightOn(light.GetHandle() if USE_OCCT_HANDLE else light) + + setup() + return handle + + +def yield_subshapes(shape): + it = TopoDS.TopoDS_Iterator(shape) + while it.More(): + yield it.Value() + it.Next() + + +def display_shape(shape, clr=None, viewer_handle=None): + if viewer_handle is None: + viewer_handle = handle + + if isinstance(shape, shape_tuple): + shape, representation = shape.geometry, shape + else: + representation = None + + material = Graphic3d.Graphic3d_MaterialAspect(Graphic3d.Graphic3d_NOM_PLASTER) + + if representation and not clr: + if len(set(representation.styles)) == 1: + clr = representation.styles[0] + if min(clr) < 0.0 or max(clr) > 1.0: + clr = DEFAULT_STYLES.get(representation.data.type, DEFAULT_STYLES["DEFAULT"]) + + if clr: + ais = AIS.AIS_Shape(shape) + ais.SetMaterial(material) + + if isinstance(clr, str): + qclr = getattr( + Quantity, "Quantity_NOC_%s" % clr.upper(), getattr(Quantity, "Quantity_NOC_%s1" % clr.upper(), None) + ) + if qclr is None: + raise Exception("No color named '%s'" % clr.upper()) + elif isinstance(clr, Iterable): + clr = tuple(clr) + if len(clr) < 3 or len(clr) > 4: + raise Exception("Need 3 or 4 color components. Got '%r'." % len(clr)) + qclr = Quantity.Quantity_Color(clr[0], clr[1], clr[2], Quantity.Quantity_TOC_RGB) + elif isinstance(clr, Quantity.Quantity_Color): + qclr = clr + else: + raise Exception("Object of type %r cannot be used as a color." % type(clr)) + + ais.SetColor(qclr) + if isinstance(clr, tuple) and len(clr) == 4 and clr[3] < 1.0: + ais.SetTransparency(1.0 - clr[3]) + + elif representation and hasattr(AIS, "AIS_MultipleConnectedShape"): + default_style_applied = None + + ais = AIS.AIS_MultipleConnectedShape(shape) + + subshapes = list(yield_subshapes(shape)) + lens = len(representation.styles), len(subshapes) + if lens[0] != lens[1]: + warnings.warn("Unable to assign styles to subshapes. Encountered %d styles for %d shapes." % lens) + else: + for shp, stl in zip(subshapes, representation.styles): + subshape = AIS.AIS_Shape(shp) + if min(stl) < 0.0 or max(stl) > 1.0: + default_style_applied = stl = DEFAULT_STYLES.get( + representation.data.type, DEFAULT_STYLES["DEFAULT"] + ) + subshape.SetColor(Quantity.Quantity_Color(stl[0], stl[1], stl[2], Quantity.Quantity_TOC_RGB)) + subshape.SetMaterial(material) + if len(stl) == 4 and stl[3] < 1.0: + subshape.SetTransparency(1.0 - stl[3]) + ais.Connect(subshape.GetHandle()) + + # For some reason it is necessary to set transparency here again + # in order for transparency to be rendered on the subshape. + applied_styles = representation.styles + if default_style_applied: + if len(default_style_applied) == 3: + default_style_applied += (1.0,) + applied_styles += (default_style_applied,) + + if len(applied_styles): + # The only way for this not to be true if is the entire shape is NULL + min_transp = min(map(operator.itemgetter(3), applied_styles)) + if min_transp < 1.0: + ais.SetTransparency(1.0) + + else: + ais = AIS.AIS_Shape(shape) + ais.SetMaterial(material) + + def r(): + return random.random() * 0.3 + 0.7 + + clr = Quantity.Quantity_Color(r(), r(), r(), Quantity.Quantity_TOC_RGB) + ais.SetColor(clr) + + ais_handle = ais.GetHandle() if USE_OCCT_HANDLE else ais + viewer_handle.Context.Display(ais_handle, False) + + return ais_handle + + +def set_shape_transparency(ais, t, update_viewer=True): + handle.Context.SetTransparency(ais, t, update_viewer) + + +def get_bounding_box_center(bbox): + bbmin = [0.0] * 3 + bbmax = [0.0] * 3 + bbmin[0], bbmin[1], bbmin[2], bbmax[0], bbmax[1], bbmax[2] = bbox.Get() + return gp.gp_Pnt(*map(lambda xy: (xy[0] + xy[1]) / 2.0, zip(bbmin, bbmax))) + + +def serialize_shape(shape): + shapes = BRepTools.BRepTools_ShapeSet() + + # @todo provide method to get ifcopenshell's built-in occt version to + # see whether this is necessary + shapes.SetFormatNb(2) + + shapes.Add(shape) + + # Check if WriteToString method exists and has the correct signature + # In PythonOCC >= 7.8.0, WriteToString signature changed and requires additional arguments + if hasattr(shapes, "WriteToString"): + try: + # Try to get the method signature + sig = inspect.signature(shapes.WriteToString) + # If WriteToString has no parameters (just self), use it + # This works for PythonOCC < 7.8.0 + if len(sig.parameters) == 0: + return shapes.WriteToString() + except (ValueError, TypeError): + # If signature inspection fails, fall through to Write() method + pass + + # Fall back to Write() method for newer PythonOCC versions (>= 7.8.0) + # or when WriteToString is not available/compatible + return shapes.Write() + + +def create_shape_from_serialization( + brep_object: Union[ifcopenshell_wrapper.SerializedElement, ifcopenshell_wrapper.Serialization], +) -> Union[shape_tuple, TopoDS.TopoDS_Shape]: + brep_data, occ_shape, styles, style_ids = None, None, (), () + + is_product_shape = True + if isinstance(brep_object, ifcopenshell_wrapper.SerializedElement): + brep_data = brep_object.geometry.brep_data + styles = brep_object.geometry.surface_styles + style_ids = brep_object.geometry.surface_style_ids + elif isinstance(brep_object, ifcopenshell_wrapper.Serialization): + try: + brep_data = brep_object.brep_data + styles = brep_object.surface_styles + style_ids = brep_object.surface_style_ids + is_product_shape = False + except BaseException as e: + print("Error occurred creating a shape:", e) + else: + assert_never(brep_object) + + styles = tuple(styles[i : i + 4] for i in range(0, len(styles), 4)) + + if not brep_data: + return shape_tuple(brep_object, None, styles, style_ids) + + try: + if OCC.VERSION < "7.8": + ss = BRepTools.BRepTools_ShapeSet() + ss.ReadFromString(brep_data) + occ_shape = ss.Shape(ss.NbShapes()) + else: + ss = BRepTools.breptools() + occ_shape = ss.ReadFromString(brep_data) + except BaseException as e: + print("Error occurred parsing a shape from a string:", e) + + if is_product_shape: + return shape_tuple(brep_object, occ_shape, styles, style_ids) + else: + return occ_shape diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/stats.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/stats.py new file mode 100644 index 0000000000000000000000000000000000000000..364083acd78ad30dd1f4e59ae0918c4a21d4f289 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/geom/stats.py @@ -0,0 +1,246 @@ +import sys +from typing import Optional, IO +from itertools import accumulate + +from . import ifcopenshell_wrapper + + +class TransformDefaultDict: + def __init__(self, keyfunc=lambda x: x, default_factory=None): + """ + Similar to collections.defaultdict, but allows for storing + non-hashable keys by means of a transform function + """ + self.keyfunc = keyfunc + self.default_factory = default_factory + self._data = {} + self._original_keys = {} + + def __setitem__(self, key, value): + k = self.keyfunc(key) + self._data[k] = value + self._original_keys[k] = key + + def __getitem__(self, key): + k = self.keyfunc(key) + if k in self._data: + return self._data[k] + if self.default_factory is not None: + value = self.default_factory() + self._data[k] = value + self._original_keys[k] = key + return value + raise KeyError(key) + + def __contains__(self, key): + return self.keyfunc(key) in self._data + + def __delitem__(self, key): + k = self.keyfunc(key) + del self._data[k] + del self._original_keys[k] + + def __iter__(self): + return iter(self._original_keys.values()) + + def __len__(self): + return len(self._data) + + def items(self): + return ((self._original_keys[k], v) for k, v in self._data.items()) + + def keys(self): + return self._original_keys.values() + + def values(self): + return self._data.values() + + def get(self, key, default=None): + return self._data.get(self.keyfunc(key), default) + + def setdefault(self, key, default=None): + k = self.keyfunc(key) + if k not in self._data: + self._data[k] = default + self._original_keys[k] = key + return self._data[k] + + def update(self, other): + for k, v in other.items(): + self[k] = v + + def clear(self): + self._data.clear() + self._original_keys.clear() + + def __repr__(self): + items = ", ".join(f"{k!r}: {v!r}" for k, v in self.items()) + return f"{self.__class__.__name__}({{{items}}})" + + +class ProductCounter: + def __init__(self, only_with_representation=True): + self.total = 0 + transform_func = lambda decl: decl.name() if hasattr(decl, "name") else decl + self.counts = TransformDefaultDict(keyfunc=transform_func, default_factory=int) + self.counts_excl = TransformDefaultDict(keyfunc=transform_func, default_factory=int) + self.only_with_representation = only_with_representation + + def count(self, decl, values): + if decl._is("IfcProduct"): + if self.only_with_representation and values.get("Representation") is None: + return + self.counts_excl[decl] += 1 + while decl.name() != "IfcProduct": + self.counts[decl] += 1 + decl = decl.supertype() + self.total += 1 + + def print(self, out=sys.stdout): + if self.counts: + results = [] + + def process(ent, level=-1): + if ent in self.counts: + results.append((level, ent.name(), self.counts[ent])) + for subtype in ent.subtypes(): + process(subtype, level=level + 1) + + prod = next(iter(self.counts.keys())).schema().declaration_by_name("ifcproduct") + process(prod) + max_width = max(level * 2 + len(name) for level, name, _ in results) + for level, name, count in results: + print(" " * (level * 2), f"{name:<{max_width - level * 2}}", ": ", count, file=out, sep="") + + +class BooleanResultCounter: + def __init__(self, exclude_union=True): + self.total = 0 + self.exclude_union = exclude_union + + def count(self, decl, values): + if decl._is("IfcBooleanResult"): + if self.exclude_union and values.get("Operator") == "UNION": + return + self.total += 1 + + def print(self, out=sys.stdout): + print("IfcBooleanResult:", self.total, file=out) + + +class StatsCollector: + streamer: ifcopenshell_wrapper.InstanceStreamer + page_size: Optional[int] + file_stream: Optional[IO[str]] + + finalized: bool = False + needs_data: bool = False + + counters: list + + num_semis: int = 0 + + def __init__(self): + self.streamer = ifcopenshell_wrapper.InstanceStreamer() + self.needs_data = True + self.counters = [ProductCounter(), BooleanResultCounter()] + + def feedFromFile(self, f: Optional[IO[str]] = None): + if f: + self.file_stream = f + self.feed(self.file_stream.read(self.page_size)) + + def feed(self, data: str): + self.streamer.pushPage(data) + self.needs_data = False + self.num_semis = self.streamer.semicolonCount() + + @staticmethod + def fromFilePath(fn, page_size: int = 102400): + collector = StatsCollector() + collector.page_size = page_size + collector.feedFromFile(open(str(fn), encoding="ascii")) + return collector + + def next(self): + if self.num_semis > 0: + if inst := self.streamer.readInstancePy(True): + self.num_semis -= 1 + return inst["type"], dict(list(inst.items())[2:]) + else: + self.finalized = True + return None + elif self.file_stream: + self.feedFromFile() + return self.next() + else: + self.needs_data = True + return None + + def process(self): + if n := self.next(): + decl, values = n + else: + return + if decl.schema().name() == "HEADER_SECTION_SCHEMA": + return + for cnt in self.counters: + cnt.count(decl, values) + + def print(self, out=sys.stdout): + for cnt in self.counters: + print(type(cnt).__name__, file=out) + print("=" * len(type(cnt).__name__), file=out) + cnt.print(out) + + def includeElementTypesBasedOnBudget(self, priorities: dict, budget): + def specificity(decl, target): + if decl._is(target): + i = 0 + while decl.name() != target: + decl = decl.supertype() + i += 1 + return i + return None + + def calc_prio(ty): + # find most specific priority directive for the given type in ty + return min(((specificity(ty, k), v) for k, v in priorities.items() if ty._is(k)), default=(0, 0))[1] + + sorted_types = sorted(self.counters[0].counts_excl.keys(), key=calc_prio, reverse=True) + sorted_types = [s for s in sorted_types if not s._is("IfcFeatureElement")] + counts = [self.counters[0].counts_excl[v] for v in sorted_types] + + ccounts = list(accumulate(counts)) + + if ccounts[0] >= budget: + # At the very least include one type + return sorted_types[0:1] + + for i, s in enumerate(ccounts): + if s >= budget: + over = s - budget + under = budget - ccounts[i - 1] + k = i if over <= under else i - 1 + return sorted_types[0 : k + 1] + + # We're lucky we can render everything in budget + return sorted_types[:] + + +if __name__ == "__main__": + collector = StatsCollector.fromFilePath(sys.argv[1]) + while not collector.finalized: + collector.process() + collector.print() + print( + *collector.includeElementTypesBasedOnBudget( + { + "IfcWall": 3, + "IfcSlab": 3, + "IfcWindow": 2, + "IfcDoor": 2, + "IfcBuildingElement": 1, + } + ) + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/README.md b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2a1cf837062c76e0e0e767dd31dec03abb9f9004 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/README.md @@ -0,0 +1,100 @@ +## python-mvdxml + +A mvdXML checker and w3c SPARQL converter, as an IfcOpenShell submodule or stand-alone. + +WARNING: While this repository has many useful building blocks to build software around mvdXML and IFC, there are many mvdXML dialects and not all variants are likely to be fully supported. + +### Quickstart + +#### Extraction + +```python +import ifcopenshell +from ifcopenshell.mvd import mvd + +mvd_concept = mvd.open_mvd("examples/wall_extraction.mvdxml") +file = ifcopenshell.open("Duplex_A_20110505.ifc") + +all_data = mvd.get_data(mvd_concept, file, spreadsheet_export=True) + +non_respecting_entities = mvd.get_non_respecting_entities(file, all_data[1]) +respecting_entities = mvd.get_respecting_entities(file, all_data[1]) + + +``` + +```python +# Create a new file +new_file = ifcopenshell.file(schema=file.schema) +proj = file.by_type("IfcProject")[0] +new_file.add(proj) + +for e in respecting_entities: + new_file.add(e) + +new_file.write("new_file.ifc") +``` + +```python +# Visualize results +mvd.visualize(file, non_respecting_entities) +``` + +##### Validation + +~~~py +import ifcopenshell + +from ifcopenshell.mvd import mvd +from colorama import Fore +from colorama import Style + +concept_roots = list(ifcopenshell.mvd.concept_root.parse(MVDXML_FILENAME)) +file = ifcopenshell.open(IFC_FILENAME) + +tt = 0 # total number of tests +ts = 0 # total number of successful tests + +for concept_root in concept_roots: + print("ConceptRoot: ", concept_root.entity) + for concept in concept_root.concepts(): + tt = tt + 1 + print("Concept: ", concept.name) + try: + + if len(concept.template().rules) > 1: + attribute_rules = [] + for rule in concept.template().rules: + attribute_rules.append(rule) + rules_root = ifcopenshell.mvd.rule("EntityRule", concept_root.entity, attribute_rules) + else: + rules_root = concept.template().rules[0] + ts = ts + 1 + finst = 0 #failed instances + + for inst in file.by_type(concept_root.entity): + try: + data = mvd.extract_data(rules_root, inst) + valid, output = mvd.validate_data(concept, data) + if not valid: + finst = finst + 1 + print("[VALID]" if valid else Fore.RED +"[failure]"+Style.RESET_ALL, inst) + print(output) + except Exception as e: + print(Fore.RED+"EXCEPTION: ", e, Style.RESET_ALL,inst) + print () + print (int(finst), "out of", int(len(file.by_type(concept_root.entity))), "instances failed the check") + print ("---------------------------------") + except Exception as e: + print("EXCEPTION: "+Fore.RED,e,Style.RESET_ALL) + print("---------------------------------") + print("---------------------------------") +print("---------------------------------") + +tf = tt-ts # total number of failed tests + +print ("\nRESULTS OVERVIEW") +print ("Total number of tests: ",tt) +print ("Total number of executed tests: ", ts) +print ("Total number of failed tests: ", tf) +~~~ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0bad1632a76ef2f818000625dbe70cf25d3c35de --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__init__.py @@ -0,0 +1,199 @@ +from . import mvdxml_expression + +from xml.dom.minidom import parse, Element + +class rule(object): + """ + A class for representing an mvdXML EntityRule or AttributeRule + """ + + def __init__(self, tag, attribute, nodes, bind=None, optional=False): + self.tag, self.attribute, self.nodes, self.bind = tag, attribute, nodes, bind + self.optional = optional + + def to_string(self, indent=0): + # return "%s%s%s[%s](%s%s)%s" % ("\n" if indent else "", " "*indent, self.tag, self.attribute, "".join(n.to_string(indent+2) for n in self.nodes), ("\n" + " "*indent) if len(self.nodes) else "", (" -> %s" % self.bind) if self.bind else "") + return "<%s %s%s>" % (self.tag, f"{self.bind}=" if self.bind else "", self.attribute) + + def __repr__(self): + return self.to_string() + +class template(object): + """ + Representation of an mvdXML template + """ + + def __init__(self, concept, root, constraints=None, rules=None, parent=None): + self.concept, self.root, self.constraints, self.parent = concept, root, (constraints or []), parent + self.rules = rules or [] + self.entity = str(root.attributes['applicableEntity'].value) + try: + self.name = root.attributes['name'].value + except: + self.name = None + + def bind(self, constraints): + return template(self.concept, self.root, constraints, self.rules) + + def parse(self, visited=None): + for rules in self.root.getElementsByTagNameNS("*", "Rules"): + for r in rules.childNodes: + if not isinstance(r, Element): continue + self.rules.append(self.parse_rule(r, visited=visited)) + + def traverse(self, fn, root=None, with_parents=False): + def visit(n, p=root, ps=[root]): + if with_parents: + close = fn(rule=n, parents=ps) + else: + close = fn(rule=n, parent=p) + + for s in n.nodes: + visit(s, n, ps + [n]) + + if close: + close() + + for r in self.rules: + visit(r) + + def parse_rule(self, root, visited=None): + def visit(node, prefix="", visited=None, parent=None): + r = None + n = node + nm = None + p = prefix + optional = False + visited = set() if visited is None else visited + + if node.localName == "AttributeRule": + r = node.attributes["AttributeName"].value + try: + nm = node.attributes["RuleID"].value + except: + # without binding, it's wrapped in a SPARQL OPTIONAL {} clause + # Aim is to insert this clause once as high in the stack as possible + # All topmost attribute rules are optional anyway as in the binding requirements on existence is specified + + def child_has_ruleid_or_prefix(node): + if type(node).__name__ == "Element": + if "RuleID" in node.attributes or "IdPrefix" in node.attributes: + return True + for n in node.childNodes: + if child_has_ruleid_or_prefix(n): return True + + optional = node.parentNode.localName == "Rules" or not child_has_ruleid_or_prefix(node) + elif node.localName == "EntityRule": + r = node.attributes["EntityName"].value + elif node.localName == "Template": + ref = node.attributes['ref'].value + # we break infinite recursion using this set + if ref not in visited: + n = self.concept.template(ref, visited=visited | {ref}).root + try: + p = p + node.attributes["IdPrefix"].value + except: + pass + elif node.localName == "Constraint": + r = mvdxml_expression.parse(node.attributes["Expression"].value) + elif node.localName == "EntityRules": pass + elif node.localName == "AttributeRules": pass + elif node.localName == "Rules": pass + elif node.localName == "Constraints": pass + elif node.localName == "References": pass + elif node.localName == "Definitions": return + elif node.localName == "SubTemplates": return # @todo perhaps just traverse them? + else: + raise ValueError(node.localName) + + def _(n): + for subnode in n.childNodes: + if not isinstance(subnode, Element): continue + for x in visit(subnode, p, visited=visited): yield x + + if r: + R = rule(node.localName, r, list(_(n)), (p + nm) if nm else nm, optional=optional) + for rr in R.nodes: + rr.parent = R + yield R + else: + for subnode in n.childNodes: + if not isinstance(subnode, Element): continue + for x in visit(subnode, p, visited=visited): yield x + + return list(visit(root, visited=visited))[0] + +class concept_or_applicability(object): + """ + Representation of either a mvdXML Concept or the Applicability node. Basically a structure + for the hierarchical TemplateRule + """ + + def __init__(self, root, c): + self.root = root + self.concept_node = c + try: + self.name = c.attributes["name"].value + except: + # probably applicability and not concept + self.name = "Applicability" + + def template(self, id=None, visited=None): + if id is None: + id = self.concept_node.getElementsByTagNameNS("*","Template")[0].attributes['ref'].value + + for node in self.root.dom.getElementsByTagNameNS('*',"ConceptTemplate"): + if node.attributes["uuid"].value == id: + t = template(self, node) + t.parse(visited=visited) + t_with_rules = t.bind(self.rules()) + return t_with_rules + + def rules(self): + # Get the top most TemplateRule and traverse + try: + rules = self.concept_node.getElementsByTagNameNS("*","TemplateRules")[0] + except: + return [] + + def visit(rules): + def _(): + for i, r in enumerate([c for c in rules.childNodes if isinstance(c, Element)]): + if i: + yield rules.attributes["operator"].value + if r.localName == "TemplateRules": + yield visit(r) + elif r.localName == "TemplateRule": + yield mvdxml_expression.parse(r.attributes["Parameters"].value) + else: + raise Exception() + + return list(_()) + + return visit(rules) + +class concept_root(object): + def __init__(self, dom, root): + self.dom, self.root = dom, root + self.name = root.attributes['name'].value + self.entity = str(root.attributes['applicableRootEntity'].value) + + def applicability(self): + return concept_or_applicability(self, self.root.getElementsByTagNameNS("*","Applicability")[0]) + + def concepts(self): + for c in self.root.getElementsByTagNameNS("*","Concept"): + yield concept_or_applicability(self, c) + + @staticmethod + def parse(fn): + dom = parse(fn) + if len(dom.getElementsByTagNameNS("*","ConceptRoot")): + for root in dom.getElementsByTagNameNS("*","ConceptRoot"): + CR = concept_root(dom, root) + yield CR + else: + for templ in dom.getElementsByTagNameNS("*","ConceptTemplate"): + t = template(None, templ) + t.parse() + yield t diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__main__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..e0f84b2941e7ee74a6a86cb7d9272316078ece56 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/__main__.py @@ -0,0 +1,35 @@ +from __future__ import print_function + +if __name__ == "__main__": + import sys + from . import concept_root + + if len(sys.argv) == 2: + mvdfn = sys.argv[1] + for mvd in concept_root.parse(mvdfn): + + def dump(rule, parents): + print(" " * len(parents), rule.tag, rule.attribute) + + for c in mvd.concepts(): + print(c.name) + print() + + t = c.template() + print("RootEntity", t.entity) + t.traverse(dump, with_parents=True) + print(" ".join(map(str, t.constraints))) + + print() + + elif len(sys.argv) == 3: + from . import sparql + mvdfn,ttlfn = sys.argv[1:] + sparql.derive_prefix(ttlfn) + ttlfn = sparql.infer_subtypes(ttlfn) + for mvd in concept_root.parse(mvdfn): + sparql.executor.run(mvd, mvdfn, ttlfn) + + else: + print(sys.executable, "ifcopenshell.mvd", "<.mvdxml>") + print(sys.executable, "ifcopenshell.mvd", "<.mvdxml>", "<.ifc>") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvd.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvd.py new file mode 100644 index 0000000000000000000000000000000000000000..d6c257fbff2b9b9f8c253be44e7a5a31acd0a878 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvd.py @@ -0,0 +1,489 @@ +import ifcopenshell +import ifcopenshell.geom + +import itertools +import os + +import xlsxwriter +import csv + + +def is_applicability(concept): + """ + Check whether the Concept created has a filtering purpose. + Actually, MvdXML has a specific Applicability node. + + :param concept: mvdXML Concept object + """ + return concept.name.startswith("AP") + + +def merge_dictionaries(dicts): + d = {} + for e in dicts: + d.update(e) + return d + + +def extract_data(mvd_node, ifc_data): + """ + Recursively traverses mvdXML Concept tree structure. + This tree is made of different mvdXML Rule nodes: AttributesRule + and EntityRule. + + :param mvd_node: an mvdXML Concept + :param ifc_data: an IFC instance or an IFC value + + + """ + to_combine = [] + return_value = [] + + if len(mvd_node.nodes) == 0: + if mvd_node.tag == "AttributeRule": + try: + values_from_attribute = getattr(ifc_data, mvd_node.attribute) + return [{mvd_node: values_from_attribute}] + except: + return [{mvd_node: "Invalid Attribute"}] + + else: + return [{mvd_node: ifc_data}] + + if mvd_node.tag == 'AttributeRule': + data_from_attribute = [] + try: + values_from_attribute = getattr(ifc_data, mvd_node.attribute) + if values_from_attribute is None: + return [{mvd_node:"Nonexistent value"}] + + except: + return [{mvd_node:"Invalid attribute rule"}] + + + if isinstance(values_from_attribute, (list, tuple)): + if len(values_from_attribute) == 0: + return [{mvd_node: 'empty data structure'}] + data_from_attribute.extend(values_from_attribute) + + else: + data_from_attribute.append(values_from_attribute) + + for child in mvd_node.nodes: + for data in data_from_attribute: + child_values = extract_data(child, data) + if isinstance(child_values, (list, tuple)): + return_value.extend(child_values) + else: + return_value.append(child_values) + return return_value + + elif mvd_node.tag == 'EntityRule': + # Avoid things like Quantities on Psets + if len(mvd_node.nodes): + if isinstance(ifc_data, ifcopenshell.entity_instance) and not ifc_data.is_a(mvd_node.attribute): + return [] + + for child in mvd_node.nodes: + if child.tag == "Constraint": + on_node = child.attribute[0].c + on_node = on_node.replace("'", "") + if isinstance(ifc_data, ifcopenshell.entity_instance): + ifc_type = type(ifc_data[0]) + typed_node = (ifc_type)(on_node) + + if ifc_data[0] == typed_node: + return [{mvd_node: ifc_data}] + + elif ifc_data == on_node: + return [{mvd_node: ifc_data}] + else: + to_combine.append(extract_data(child, ifc_data)) + + if len(to_combine): + return_value = list(map(merge_dictionaries, itertools.product(*to_combine))) + + return return_value + + +def open_mvd(filename): + """ + Open an mvdXML file. + + :param filename: Path of the mvdXML file. + :return: mvdXML Concept instance. + """ + my_concept_object = list(ifcopenshell.mvd.concept_root.parse(filename))[0] + return my_concept_object + + +def format_data_from_nodes(recurse_output): + """ + Enable to format data collected such that the value to be exported is extracted. + + :param recurse_output: Data extracted from the recursive function + + """ + if len(recurse_output) > 1: + output = [] + for resulting_dict in recurse_output: + intermediate_storing = [] + for value in resulting_dict.values(): + intermediate_storing.append(value) + output.extend(intermediate_storing) + return output + + elif len(recurse_output) == 1: + return_list = [] + intermediate_list = list(recurse_output[0].values()) + if len(intermediate_list) > 1: + returned_value = intermediate_list + for element in intermediate_list: + # In case of a property that comes with all its path + # (like ['PSet_WallCommon, 'IsExternal', IfcBoolean(.F.) + # return only the list element which is not of string type + # todo: check above condition with ifcopenshell type + if not isinstance(element, str): + returned_value = element + if returned_value != intermediate_list: + return returned_value + else: + return intermediate_list + else: + return intermediate_list[0] + + else: + return [] + + +def get_data_from_mvd(entities, tree, filtering=False): + """ + Apply the recursive function on the entities to return + the values extracted. + + :param entities: IFC instances to be processed. + :param tree: mvdXML Concept instance tree root. + :param filtering: Indicates whether the mvdXML tree is an applicability. + + """ + filtered_entities = [] + extracted_entities_data = {} + + for entity in entities: + entity_id = entity.GlobalId + combinations = extract_data(tree, entity) + desired_results = [] + + for dictionary in combinations: + desired_results.append(dictionary) + + output = format_data_from_nodes(desired_results) + + if filtering: + if len(output): + extracted_entities_data[entity_id] = output + else: + extracted_entities_data[entity_id] = output + + return extracted_entities_data + + +def correct_for_export(all_data): + """ + Process the data for spreadsheet export. + """ + for d in all_data: + for k, v in d.items(): + if isinstance(v, list) or isinstance(v, tuple): + if len(v): + new_list = [] + for data in v: + new_list.append(str(data)) + d[k] = ','.join(new_list) + if len(v) == 0: + d[k] = 0 + + elif isinstance(v, ifcopenshell.entity_instance): + d[k] = v[0] + return all_data + + +def export_to_xlsx(xlsx_name, concepts, all_data): + """ + Export data towards XLSX spreadsheet format. + + :param xlsx_name: Name of the outputted file. + :param concepts: List of mvdXML Concept instances. + :param all_data: Data extracted. + + """ + + if not os.path.isdir("spreadsheet_output/"): + os.mkdir("spreadsheet_output/") + + workbook = xlsxwriter.Workbook("spreadsheet_output/" + xlsx_name) + worksheet = workbook.add_worksheet() + # Formats + bold_format = workbook.add_format() + bold_format.set_bold() + bold_format.set_center_across() + # Write first row + column_index = 0 + for concept in concepts: + worksheet.write(0, column_index, concept.name, bold_format) + column_index += 1 + + col = 0 + for feature in all_data: + row = 1 + for d in feature.values(): + worksheet.write(row, col, d) + row += 1 + col += 1 + + workbook.close() + + +def export_to_csv(csv_name, concepts, all_data): + """ + Export data towards CSV spreadsheet format. + + :param csv_name: Name of the file outputted file. + :param concepts: List of mvdXML Concept instances. + :param all_data: Data extracted. + """ + + if not os.path.isdir("spreadsheet_output/"): + os.mkdir("spreadsheet_output/") + + with open('spreadsheet_output/' + csv_name, 'w', newline='') as f: + writer = csv.writer(f) + header = [concept.name for concept in concepts] + first_row = writer.writerow(header) + + values_by_row = [] + for val in all_data: + values_by_row.append(list(val.values())) + entities_number = len(all_data[0].keys()) + for i in range(0, entities_number): + row_to_write = [] + for r in values_by_row: + row_to_write.append(r[i]) + + f = writer.writerow(row_to_write) + + +def get_data(mvd_concept, ifc_file, spreadsheet_export=True): + """ + Use the majority of all the other functions to return the data + queried by the mvdXML file in python format. + + :param mvd_concept: mvdXML Concept instance. + :param ifc_file: IFC file from any schema. + :param spreadsheet_export: The spreadsheet export is carried out when set to True. + + + + """ + + # Check if IFC entities have been filtered at least once + filtered = 0 + + entities = ifc_file.by_type(mvd_concept.entity) + selected_entities = entities + verification_matrix = {} + for entity in selected_entities: + verification = dict() + verification_matrix[entity.GlobalId] = verification + + # For each Concept(ConceptTemplate) in the ConceptRoot + concepts = sorted(mvd_concept.concepts(), key=is_applicability, reverse=True) + all_data = [] + counter = 0 + for concept in concepts: + if is_applicability(concept): + filtering = True + else: + filtering = False + + # Access all the Rules of the ConceptTemplate + if len(concept.template().rules) > 1: + attribute_rules = [] + for rule in concept.template().rules: + attribute_rules.append(rule) + rules_root = ifcopenshell.mvd.rule("EntityRule", mvd_concept.entity, attribute_rules) + else: + rules_root = concept.template().rules[0] + + + extracted_data = get_data_from_mvd(selected_entities, rules_root, filtering=filtering) + all_data.append(extracted_data) + + if filtering: + filtered = 1 + new_entities = [] + for entity_id in all_data[counter].keys(): + if len(all_data[counter][entity_id]) != 0: + entity = ifc_file.by_id(entity_id) + new_entities.append(entity) + + selected_entities = new_entities + not_respecting_entities = [item for item in entities if item not in selected_entities] + for entity in entities: + val = 0 + if entity in not_respecting_entities: + val = 1 + verification_matrix[entity.GlobalId].update({concept.name: val}) + counter += 1 + + all_data = correct_for_export(all_data) + + if spreadsheet_export: + if filtered != 0: + export_name = "output_filtered" + else: + export_name = "output_non_filtered" + export_to_xlsx(export_name + '.xlsx', concepts, all_data) + export_to_csv(export_name + '.csv', concepts, all_data) + + + return all_data, verification_matrix + + +def get_non_respecting_entities(file, verification_matrix): + non_respecting = [] + for k, v in verification_matrix.items(): + entity = file.by_id(k) + print(list(v.values())) + if sum(v.values()) != 0: + non_respecting.append(entity) + + return non_respecting + + + + +def get_respecting_entities(file, verification_matrix): + respecting = [] + for k, v in verification_matrix.items(): + entity = file.by_id(k) + print(list(v.values())) + if sum(v.values()) == 0: + respecting.append(entity) + + return respecting + + +def visualize(file, not_respecting_entities): + """ + Visualize the instances of the entity type targeted by the mvdXML ConceptRoot. + At display, a color differentiation is made between the entities which comply with + mvdXML requirements and the ones which don't. + + :param file: IFC file from any schema. + :param not_respecting_entities: Entities which don't comply with mvdXML requirements. + + """ + + s = ifcopenshell.geom.main.settings() + s.set(s.USE_PYTHON_OPENCASCADE, True) + s.set(s.DISABLE_OPENING_SUBTRACTIONS, False) + + viewer = ifcopenshell.geom.utils.initialize_display() + + entity_type = not_respecting_entities[0].is_a() + + other_entities = [x for x in file.by_type("IfcBuildingElement") if x.is_a() != str(entity_type)] + + set_of_entities = set(not_respecting_entities) | set(file.by_type(entity_type)) + set_to_display = set_of_entities.union(set(other_entities)) + + for el in set_to_display: + if el in not_respecting_entities: + c = (1, 0, 0, 1) + elif el in other_entities: + c = (1, 1, 1, 0) + else: + c = (0, 1, 0.5, 1) + + try: + shape = ifcopenshell.geom.create_shape(s, el) + # OCC.BRepTools.breptools_Write(shape.geometry, "test.brep") + ds = ifcopenshell.geom.utils.display_shape(shape, clr=c) + except: + pass + + viewer.FitAll() + + ifcopenshell.geom.utils.main_loop() + + +def validate_data(concept, data): + import io + import ast + import operator + from functools import reduce, partial + + rules = [x[0] for x in concept.rules() if not isinstance(x, str)] + + def transform_data(d): + """ + Transform dictionary keys from tree nodes to rule ids + """ + + return {(k.parent if k.bind is None and k.parent.bind is not None else k).bind: v for k, v in d.items()} + + + def parse_mvdxml_token(v): + # @todo make more permissive and tolerant + return ast.literal_eval(v) + + + data = list(map(transform_data, data)) + + output = io.StringIO() + + # https://stackoverflow.com/a/70227259 + def operation_reduce(x, y): + """ + Takes alternating value and function as input and + reduces while applying function + """ + + if callable(x): + return x(y) + else: + return partial(y, x) + + + def apply_rules(): + + for r in rules: + + def apply_data(): + + for d in data: + + def translate(v): + if isinstance(v, str): + return getattr(operator, v.lower() + "_") + else: + if v.b == "Value": + return d.get(v.a) == parse_mvdxml_token(v.c) + elif v.b == "Type": + return d.get(v.a) and d.get(v.a).is_a(parse_mvdxml_token(v.c)) + + r2 = list(map(translate, r)) + yield reduce(operation_reduce, r2) + + v = any(list(apply_data())) + print(("Met:" if v else "Not met:"), r, file=output) + yield v + + + valid = all(list(apply_rules())) + return valid, output.getvalue() + + +if __name__ == '__main__': + print('functions to parse MVD rules and extract IFC data/filter IFC entities from them') diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvdxml_expression.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvdxml_expression.py new file mode 100644 index 0000000000000000000000000000000000000000..cc008aaa2dca1bbafe2fc90ece3c17965c08e714 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/mvdxml_expression.py @@ -0,0 +1,29 @@ +import pyparsing as pp + +class node(object): + def __init__(self, args): + if len(args) == 3 and args[1] == '=': + self.a, self.b, self.c = args[0], None, args[2] + elif (args[1], args[3], args[4]) == ('[', ']', '='): + self.a, self.b, self.c = args[0], args[2], args[5] + else: + self.a, self.b, self.c = None, args[1], args[4] + + def __repr__(self): return "{%s[%s]=%s}" % (self.a, self.b, self.c) + +word = pp.Word(pp.alphanums+"_"+" "+"/"+"#") +quoted = pp.Combine("'" + word + "'") +bool_value = pp.CaselessLiteral("TRUE") | pp.CaselessLiteral("FALSE") +ref_val = word + "[" + word + "]" +rhs = quoted | bool_value | ref_val | word +stmt = (pp.Optional(word) + pp.Optional("[" + word + "]") + "=" + rhs).setParseAction(node) +bool_op = pp.CaselessLiteral("AND") | pp.CaselessLiteral("OR") +grammar = stmt + pp.Optional(pp.OneOrMore(bool_op + stmt)) + +def parse(exprs): + def _(): + for expr in exprs.split(";"): + expr = "".join(c for c in expr if c not in "\r\n") + if not expr: continue + yield grammar.parseString(expr) + return list(_()) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/sparql.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/sparql.py new file mode 100644 index 0000000000000000000000000000000000000000..3dd35a7e23c16be35a44ce957870dea54bf49e22 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/mvd/sparql.py @@ -0,0 +1,609 @@ +import io +import os +import csv +import platform +import tabulate +import operator +import itertools +import subprocess +import ifcopenshell + +from collections import defaultdict + +import mvdxml_expression + +def camel(s): + """ + Camel case conversion function + :param s: str + :return: camel case formatted string + """ + + s = s.title().replace(" ", "") + if s.endswith("s"): s = s[:-1] + return s[0].lower() + s[1:] + + +STANDARD_PREFIXES = { + 'rdf': '', + 'owl': '', + 'xsd': '', + 'list': '', + 'ifcowl': '', + 'express': '', +} + +def derive_prefix(ttlfn): + with open(ttlfn, "r") as f: + for ln in f: + ln.strip() + if ln.startswith("@prefix ifcowl"): + uri = ln.split(':', 1)[1].strip()[:-1].strip() + print("Detected ifcowl prefix", uri) + STANDARD_PREFIXES['ifcowl'] = uri + break + +def withschema(fn): + """ + Decorator that takes a function and adds an IFC latebound schema definition + in the first parameter. The schema identifier is looked up based on the + global ifcOwl prefix. + + :param fn: input function + :return: decorated function + """ + + def _(*args, **kwargs): + schema_name = STANDARD_PREFIXES['ifcowl'].split('/')[-1][:-2] + if "_" in schema_name: + schema_name = schema_name.split('_')[0] + S = ifcopenshell.ifcopenshell_wrapper.schema_by_name(schema_name) + return fn(S, *args, **kwargs) + return _ + +noop = lambda *args: None + +class rule_binding(object): + """ + Object for mapping rules to generated SPARQL variables + """ + def __init__(self): + pass + + +class builder(object): + """ + A helper class for dealing with SPARQL query statements + """ + + def __init__(self): + self.prefixes = {"express": "", "ifcowl": ""} + self.statements = [] + + def append(self, *stmt): + if len(stmt) == 3: + for i, pos in enumerate(stmt[1:]): + for po in pos.split("/"): + if ":" in pos: + a, b = po.split(':') + self.prefixes[a] = '' + self.statements.append(stmt) + + def bind(self, di): + for k in set(self.prefixes.keys()) & set(di.keys()): + self.prefixes[k] = di[k] + + def x(self): + return len(self.statements) + + def __repr__(self): + def f(s): + S = " ".join(s) + if len(s) == 3: S += ' .' + return S + + def g(s): + return "PREFIX %s: %s" % s + + return "\n".join(itertools.chain( + (g(s) for s in self.prefixes.items()), + (f(s) for s in self.statements) + )) + +class ifcOwl(object): + """ + Helper class with static function for dealing with ifcOwl attribute names + """ + + @staticmethod + @withschema + def supertypes(S, entity): + """ + Yields ifcOwl subtypes for the supplied entity name + + :param S: schema definition (from decorator) + :param entity: entity name string + :return: + """ + + a, b = entity.split('#') + try: + en = S.declaration_by_name(b) + if en.__class__.__name__ == "entity": + while en.supertype(): + yield "%s#%s" % (a, en.supertype().name()) + en = en.supertype() + except: pass + + @staticmethod + def get_names(e, c): + """ + Returns inverse or forward attribute names for latebound entity definition + + :param e: latebound entity definition + :param c: either 'all_attributes' or 'all_inverse_attributes' + :return: set of attribute names + """ + + return set(map(lambda a: a.name(), getattr(e, c)())) + + @staticmethod + @withschema + def is_boxed(S, entity, attribute, predCount=0): + """ + Returns whether the entity attribute should be boxed in ifcOwl. Which means + that there is an additional indirection. + + inst:IfcRelDefinesByType_21937 + ifcowl:globalId_IfcRoot inst:IfcGloballyUniqueId_117684 ; + + inst:IfcGloballyUniqueId_117684 + rdf:type ifcowl:IfcGloballyUniqueId ; + express:hasString "2P9FPkykn0r8rCpmBxZH0w" . + + :param S: schema definition (from decorator) + :param entity: entity name string + :param attribute: attribute name string + :param predCount: numeric identifier to postfix predicate identifier in case of SELECT types + :return: either a predicate from the express namespace or a variable postfixed with predCount + """ + + en = S.declaration_by_name(entity) + attr = [a for a in en.all_attributes() if a.name() == attribute][0] + ty = attr.type_of_attribute() + is_boxed = False + while isinstance(ty, ifcopenshell.ifcopenshell_wrapper.named_type): + ty = ty.declared_type() + + if isinstance(ty, ifcopenshell.ifcopenshell_wrapper.select_type): + + # Just assume there is going to be some boxed type in here. + # It could be all instance references, but fact is we don't know at this moment. + # It's likely that mvdXML will only bind to literals? + + return "?pred%d" % predCount + + else: + + while isinstance(ty, ifcopenshell.ifcopenshell_wrapper.type_declaration): + is_boxed = True + ty = ty.declared_type() + if is_boxed and isinstance(ty, ifcopenshell.ifcopenshell_wrapper.simple_type): + ty = ty.declared_type() + return "express:has%s%s" % (ty[0].upper(), ty[1:]) + + return False + + @staticmethod + @withschema + def name(S, entity, attribute): + """ + Names the entity attribute according to ifcOwl + + :param S: + :param entity: + :param attribute: + :return: + """ + en = S.declaration_by_name(entity) + + while True: + st = en.supertype() + + attribute_names = ifcOwl.get_names(en, "all_attributes") | \ + ifcOwl.get_names(en, "all_inverse_attributes") + + if st: + attribute_names -= ifcOwl.get_names(st, "all_attributes") | \ + ifcOwl.get_names(st, "all_inverse_attributes") + + if attribute in attribute_names: + return "ifcowl:" + attribute[0].lower() + attribute[1:] + "_" + en.name() + + en = st + + if en is None: + raise AttributeError("%s not found on %s" % (attribute, entity)) + + @staticmethod + @withschema + def is_select(S, decl_name): + """ + Returns True when the declaration is a select type + + :param S: + :param decl_name: + :return: + """ + decl = S.declaration_by_name(decl_name) + return isinstance(decl, ifcopenshell.ifcopenshell_wrapper.select_type) + + @staticmethod + @withschema + def is_inverse(S, entity, attribute): + """ + When entity attribute is an INVERSE attribute, returns the opposite + forward entity and attribute name. Otherwise returns (False, False) + + :param S: + :param entity: + :param attribute: + :return: + """ + + en = S.declaration_by_name(entity) + attrs = [a for a in en.all_inverse_attributes() if a.name() == attribute] + if not attrs: return False, False + + a = attrs[0] + assert a.type_of_aggregation_string() == "set" + entity = a.entity_reference().name() + attr = a.attribute_reference().name() + return "ifcowl:" + entity, ifcOwl.name(entity, attr) + +class convertor(object): + + @staticmethod + def convert(item, *args, **kwargs): + return getattr(convertor, item.__class__.__name__)(item, *args, **kwargs) + + @staticmethod + def concept_or_applicability(concept): + """ + Convert the Template (SELECT ... WHERE {}) structure and TemplateRule (FILTER) + + :param qtype: 0 or 1, 0 for a general query matching the applicableRootEntity + :return: + """ + + bld = builder() + t = concept.template() + bld.append("# %s" % camel(concept.root.name)) + convertor.template(t, bld, concept.root.entity) + bld.bind(STANDARD_PREFIXES) + + return bld + + @staticmethod + def root(rootEntity): + args = ["URI", "GlobalId"] + + b = builder() + b.args = args + b.append("SELECT " + " ".join("?" + a for a in args) + " WHERE {") + b.append("?URI", "rdf:type", "ifcowl:%s" % rootEntity) + b.append("?URI", "ifcowl:globalId_IfcRoot/express:hasString", "?GlobalId") + b.append("}") + b.bind(STANDARD_PREFIXES) + + return b + + @staticmethod + def template(template, bld = None, rootEntity = None): + if bld is None: + bld = builder() + + if rootEntity is None: + rootEntity = template.entity + + args = ["URI", "GlobalId"] + + def enumerate(rule, **kwargs): + if rule.bind: + args.append(rule.bind) + + template.traverse(enumerate) + + bld.args = args + + bld.append("SELECT " + " ".join("?" + a for a in args) + " WHERE {") + + args = set(args) + + bld.append("?URI", "rdf:type", "ifcowl:%s" % rootEntity) + bld.append("?URI", "ifcowl:globalId_IfcRoot/express:hasString", "?GlobalId") + + nm = "?URI" + ROOT = type('_', (), {'attribute': rootEntity})() + # rule_stack = [ROOT] + # name_stack = [nm] + # callback_stack = [noop] + # G = type('_', (object,), dict(indent = 0, nm = nm, next_nm=None, first=True)) + + rule_mapping = defaultdict(rule_binding) + rule_mapping[ROOT].name = nm + + def build(rule, parents): + # print "AAA", rule.tag, parent.tag if parent else parent + # print map(id, rule_stack) + # print name_stack + INDENT = " " * (len(parents) * 2) + return_value = None + + if rule.optional: + bld.append(INDENT + "OPTIONAL {") + return_value = lambda: bld.append(INDENT + "}") + + if rule.tag == "EntityRule": + # G.nm = G.next_nm + + if not ifcOwl.is_select(rule.attribute): + # SELECT types should never be qualified as they cannot be inferred + bld.append(INDENT + rule_mapping[parents[-1]].name, "rdf:type", "ifcowl:" + rule.attribute) + + # propagate binding name + rule_mapping[rule].name = rule_mapping[parents[-1]].name + else: + + # if rule_stack[-1] is parent: + # # print "sl", id(parent), id(rule) + # # same level + # pass + # elif parent in rule_stack: + # # print "up", id(parent), id(rule) + # while rule_stack[-1] is not parent: + # # rule_stack.pop() + # name_stack.pop() + # callback_stack.pop()() + # else: + # # print "dn", id(parent), id(rule) + # pass + + indirect = False + + if rule.bind: + if len(rule.nodes) == 1: + indirect = ifcOwl.is_boxed(parents[-1].attribute, rule.attribute, predCount=bld.x()) + + if rule.bind and not indirect: + next_nm = "?" + rule.bind + else: + next_nm = "?var%d" % bld.x() + + rule_mapping[rule].name = next_nm + + inventy, invattr = ifcOwl.is_inverse(parents[-1].attribute, rule.attribute) + if invattr: + # This seems not to be necessary, because the entity name is also stated in mvdXML + # q.append( + # next_nm, + # "rdf:type", + # inventy + # ) + bld.append( + INDENT + next_nm, + invattr, + rule_mapping[parents[-1]].name + ) + else: + bld.append( + INDENT + rule_mapping[parents[-1]].name, + ifcOwl.name(parents[-1].attribute, rule.attribute), + next_nm + ) + + if rule.bind and indirect: + # For boxed literals, only strings atm + bld.append(INDENT + next_nm, indirect, "?" + rule.bind) + + # rule_stack.append(rule) + # name_stack.append(next_nm) + # if rule.optional: + # callback_stack.append(lambda: q.append(INDENT+"}")) + # else: + # callback_stack.append(noop) + + # print(q.statements[-1]) + + return return_value + + template.traverse(build, root=ROOT, with_parents=True) + + # while callback_stack: + # callback_stack.pop()() + + if template.params: + bld.append(convertor.build_filter(template)) + + bld.append("}") + + return bld + + @staticmethod + def build_filter(self): + def v(p): + if isinstance(p, mvdxml_expression.node): + if p.b == "Value": + if p.c.lower() in {'true', 'false'}: + yield "(%s?%s)" % ("!" if p.c.lower() == "false" else "", p.a) + else: + yield "(?%s = %s)" % (p.a, p.c) + elif p.b == "Exists": + yield "(!isBLANK(?%s))" % p.a + else: + raise Exception("Unsupported " + p.b) + elif isinstance(p, str): + yield { + "and": "&&", + "or": "||", + "not": "&& !" + }[p.lower()] + else: + yield "(" + for q in p: + yield from v(q) + yield ")" + + return "FILTER(%s)" % " ".join(v(self.params)) + +def infer_subtypes(ttlfn): + # Disabled currently + return ttlfn + + if not os.path.exists(ttlfn + ".subclass.nt"): + + print("Inferring supertype relationships") + + import hashlib + import rdflib + + a = rdflib.namespace.RDF.type + + # Hardly possible on Windows + # graph = rdflib.Graph("Sleepycat") + # graph.open("store", create=True) + # graph.parse(ttlfn) + + from sqlalchemy import create_engine + from rdflib_sqlalchemy.store import SQLAlchemy + + if os.path.exists("db.sqlite"): + os.unlink("db.sqlite") + + uri = rdflib.Literal("sqlite:///%(here)s/db.sqlite" % {"here": os.getcwd()}) + ident = rdflib.URIRef(hashlib.sha1(ttlfn.encode()).hexdigest()) + engine = create_engine(uri) + store = SQLAlchemy( + identifier=ident, + engine=engine, + ) + graph = rdflib.Graph( + store, + identifier=ident, + ) + graph.open(uri, create=True) + graph.parse(ttlfn, format="ttl") + + # print out all the triples in the graph + def _(): + for subject, predicate, object in graph: + if predicate == a: + for sup in ifcOwl.supertypes(object): + yield subject, a, rdflib.URIRef(sup) + + for stmt in list(_()): + graph.add(stmt) + + graph.serialize(destination=ttlfn + ".subclass.nt", format="nt") + + ttlfn += ".subclass.nt" + +if platform.system() == "Windows": + JENA_SPARQL = os.path.join(os.environ.get("JENA_HOME"), "bat", "sparql.bat") +else: + JENA_SPARQL = "sparql" + +class executor(object): + @staticmethod + def run(CR, fn, ttlfn): + """ + Generates SPARQL queries for the parsed MVD and executes on the building model + + :param CR: A parsed concept root + :param fn: A filename used as the prefix to store generate SPARQL queries to disk + :param ttlfn: A filename for the LD representation of an IFC model + :return: + """ + + def dict_to_list(headers): + return lambda di: [di[h] for h in headers] + + def execute(query, *args): + sparqlfn = ".".join(itertools.chain([fn], map(str, args))) + ".sparql" + with open(sparqlfn, "w") as f: + print(query, file=f) + + proc = subprocess.Popen( + [JENA_SPARQL, "--data=" + ttlfn, "--query=" + sparqlfn, "--results=CSV"], + stdout=subprocess.PIPE, + stderr=subprocess.PIPE) + stdout, stderr = proc.communicate() + + csvf = io.StringIO(stdout.decode('utf-8')) + + return list(csv.DictReader(csvf)) + + root_query = convertor.root(CR.entity) + roots = execute(root_query, 0) + + print("\nFile contains %d elements of type %s" % (len(roots), CR.entity)) + + passing_all = {} + + # for summary below + num_columns = 0 + + try: + # Full MVD with multiple concepts + is_template = False + concept_enumerator = list(itertools.chain([CR.applicability()], CR.concepts())) + except: + is_template = True + concept_enumerator = [CR] + + for ci, C in enumerate(concept_enumerator): + + num_columns += 1 + + if is_template or ci > 1: + print("\n%s" % C.name) + else: + print("\nApplicability") + + query = convertor.convert(C) + + print("\nSPARQL query") + print("============") + print(query) + + passing = execute(query, ci, 1) + passing_guids = set(r['GlobalId'] for r in passing) + + print("\nElements passing") + print(tabulate.tabulate(list(map(dict_to_list(query.args), passing)), query.args, tablefmt="grid")) + + print("\nElements failing concept") + hd = ["URI", "GlobalId"] + print(tabulate.tabulate( + list(map(dict_to_list(hd), [r for r in roots if r["GlobalId"] not in passing_guids])), hd, + tablefmt="grid")) + + passing_all[ci] = passing_guids + + print("\nSummary") + + for ci, C in enumerate(concept_enumerator): + print("(%d) %s" % (ci+(0 if is_template else 0), C.name)) + + def get_stats(guid): + v = lambda i: guid in passing_all[i] + st = [guid] + ["x" if v(i) else "" for i in range(num_columns)] + if not is_template: + st += ["x" if not v(0) or all(v(i) for i in range(1, num_columns)) else " "] + return st + + hd = ["GlobalId"] + list(map(str, range(num_columns))) + if not is_template: + hd += ["Valid"] + + print(tabulate.tabulate(list(map(get_stats, map(operator.itemgetter("GlobalId"), roots))), hd, tablefmt="grid")) \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/README.md b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/README.md new file mode 100644 index 0000000000000000000000000000000000000000..601772d100d32288a40525dc2abccce7492d92d4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/README.md @@ -0,0 +1,37 @@ +# Step Physical File Validator + +Pure-python Step Physical File Validator and Parser implemented using Lark (`pip install -r requirements.in`). + +## Example command line usage: + +~~~ +$ python main.py fixtures\fail_double_comma.ifc +On line 8 column 21: +Unexpected comma (',') +Expecting one of DBLQUOTE DOT HASH INT LPAR NONE QUOTE REAL STAR UPPER +00008 | #1=IFCPERSON($,$,'',,$,$,$,$); + ^ + +$ python main.py fixtures\fail_double_semi.ifc +On line 27 column 66: +Unexpected semicolon (';') +Expecting one of ENDSEC HASH +00027 | #20=IFCPROJECT('2AyG2X0sb16Bjd4gQc07yZ',#5,'',$,$,$,$,(#11),#19);; + ^ + +$ python main.py fixtures\fail_duplicate_id.ifc +On line 27: +Duplicate instance name #19 +00027 | #19=IFCPROJECT('2AyG2X0sb16Bjd4gQc07yZ',#5,'',$,$,$,$,(#11),#19); + ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +$ python main.py fixtures\fail_no_header.ifc +On line 2 column 1: +Unexpected hex ('F') +Expecting HEADER +00002 | FILE_DESCRIPTION(('ViewDefinition [CoordinationView]'),'2;1'); + ^ + +$ python main.py fixtures\pass_1.ifc +Valid +~~~ diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b79fbe1da063f46e62e35913e48740b94d820d30 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__init__.py @@ -0,0 +1,11 @@ +try: + from parser.parse import parse + from parser.file import file, open + from parser.errors import _ValidationError, CollectedValidationErrors, DuplicateNameError, HeaderFieldError +except: + from .parser.parse import parse + from .parser.file import file, open + from .parser.errors import _ValidationError, CollectedValidationErrors, DuplicateNameError, HeaderFieldError + +__all__ = ["parse", "open", "file", "_ValidationError", + "CollectedValidationErrors", "DuplicateNameError", "HeaderFieldError"] # for testing \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__main__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..537d02222b7a20833945ee7fdced0ad5a245b7e0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/__main__.py @@ -0,0 +1,33 @@ +import sys +import json +import argparse +from . import parse, CollectedValidationErrors + +def main(): + parser = argparse.ArgumentParser(description="Parse and validate STEP file.") + parser.add_argument("filename", help="The STEP file to validate.") + parser.add_argument("--progress", action="store_true", help="Show progress during validation.") + parser.add_argument("--json", action="store_true", help="Output errors in JSON format.") + parser.add_argument("--only-header", action="store_true", help="Validate only the header section.") + + args = parser.parse_args() + + try: + parse( + filename=args.filename, + with_progress = args.progress, + with_tree = False, + only_header=args.only_header, + ) + if not args.json: + print("Valid", file=sys.stderr) + exit(0) + except CollectedValidationErrors as exc: + if not args.json: + print(exc, file=sys.stderr) + else: + json.dump([e.asdict() for e in exc.errors], sys.stdout, indent=2) + exit(1) + +if __name__ == '__main__': + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/ifcgraph.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/ifcgraph.py new file mode 100644 index 0000000000000000000000000000000000000000..e912ff5508d7995c6c98602f19e2a797b8cd3c0d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/ifcgraph.py @@ -0,0 +1,92 @@ +import matplotlib.pyplot as plt +import networkx as nx +from itertools import count +import matplotlib.patches as mpatches +from matplotlib import pylab + + +class IfcEntity: + def __init__(self, data): + self.ifctype = data["ifc_type"] + self.id = data["id"] + + def __str__(self): + return "#" + str(self.id) + "_" + self.ifctype + + __repr__ = __str__ + + +def get_cmap(n, name="hsv"): + """Returns a function that maps each index in 0, 1, ..., n-1 to a distinct + RGB color; the keyword argument name must be a standard mpl colormap name.""" + return plt.cm.get_cmap(name, n) + + +G = nx.Graph() + +colors = [] +color_map = [] + +ifctypes = set() + +types_color = {} + +for e in ents.values(): + for r in e["attributes"][1]: + G.add_edge(e["id"], r) + color_map.append("red") + ifctypes.add(e["ifc_type"]) + ifctypes.add(ents[r]["ifc_type"]) + + +cmap = get_cmap(len(ifctypes), "rainbow") + +colors = [cmap(i) for i in range(len(ifctypes))] + +type_color_mapping = {} + +cols = [] + +i = 0 +for eid in G.nodes(): + t = ents[eid]["ifc_type"] + # print(t) + if t in type_color_mapping.keys(): + cols.append(type_color_mapping[t]) + else: + type_color_mapping[t] = colors[i] + i = i + 1 + cols.append(type_color_mapping[t]) + + +# k controls the distance between the nodes and varies between 0 and 1 +# iterations is the number of times simulated annealing is run +# default k=0.1 and iterations=50 +pos = nx.spring_layout(G, k=0.8, iterations=60) # positions for all nodes + +nodes = G.nodes() +print(get_cmap(len(nodes))) +cmap = get_cmap(len(nodes)) + +c_map = [cmap(i) for i in range(len(nodes))] + +nc = nx.draw_networkx_nodes(G, pos, nodelist=nodes, node_color=cols, node_size=200) + +# edges +elarge = [(u, v) for (u, v, d) in G.edges(data=True)] +nx.draw_networkx_edges(G, pos, edgelist=elarge, width=1) + +nx.draw_networkx_labels(G, pos, font_size=8, font_family="sans-serif") + + +red_patch = mpatches.Patch(color="red", label="The red data") +blue_patch = mpatches.Patch(color="blue", label="The blue data") + +patches = [] +for k, v in type_color_mapping.items(): + patches.append(mpatches.Patch(color=v, label=k)) + + +plt.legend(handles=patches, fontsize=8) +plt.axis("off") +plt.show() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/requirements.in b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/requirements.in new file mode 100644 index 0000000000000000000000000000000000000000..0aa1d5af4b369539e8fd4315519b24b7dedd5524 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/requirements.in @@ -0,0 +1 @@ +lark-parser diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/test_parser.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/test_parser.py new file mode 100644 index 0000000000000000000000000000000000000000..5e4ef56f9ba862b87640cf72fb7247d878f450bd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/simple_spf/test_parser.py @@ -0,0 +1,160 @@ +import glob +import pytest + +from __init__ import parse, open, _ValidationError, CollectedValidationErrors, DuplicateNameError, HeaderFieldError +from contextlib import nullcontext + + +def create_context(fn): + if "fail_" in fn: + return pytest.raises(_ValidationError) + else: + return nullcontext() + + +@pytest.mark.parametrize("file", glob.glob("fixtures/*.ifc")) +def test_file_with_tree(file): + with create_context(file): + parse(filename=file, with_tree=True) + + +@pytest.mark.parametrize("file", glob.glob("fixtures/*.ifc")) +def test_file_without_tree(file): + if any(sub in file for sub in ["fail_too_many_header_entity_fields.ifc", "fail_multiple_wrong_header_fields"]): + pytest.skip("This file relies on header field validation using the parsed AST, " + "but with_tree=False uses a NullTransformer that discards the AST, " + "so validating the header field names is not possible in this mode.") + with create_context(file): + parse(filename=file, with_tree=False) + + +def test_parse_features(): + f = open('fixtures/pass_1.ifc') + assert f.by_id(1).id == 1 + assert f.by_id(1).type == 'IFCPERSON' + assert f.data_[1][0].type == 'IFCPERSON' + assert f.by_type('ifcperson')[0].id == 1 + assert f[1][0] is None + assert f.header.file_description[0][0] == 'ViewDefinition [CoordinationView]' + assert f.header_.get('FILE_DESCRIPTION')[0][0] + assert f.by_type('ifcapplication')[1][2] == "Nested ' quotes" + + +def test_parse_valid_header(): + f = open('fixtures/passing_header.ifc') + + expected_description = { + "description": ('ViewDefinition [Alignment-basedView]',), + "implementation_level": '2;1', + } + + expected_name = { + "name": 'Header example2.ifc', + "time_stamp": '2022-09-16T10:35:07', + "author": ('Evandro Alfieri',), + "organization": ('buildingSMART Int.',), + "preprocessor_version": 'IFC Motor 1.0', + "originating_system": 'Company - Application - 26.0.0.0', + "authorization": 'none', + } + + expected_schema = { + "schema_identifiers": ('IFC4X3_ADD2',), + } + + for key, val in expected_description.items(): + assert getattr(f.header.file_description, key) == val, f"{key} mismatch" + + for key, val in expected_name.items(): + assert getattr(f.header.file_name, key) == val, f"{key} mismatch" + + for key, val in expected_schema.items(): + assert getattr(f.header.file_schema, key) == val, f"{key} mismatch" + + +def test_header_only_api(): + f = open('fixtures/passing_header.ifc', only_header=True) + expected_description = { + "description": ('ViewDefinition [Alignment-basedView]',), + "implementation_level": '2;1', + } + + expected_name = { + "name": 'Header example2.ifc', + "time_stamp": '2022-09-16T10:35:07', + "author": ('Evandro Alfieri',), + "organization": ('buildingSMART Int.',), + "preprocessor_version": 'IFC Motor 1.0', + "originating_system": 'Company - Application - 26.0.0.0', + "authorization": 'none', + } + + expected_schema = { + "schema_identifiers": ('IFC4X3_ADD2',), + } + + for key, val in expected_description.items(): + assert getattr(f.header.file_description, key) == val, f"{key} mismatch" + + for key, val in expected_name.items(): + assert getattr(f.header.file_name, key) == val, f"{key} mismatch" + + for key, val in expected_schema.items(): + assert getattr(f.header.file_schema, key) == val, f"{key} mismatch" + +def test_file_mvd_attr(): + f = open('fixtures/extended_mvd.ifc', only_header=True) + + assert 'ReferenceView_V1.2' in f.mvd.view_definitions + assert all(i in f.mvd.keywords for i in ['exchange_requirements', 'view_definitions', 'remark', 'comments']) + assert 'Ramp' in f.mvd.options['ExcludedObjects'] + assert f.mvd.Remark['SomeKey'] == 'SomeValue' + assert len(f.mvd.comments) == 2 + assert all(v in vars(f.header).keys() for v in ['file_description', 'file_name', 'file_schema']) + assert len(f.header.file_name) == 7 + + +@pytest.mark.parametrize("filename", [ + 'fixtures/fail_invalid_header_entity.ifc', + 'fixtures/fail_no_header.ifc', +]) +def test_invalid_headers_(filename): + # error in header + with pytest.raises(_ValidationError): + parse(filename=filename, with_tree=False, only_header=True) + +@pytest.mark.parametrize("filename", [ + 'fixtures/fail_duplicate_id.ifc', + 'fixtures/fail_double_comma.ifc', + 'fixtures/fail_double_semi.ifc' +]) +def test_valid_headers(filename): + # error in body + with nullcontext(): + parse(filename=filename, with_tree=False, only_header=True) + +def test_header_entity_fields(): + with pytest.raises(_ValidationError): + parse(filename='fixtures/fail_too_many_header_entity_fields.ifc', only_header=True) + +def test_header_entity_fields_whole_file(): + with pytest.raises(_ValidationError): + parse(filename='fixtures/fail_too_many_header_entity_fields.ifc') + +def test_header_entity_fields_whole_file(): + with pytest.raises(CollectedValidationErrors) as exc_info: + parse(filename="fixtures/fail_multiple_duplicate_ids.ifc") + + errors = exc_info.value.errors + + assert len(errors) == 2 + assert all(isinstance(e, DuplicateNameError) for e in errors) + +def test_multiple_wrong_header_fields(): + with pytest.raises(CollectedValidationErrors) as exc_info: + parse(filename="fixtures/fail_multiple_wrong_header_fields.ifc") + + errors = exc_info.value.errors + + assert len(errors) == 2 + assert all(isinstance(e, HeaderFieldError) for e in errors) \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/__init__.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..03fea1cd53d0af8624c28fc5df187834eeaab238 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/__init__.py @@ -0,0 +1,44 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +"""Utility functions for extracting IFC data + +Data in IFC files is represented using relationships between IFC entities. To +extract data like "what properties does this wall have" involves looping +through these relationships which can be tedious. + +This module makes it easy to get commonly requested data from IFC +relationships, such as properties of a wall, what elements are connected to +pipes, dates from work schedules, filtering maintainable elements, and more. + +The most commonly used utilities to help you get started are: + +- See :mod:`ifcopenshell.util.element` which contains a lot of useful functions + for getting most common relationships on elements. +- See :func:`ifcopenshell.util.element.get_psets` to get all properties of an + entity, like a wall. +- See :func:`ifcopenshell.util.element.get_type` to get the corresponding type + object (e.g. the wall type definition) of a single occurrence (e.g. an + individual wall). +- See :func:`ifcopenshell.util.placement.get_local_placement` to get the XYZ + placement point of a single object. +- See :func:`ifcopenshell.util.unit.calculate_unit_scale` to convert between SI + units and project units. +- See :mod:`ifcopenshell.util.shape` to calculate quantities from processed + geometry. +""" diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/alignment.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/alignment.py new file mode 100644 index 0000000000000000000000000000000000000000..ad6c6dd65d89448f36b7b07ff651e9c0a1dadf73 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/alignment.py @@ -0,0 +1,110 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Thomas Krijnen +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import math +import ifcopenshell +import ifcopenshell.util.unit + + +def add_linear_placement_fallback_position(file: ifcopenshell.file) -> ifcopenshell.file: + import ifcopenshell.api.alignment + + patched_file = ifcopenshell.file.from_string(file.wrapped_data.to_string()) + + linear_placements = patched_file.by_type("IfcLinearPlacement") + for lp in linear_placements: + ifcopenshell.api.alignment.update_fallback_position(patched_file, lp) + + return patched_file + + +def create_alignment_geometry(file: ifcopenshell.file) -> ifcopenshell.file: + import ifcopenshell.api.alignment + + patched_file = ifcopenshell.file.from_string(file.wrapped_data.to_string()) + + alignments = patched_file.by_type("IfcAlignment") + for alignment in alignments: + ifcopenshell.api.alignment.create_representation(patched_file, alignment) + + return patched_file + + +def append_zero_length_segments(file: ifcopenshell.file) -> ifcopenshell.file: + """Appends zero length segments to all alignment layouts and layout geometry, if missing.""" + import ifcopenshell.api.alignment + + patched_file = ifcopenshell.file.from_string(file.wrapped_data.to_string()) + + alignments = patched_file.by_type("IfcAlignment") + for alignment in alignments: + layouts = ifcopenshell.api.alignment.get_alignment_layouts(alignment) + for layout in layouts: + ifcopenshell.api.alignment.add_zero_length_segment(patched_file, layout, include_referent=False) + curve = ifcopenshell.api.alignment.get_layout_curve(layout) + if curve: + ifcopenshell.api.alignment.add_zero_length_segment(patched_file, curve) + + return patched_file + + +def station_as_string(file: ifcopenshell.file, sta: float): + """ + Returns a stringized version of a station. Example 100.0 is 1+00.00 as a stationing string. + If the project units are SI-based, the string is in the format xxx+yyy.zzz + If the project units are Emperial-based, the string is in the format xx+yy.zz + :param station: the station to be stringized + :return: stringized station + """ + + unit_type = ifcopenshell.util.unit.get_project_unit(file, "LENGTHUNIT") + if unit_type.is_a("IfcConversionBasedUnit"): + station = ifcopenshell.util.unit.convert( + sta, from_unit=unit_type.Name, from_prefix=None, to_unit="foot", to_prefix=None + ) + plus_seperator = 2 + precision = 2 + else: + station = ifcopenshell.util.unit.convert( + sta, from_unit=unit_type.Name, from_prefix=unit_type.Prefix, to_unit="meter", to_prefix=None + ) + plus_seperator = 3 + precision = 3 + + value = math.fabs(station) + + shifter = math.pow(10.0, plus_seperator) + v1 = math.floor(value / shifter) + v2 = value - v1 * shifter + + # Check to make sure that v2 is not basically the same as shifter + # If station = 69500.00000, we sometimes get 694+100.00 instead of 695+00.00 + if math.isclose(v2 - shifter, 0.0, abs_tol=5.0 * math.pow(10.0, -(precision + 1))): + v2 = 0.0 + v1 += 1 + + v1 = -1 * v1 if station < 0 else v1 + + station_string = "{:d}+{:0{}.{}f}".format(v1, v2, plus_seperator + precision + 1, precision) + + # special case when v1 is 0 and station is negative, the string above doesn't get the leading + # negative sign. this snippet fixes that + if v1 == 0 and station < 0: + station_string = "-" + station_string + + return station_string diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute.py new file mode 100644 index 0000000000000000000000000000000000000000..a3212aca672b630957024061eb5a14463c2b3ac0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute.py @@ -0,0 +1,80 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper +from typing import Union, Literal + +PrimitiveType = Literal["entity", "string", "float", "integer", "boolean", "enum", "binary"] +ComplexPrimitiveType = Literal["list", "array", "set"] +PrimitiveTypeOutput = Union[ + PrimitiveType, + tuple[ComplexPrimitiveType, "PrimitiveTypeOutput"], + tuple[Literal["select"], tuple["PrimitiveTypeOutput", ...]], + None, +] + + +def get_primitive_type( + attribute_or_data_type: Union[ifcopenshell_wrapper.attribute, ifcopenshell_wrapper.parameter_type], +) -> PrimitiveTypeOutput: + if isinstance(attribute_or_data_type, ifcopenshell_wrapper.attribute): + data_type = str(attribute_or_data_type.type_of_attribute()) + else: + data_type = str(attribute_or_data_type) + if data_type.find("" in data_type: + return "string" + elif "" in data_type: + return "float" + elif "" in data_type or "" in data_type: + return "integer" + elif "" in data_type: + return "boolean" + elif "" in data_type or " tuple[str, ...]: + named_type = attribute.type_of_attribute().as_named_type() + assert named_type + enumeration = named_type.declared_type().as_enumeration_type() + assert enumeration + return enumeration.enumeration_items() + + +def get_select_items(attribute: ifcopenshell_wrapper.attribute) -> tuple[ifcopenshell_wrapper.declaration, ...]: + named_type = attribute.type_of_attribute().as_named_type() + assert named_type + select_type = named_type.declared_type().as_select_type() + assert select_type + return select_type.select_list() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4_to_2x3.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4_to_2x3.json new file mode 100644 index 0000000000000000000000000000000000000000..6de45678688c5e673a5e02752ee4c30ee9af0675 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4_to_2x3.json @@ -0,0 +1,251 @@ +{ + "IfcPerformanceHistory": { + "Identification": "LifeCyclePhase" + }, + "IfcProcedure": { + "Identification": "ProcedureID", + "LongDescription": "ProcedureType", + "PredefinedType": "UserDefinedProcedureType" + }, + "IfcTask": { + "Identification": "TaskId", + "LongDescription": "Status", + "Status": "WorkMethod", + "WorkMethod": "IsMilestone", + "IsMilestone": "Priority" + }, + "IfcWorkPlan": { + "Identification": "Identifier", + "PredefinedType": "WorkControlType" + }, + "IfcWorkSchedule": { + "Identification": "Identifier", + "PredefinedType": "WorkControlType" + }, + "IfcSpace": { + "PredefinedType": "InteriorOrExteriorSpace" + }, + "IfcTransportElement": { + "PredefinedType": "OperationType" + }, + "IfcBuildingElementProxy": { + "PredefinedType": "CompositionType" + }, + "IfcRamp": { + "PredefinedType": "ShapeType" + }, + "IfcRelCoversSpaces": { + "RelatingSpace": "RelatedSpace" + }, + "IfcRoof": { + "PredefinedType": "ShapeType" + }, + "IfcStair": { + "PredefinedType": "ShapeType" + }, + "IfcAsset": { + "Identification": "AssetID" + }, + "IfcInventory": { + "PredefinedType": "InventoryType" + }, + "IfcActionRequest": { + "Identification": "RequestID" + }, + "IfcCostSchedule": { + "Identification": "SubmittedBy", + "PredefinedType": "PreparedBy", + "Status": "SubmittedOn", + "SubmittedOn": "Status", + "UpdateDate": "TargetUsers" + }, + "IfcPermit": { + "Identification": "PermitID" + }, + "IfcProjectOrder": { + "Identification": "ID" + }, + "IfcConstructionEquipmentResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity" + }, + "IfcConstructionMaterialResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity", + "BaseQuantity": "Suppliers", + "PredefinedType": "UsageRatio" + }, + "IfcConstructionProductResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity" + }, + "IfcCrewResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity" + }, + "IfcLaborResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity", + "BaseQuantity": "SkillSet" + }, + "IfcSubContractResource": { + "Identification": "ResourceIdentifier", + "LongDescription": "ResourceGroup", + "Usage": "ResourceConsumption", + "BaseCosts": "BaseQuantity", + "BaseQuantity": "SubContractor", + "PredefinedType": "JobDescription" + }, + "IfcStructuralLinearAction": { + "ProjectedOrTrue": "CausedBy", + "PredefinedType": "ProjectedOrTrue" + }, + "IfcStructuralPlanarAction": { + "ProjectedOrTrue": "CausedBy", + "PredefinedType": "ProjectedOrTrue" + }, + "IfcReinforcingBar": { + "PredefinedType": "BarRole" + }, + "IfcOrganization": { + "Identification": "Id" + }, + "IfcPerson": { + "Identification": "Id" + }, + "IfcApproval": { + "Identifier": "Description", + "Name": "ApprovalDateTime", + "Description": "ApprovalStatus", + "TimeOfApproval": "ApprovalLevel", + "Status": "ApprovalQualifier", + "Level": "Name", + "Qualifier": "Identifier" + }, + "IfcApprovalRelationship": { + "Name": "RelatedApproval", + "Description": "RelatingApproval", + "RelatingApproval": "Description", + "RelatedApprovals": "Name" + }, + "IfcObjective": { + "LogicalAggregator": "ResultValues" + }, + "IfcCostValue": { + "Category": "CostType" + }, + "IfcCurrencyRelationship": { + "Name": "RelatingMonetaryUnit", + "Description": "RelatedMonetaryUnit", + "RelatingMonetaryUnit": "ExchangeRate", + "RelatedMonetaryUnit": "RateDateTime", + "ExchangeRate": "RateSource" + }, + "IfcClassificationReference": { + "Identification": "ItemReference" + }, + "IfcDocumentInformation": { + "Identification": "DocumentId", + "Location": "DocumentReferences" + }, + "IfcDocumentInformationRelationship": { + "Name": "RelatingDocument", + "Description": "RelatedDocuments", + "RelatingDocument": "RelationshipType" + }, + "IfcDocumentReference": { + "Identification": "ItemReference" + }, + "IfcLibraryInformation": { + "Location": "LibraryReference" + }, + "IfcLibraryReference": { + "Identification": "ItemReference" + }, + "IfcMaterialProperties": { + "Properties": "ExtendedProperties" + }, + "IfcBlobTexture": { + "Mode": "TextureType", + "Parameter": "RasterFormat", + "RasterFormat": "RasterCode" + }, + "IfcExternallyDefinedHatchStyle": { + "Identification": "ItemReference" + }, + "IfcExternallyDefinedSurfaceStyle": { + "Identification": "ItemReference" + }, + "IfcExternallyDefinedTextFont": { + "Identification": "ItemReference" + }, + "IfcImageTexture": { + "Mode": "TextureType", + "Parameter": "UrlReference" + }, + "IfcPixelTexture": { + "Mode": "TextureType", + "Parameter": "Width", + "Width": "Height", + "Height": "ColourComponents", + "ColourComponents": "Pixel" + }, + "IfcTextureCoordinateGenerator": { + "Maps": "Mode", + "Mode": "Parameter" + }, + "IfcTextureMap": { + "Maps": "TextureMaps" + }, + "IfcAsymmetricIShapeProfileDef": { + "BottomFlangeWidth": "OverallWidth", + "BottomFlangeThickness": "FlangeThickness", + "BottomFlangeFilletRadius": "FilletRadius", + "BottomFlangeEdgeRadius": "CentreOfGravityInY" + }, + "IfcProfileProperties": { + "Name": "ProfileName", + "Description": "ProfileDefinition" + }, + "IfcPropertyDependencyRelationship": { + "Name": "DependingProperty", + "Description": "DependantProperty", + "DependingProperty": "Name", + "DependantProperty": "Description" + }, + "IfcBoundaryEdgeCondition": { + "TranslationalStiffnessByLengthX": "LinearStiffnessByLengthX", + "TranslationalStiffnessByLengthY": "LinearStiffnessByLengthY", + "TranslationalStiffnessByLengthZ": "LinearStiffnessByLengthZ" + }, + "IfcBoundaryFaceCondition": { + "TranslationalStiffnessByAreaX": "LinearStiffnessByAreaX", + "TranslationalStiffnessByAreaY": "LinearStiffnessByAreaY", + "TranslationalStiffnessByAreaZ": "LinearStiffnessByAreaZ" + }, + "IfcBoundaryNodeCondition": { + "TranslationalStiffnessX": "LinearStiffnessX", + "TranslationalStiffnessY": "LinearStiffnessY", + "TranslationalStiffnessZ": "LinearStiffnessZ" + }, + "IfcBoundaryNodeConditionWarping": { + "TranslationalStiffnessX": "LinearStiffnessX", + "TranslationalStiffnessY": "LinearStiffnessY", + "TranslationalStiffnessZ": "LinearStiffnessZ" + }, + "IfcStructuralLoadTemperature": { + "DeltaTConstant": "DeltaT_Constant", + "DeltaTY": "DeltaT_Y", + "DeltaTZ": "DeltaT_Z" + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4x3_to_4.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4x3_to_4.json new file mode 100644 index 0000000000000000000000000000000000000000..9c6bfea5082c18f8a3d0c8407df032b9de1a7271 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/attribute_4x3_to_4.json @@ -0,0 +1,30 @@ +{ + "IfcClassification": { + "Specification": "Location" + }, + "IfcPropertyBoundedValue": { + "Specification": "Description" + }, + "IfcPropertyEnumeratedValue": { + "Specification": "Description" + }, + "IfcPropertyListValue": { + "Specification": "Description" + }, + "IfcPropertyReferenceValue": { + "Specification": "Description" + }, + "IfcPropertyTableValue": { + "Specification": "Description" + }, + "IfcPropertySingleValue": { + "Specification": "Description" + }, + "IfcComplexProperty": { + "Specification": "Description" + }, + "IfcWorkTime": { + "StartDate": "Start", + "FinishDate": "Finish" + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/brick.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/brick.py new file mode 100644 index 0000000000000000000000000000000000000000..04e0be5452d714c7b38cd200169fbc1099e971ec --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/brick.py @@ -0,0 +1,105 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import os +import json +import ifcopenshell +import ifcopenshell.util.classification +import ifcopenshell.util.element +import ifcopenshell.util.system +from typing import Union + + +cwd = os.path.dirname(os.path.realpath(__file__)) + +ifc4_to_brick_map = {} + +with open(os.path.join(cwd, "ifc4_to_brick.json")) as f: + ifc4_to_brick_map = json.load(f) + + +def get_brick_type(element: ifcopenshell.entity_instance) -> Union[str, None]: + references = ifcopenshell.util.classification.get_references(element) + for reference in references: + system = ifcopenshell.util.classification.get_classification(reference) + if system.Name == "Brick": + return reference.Location + result = None + predefined_type = ifcopenshell.util.element.get_predefined_type(element) + if predefined_type: + result = ifc4_to_brick_map.get(f"{element.is_a()}.{predefined_type}", None) + if not result: + result = ifc4_to_brick_map.get(element.is_a(), None) + if not result: + element_type = ifcopenshell.util.element.get_type(element) + if element_type: + ifc_type_class = element_type.is_a().replace("Type", "") + result = ifc4_to_brick_map.get(f"{ifc_type_class}.{predefined_type}", None) + if not result: + result = ifc4_to_brick_map.get(ifc_type_class, None) + if result: + if result.startswith("http"): + return result + return f"https://brickschema.org/schema/Brick#{result}" + # Generic fallback + if element.is_a("IfcDistributionElement"): + return f"https://brickschema.org/schema/Brick#Equipment" + elif element.is_a("IfcSpatialElement") or element.is_a("IfcSpatialStructureElement"): + return f"https://brickschema.org/schema/Brick#Location" + elif element.is_a("IfcSystem"): + return f"https://brickschema.org/schema/Brick#System" + + +def get_element_feeds(element: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + current_element = element + processed_elements = set() + downstream_equipment: set[ifcopenshell.entity_instance] = set() + + # A queue is a list of branches. A branch is a list of elements in + # sequence, each one connecting to another element. An element in a + # branch may have a child queue. The queue and child queues are + # acyclic. + + def extend_branch(element, branch, predecessor=None): + processed_elements.add(element) + branch_element = {"element": element, "children": [], "predecessor": predecessor} + branch.append(branch_element) + + connected = { + e + for e in ifcopenshell.util.system.get_connected_to(element, flow_direction="SOURCE") + if e not in processed_elements + } + connected.update( + [ + e + for e in ifcopenshell.util.system.get_connected_from(element, flow_direction="SOURCE") + if e not in processed_elements + ] + ) + + for connected_element in connected: + if connected_element.is_a("IfcFlowFitting") or connected_element.is_a("IfcFlowSegment"): + branch_element["children"].append(extend_branch(connected_element, [], element)) + else: + downstream_equipment.add(connected_element) + + return branch + + extended_branch = extend_branch(current_element, []) + return downstream_equipment diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_2x3_to_4.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_2x3_to_4.json new file mode 100644 index 0000000000000000000000000000000000000000..3addf1516fc59fe89b5f5e1d865a38403bb03ea0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_2x3_to_4.json @@ -0,0 +1,9 @@ +{ + "IfcElectricDistributionPoint": "IfcElectricDistributionBoard" + , "IfcAnnotationCurveOccurrence": "IfcStyledItem" + , "IfcAnnotationFillAreaOccurrence": "IfcStyledItem" + , "IfcAnnotationSurfaceOccurrence": "IfcStyledItem" + , "IfcAnnotationSymbolOccurrence": "IfcStyledItem" + , "IfcAnnotationTextOccurrence": "IfcStyledItem" + , "IfcExtendedMaterialProperties": "IfcMaterialProperties" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_4_to_2x3.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_4_to_2x3.json new file mode 100644 index 0000000000000000000000000000000000000000..250a05b2577a3b8886d2f49240ee166b7bc7a1ce --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/class_4_to_2x3.json @@ -0,0 +1,213 @@ +{ + "IfcComplexPropertyTemplate": "", + "IfcProjectLibrary": "", + "IfcPropertySetTemplate": "", + "IfcRelAssignsToGroupByFactor": "", + "IfcRelDeclares": "", + "IfcRelDefinesByObject": "", + "IfcRelDefinesByTemplate": "", + "IfcSimplePropertyTemplate": "", + "IfcEvent": "", + "IfcEventType": "", + "IfcProcedureType": "", + "IfcTaskType": "", + "IfcWorkCalendar": "", + "IfcCivilElement": "", + "IfcCivilElementType": "", + "IfcElementAssemblyType": "", + "IfcExternalSpatialElement": "IfcSpace", + "IfcGeographicElement": "", + "IfcGeographicElementType": "", + "IfcOpeningStandardCase": "", + "IfcRelInterferesElements": "", + "IfcRelSpaceBoundary1stLevel": "", + "IfcRelSpaceBoundary2ndLevel": "", + "IfcSpatialZone": "", + "IfcSpatialZoneType": "", + "IfcBeamStandardCase": "", + "IfcBuildingSystem": "", + "IfcChimney": "", + "IfcChimneyType": "", + "IfcColumnStandardCase": "", + "IfcDoorStandardCase": "", + "IfcDoorType": "", + "IfcMemberStandardCase": "", + "IfcPlateStandardCase": "", + "IfcRampType": "", + "IfcRoofType": "", + "IfcShadingDevice": "", + "IfcShadingDeviceType": "", + "IfcSlabElementedCase": "", + "IfcSlabStandardCase": "", + "IfcStairType": "", + "IfcWallElementedCase": "", + "IfcWindowStandardCase": "", + "IfcWindowType": "", + "IfcDistributionCircuit": "", + "IfcDistributionSystem": "", + "IfcBuildingElementPartType": "", + "IfcFurniture": "", + "IfcSystemFurnitureElement": "", + "IfcActuator": "", + "IfcAlarm": "", + "IfcController": "", + "IfcFlowInstrument": "", + "IfcSensor": "", + "IfcUnitaryControlElement": "", + "IfcUnitaryControlElementType": "", + "IfcConstructionEquipmentResourceType": "", + "IfcConstructionMaterialResourceType": "", + "IfcConstructionProductResourceType": "", + "IfcCrewResourceType": "", + "IfcLaborResourceType": "", + "IfcSubContractResourceType": "", + "IfcAudioVisualAppliance": "", + "IfcAudioVisualApplianceType": "", + "IfcCableCarrierFitting": "", + "IfcCableCarrierSegment": "", + "IfcCableFitting": "", + "IfcCableFittingType": "", + "IfcCableSegment": "", + "IfcCommunicationsAppliance": "", + "IfcCommunicationsApplianceType": "", + "IfcElectricAppliance": "", + "IfcElectricDistributionBoard": "", + "IfcElectricDistributionBoardType": "", + "IfcElectricFlowStorageDevice": "", + "IfcElectricGenerator": "", + "IfcElectricMotor": "", + "IfcElectricTimeControl": "", + "IfcJunctionBox": "", + "IfcLamp": "", + "IfcLightFixture": "", + "IfcMotorConnection": "", + "IfcOutlet": "", + "IfcProtectiveDevice": "", + "IfcProtectiveDeviceTrippingUnit": "", + "IfcProtectiveDeviceTrippingUnitType": "", + "IfcSolarDevice": "", + "IfcSolarDeviceType": "", + "IfcSwitchingDevice": "", + "IfcTransformer": "", + "IfcAirTerminal": "", + "IfcAirTerminalBox": "", + "IfcAirToAirHeatRecovery": "", + "IfcBoiler": "", + "IfcBurner": "", + "IfcBurnerType": "", + "IfcChiller": "", + "IfcCoil": "", + "IfcCompressor": "", + "IfcCondenser": "", + "IfcCooledBeam": "", + "IfcCoolingTower": "", + "IfcDamper": "", + "IfcDuctFitting": "", + "IfcDuctSegment": "", + "IfcDuctSilencer": "", + "IfcEngine": "", + "IfcEngineType": "", + "IfcEvaporativeCooler": "", + "IfcEvaporator": "", + "IfcFan": "", + "IfcFilter": "", + "IfcFlowMeter": "", + "IfcHeatExchanger": "", + "IfcHumidifier": "", + "IfcMedicalDevice": "", + "IfcMedicalDeviceType": "", + "IfcPipeFitting": "", + "IfcPipeSegment": "", + "IfcPump": "", + "IfcSpaceHeater": "", + "IfcTank": "", + "IfcTubeBundle": "", + "IfcUnitaryEquipment": "", + "IfcValve": "", + "IfcVibrationIsolator": "", + "IfcFireSuppressionTerminal": "", + "IfcInterceptor": "", + "IfcInterceptorType": "", + "IfcSanitaryTerminal": "", + "IfcStackTerminal": "", + "IfcWasteTerminal": "", + "IfcStructuralCurveAction": "", + "IfcStructuralCurveReaction": "", + "IfcStructuralLoadCase": "", + "IfcStructuralSurfaceAction": "", + "IfcStructuralSurfaceReaction": "", + "IfcFootingType": "", + "IfcPileType": "", + "IfcReinforcingBarType": "", + "IfcReinforcingMeshType": "", + "IfcSurfaceFeature": "", + "IfcTendonAnchorType": "", + "IfcTendonType": "", + "IfcVoidingFeature": "", + "IfcResourceApprovalRelationship": "", + "IfcAppliedValue": "", + "IfcReference": "", + "IfcResourceConstraintRelationship": "", + "IfcEventTime": "", + "IfcLagTime": "", + "IfcRecurrencePattern": "", + "IfcResourceTime": "", + "IfcTaskTime": "", + "IfcTaskTimeRecurring": "", + "IfcTimePeriod": "", + "IfcWorkTime": "", + "IfcExternalReferenceRelationship": "", + "IfcConnectionVolumeGeometry": "", + "IfcAdvancedBrep": "", + "IfcAdvancedBrepWithVoids": "", + "IfcCartesianPointList3D": "", + "IfcExtrudedAreaSolidTapered": "", + "IfcFixedReferenceSweptAreaSolid": "", + "IfcRevolvedAreaSolidTapered": "", + "IfcSweptDiskSolidPolygonal": "", + "IfcTriangulatedFaceSet": "", + "IfcBoundaryCurve": "", + "IfcBSplineCurveWithKnots": "", + "IfcBSplineSurfaceWithKnots": "", + "IfcCompositeCurveOnSurface": "", + "IfcCurveBoundedSurface": "", + "IfcCylindricalSurface": "", + "IfcOuterBoundaryCurve": "", + "IfcPcurve": "", + "IfcRationalBSplineCurveWithKnots": "", + "IfcRationalBSplineSurfaceWithKnots": "", + "IfcReparametrisedCompositeCurveSegment": "", + "IfcMaterialConstituent": "", + "IfcMaterialConstituentSet": "", + "IfcMaterialLayerWithOffsets": "", + "IfcMaterialProfile": "", + "IfcMaterialProfileSet": "", + "IfcMaterialProfileSetUsage": "", + "IfcMaterialProfileSetUsageTapering": "", + "IfcMaterialProfileWithOffsets": "", + "IfcMaterialRelationship": "", + "IfcConversionBasedUnitWithOffset": "", + "IfcVector": "", + "IfcColourRgbList": "", + "IfcIndexedColourMap": "", + "IfcIndexedTriangleTextureMap": "", + "IfcTextureVertexList": "", + "IfcMirroredProfileDef": "", + "IfcTable": "", + "IfcMapConversion": "", + "IfcProjectedCRS": "", + "IfcStructuralLoadConfiguration": "", + "IfcSurfaceReinforcementArea": "", + "IfcAdvancedFace": "", + "IfcTableColumn": "", + "IfcCartesianPointList2D": "", + "IfcIndexedPolyCurve": "", + "IfcIndexedPolygonalFace": "", + "IfcIndexedPolygonalFaceWithVoids": "", + "IfcPolygonalFaceSet": "", + "IfcIntersectionCurve": "", + "IfcSeamCurve": "", + "IfcSphericalSurface": "", + "IfcSurfaceCurve": "", + "IfcToroidalSurface": "" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/classification.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/classification.py new file mode 100644 index 0000000000000000000000000000000000000000..06f9b0e31ae90dce37fad70385e49f6a8a704030 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/classification.py @@ -0,0 +1,98 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.element +from typing import Optional + + +def get_references(element: ifcopenshell.entity_instance, should_inherit=True) -> set[ifcopenshell.entity_instance]: + """Gets classification references associated with the element + + :param should_inherit: If true, classification references are inherited + from the type. Classifications can be overriden per system. + :return: A set of IfcClassificationReference + """ + results = set() + if not element.is_a("IfcRoot"): + if (references := getattr(element, "HasExternalReferences", None)) is not None or ( + references := getattr(element, "HasExternalReference", None) + ) is not None: + return {r.RelatingReference for r in references} + if should_inherit and element.is_a("IfcObject"): + element_type = ifcopenshell.util.element.get_type(element) + if element_type and element_type != element: + results = get_references(element_type) + occurrence_results = { + r.RelatingClassification + for r in getattr(element, "HasAssociations", []) + if r.is_a("IfcRelAssociatesClassification") + } + if results: + type_references_per_system = {} + occurrence_references_per_system = {} + for result in results: + type_references_per_system.setdefault(get_classification(result), []).append(result) + for result in occurrence_results: + occurrence_references_per_system.setdefault(get_classification(result), []).append(result) + type_references_per_system.update(occurrence_references_per_system) + results = set() + for values in type_references_per_system.values(): + [results.add(v) for v in values] + return results + return occurrence_results + + +def get_classification(reference: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Get the IfcClassification that a classification reference belongs to + + :param reference: An IfcClassificationReference + :return: IfcClassification + """ + if reference.is_a("IfcClassification"): + return reference + return get_classification(reference.ReferencedSource) if reference.ReferencedSource is not None else None + + +def get_inherited_references(reference: Optional[ifcopenshell.entity_instance]) -> list[ifcopenshell.entity_instance]: + results = [] + while True: + if not reference or reference.is_a("IfcClassification"): + break + results.append(reference) + reference = reference.ReferencedSource + return results + + +def get_classification_data(file: ifcopenshell.file) -> Optional[tuple[list[dict], str]]: + if not file or not file.by_type("IfcClassification"): + return [], "" + classification = file.by_type("IfcClassification")[0] + classification_name = classification.Name + + def process_references(reference): + data = reference.get_info() + del data["ReferencedSource"] + data["referenced_source"] = reference.ReferencedSource.id() if reference.ReferencedSource else None + data["has_references"] = bool(reference.HasReferences) + data["references"] = ( + [process_references(ref) for ref in reference.HasReferences] if reference.HasReferences else [] + ) + return data + + classification_data = [process_references(reference) for reference in classification.HasReferences] + return classification_data, classification_name diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/constraint.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/constraint.py new file mode 100644 index 0000000000000000000000000000000000000000..2c370aa997db21077007662fd5c765304bba6bf4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/constraint.py @@ -0,0 +1,110 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult, Yassine Oualid +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . +# +# + +import ifcopenshell +from typing import Union + + +def get_constraints(product: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the constraints assigned to the `product`. + + :param product: The IFC element. + :return: List of assigned constraints. + """ + constraints = [] + for rel in product.HasAssociations or []: + if rel.is_a("IfcRelAssociatesConstraint"): + constraints.append(rel.RelatingConstraint) + return constraints + + +def get_constrained_elements(constraint: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + """ + Retrieves the elements constrained by a `constraint`. + + :param product: The IFC element. + :return: Set of elements constrained by a `constrant`. + """ + elements = set() + for rel in constraint.file.get_inverse(constraint): + if rel.is_a("IfcRelAssociatesConstraint"): + elements.update(rel.RelatedObjects) + return elements + + +def get_metrics(constraint: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the list of nested constraints for a IfcObjective `constraint`. + + :param product: IfcObjective constraint. + :return: List of nested constraints. + """ + + metrics = [] + for metric in constraint.BenchmarkValues or []: + metrics.append(metric) + return metrics + + +def get_metric_reference(metric: ifcopenshell.entity_instance, is_deep=True): + def get_reference_Attribute(ref, path): + if ref: + if is_deep: + if not path: + path = ref.AttributeIdentifier + else: + path += ".{}".format(ref.AttributeIdentifier) if ref.AttributeIdentifier else "" + return get_reference_Attribute(ref.InnerReference, path) + else: + return ref.AttributeIdentifier + return path + + reference = metric.ReferencePath + return get_reference_Attribute(reference, "") + + +def get_metric_constraints( + resource: ifcopenshell.entity_instance, attribute +) -> Union[list[ifcopenshell.entity_instance], None]: + metrics = [] + for constraint in get_constraints(resource) or []: + for metric in get_metrics(constraint) or []: + if bool( + get_metric_reference(metric, is_deep=False) == attribute + or get_metric_reference(metric, is_deep=True) == attribute + ): + metrics.append(metric) + if metrics: + return metrics + return None + + +def is_hard_constraint(metric: ifcopenshell.entity_instance) -> bool: + return metric.ConstraintGrade == "HARD" and metric.Benchmark == "EQUALTO" + + +def is_attribute_locked(product: ifcopenshell.entity_instance, attribute) -> bool: + is_locked = False + metrics = get_metric_constraints(product, attribute) + for metric in metrics or []: + if is_hard_constraint(metric): + is_locked = True + return is_locked diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/cost.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/cost.py new file mode 100644 index 0000000000000000000000000000000000000000..a7e96221d998d1ed580a3a8adbaeebf0e7ada0ba --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/cost.py @@ -0,0 +1,436 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import lark +import ifcopenshell +from typing import Optional, Union, Literal, Any +from collections.abc import Generator +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper +import ifcopenshell.util.attribute +import ifcopenshell.util.element +from ifcopenshell.util.doc import get_predefined_type_doc +from ifcopenshell.util.element import get_psets +from ifcopenshell.util.unit import get_unit_symbol + +arithmetic_operator_symbols = {"ADD": "+", "DIVIDE": "/", "MULTIPLY": "*", "SUBTRACT": "-"} +symbol_arithmetic_operators = {"+": "ADD", "/": "DIVIDE", "*": "MULTIPLY", "-": "SUBTRACT"} +FILTER_BY_TYPE = Literal["PRODUCT", "RESOURCE", "PROCESS"] + + +def get_primitive_applied_value(applied_value: Union[ifcopenshell.entity_instance, float, None]) -> float: + if not applied_value: + return 0.0 + elif isinstance(applied_value, float): + return applied_value + elif hasattr(applied_value, "wrappedValue") and isinstance(applied_value.wrappedValue, float): + return applied_value.wrappedValue + elif applied_value.is_a("IfcMeasureWithUnit"): + return applied_value.ValueComponent + assert False, f"Applied value {applied_value} not implemented" + + +def get_total_quantity(root_element: ifcopenshell.entity_instance) -> Union[float, None]: + # 3 IfcPhysicalQuantity Value + if root_element.is_a("IfcCostItem"): + # Different output for no quantities and zero quantites + # as they have different meaning in IFC. + quantities = root_element.CostQuantities + if not quantities: + return None + return sum([q[3] for q in quantities]) + elif root_element.is_a("IfcConstructionResource"): + quantity = root_element.BaseQuantity + return quantity[3] if quantity else 1.0 + + +def calculate_applied_value( + root_element: ifcopenshell.entity_instance, + cost_value: ifcopenshell.entity_instance, + category_filter: Optional[str] = None, +) -> float: + if cost_value.ArithmeticOperator and cost_value.Components: + component_values = [] + for component in cost_value.Components: + component_values.append(calculate_applied_value(root_element, component, category_filter)) + if cost_value.ArithmeticOperator == "ADD": + return sum(component_values) + result = component_values.pop(0) + if cost_value.ArithmeticOperator == "DIVIDE": + for value in component_values: + try: + result /= value + except ZeroDivisionError: + pass + elif cost_value.ArithmeticOperator == "MULTIPLY": + for value in component_values: + result *= value + elif cost_value.ArithmeticOperator == "SUBTRACT": + for value in component_values: + result -= value + return result + if cost_value.Category is None: + return get_primitive_applied_value(cost_value.AppliedValue) + elif cost_value.Category == "*": + if root_element.IsNestedBy: + return sum_child_root_elements(root_element) + else: + return get_primitive_applied_value(cost_value.AppliedValue) + elif cost_value.Category: + if root_element.IsNestedBy: + return sum_child_root_elements(root_element, category_filter=cost_value.Category) + else: + return get_primitive_applied_value(cost_value.AppliedValue) + return 0.0 + + +def sum_child_root_elements(root_element: ifcopenshell.entity_instance, category_filter: Optional[str] = None) -> float: + result = 0.0 + for rel in root_element.IsNestedBy: + for child_root_element in rel.RelatedObjects: + if get_assigned_rate_cost_item(child_root_element): + new_child_root_element = get_assigned_rate_cost_item(child_root_element) + else: + new_child_root_element = child_root_element + if root_element.is_a("IfcCostItem"): + values = new_child_root_element.CostValues + elif root_element.is_a("IfcConstructionResource"): + values = child_root_element.BaseCosts + for child_cost_value in values or []: + if category_filter and child_cost_value.Category != category_filter: + continue + child_applied_value = calculate_applied_value(new_child_root_element, child_cost_value) + child_quantity = get_total_quantity(child_root_element) + child_quantity = 1.0 if child_quantity is None else child_quantity + if child_cost_value.UnitBasis: + value_component = child_cost_value.UnitBasis.ValueComponent.wrappedValue + result += child_quantity / value_component * child_applied_value + else: + result += child_quantity * child_applied_value + return result + + +def serialise_cost_value(cost_value: ifcopenshell.entity_instance) -> str: + result = _serialise_cost_value(cost_value) + if result and result[0] == "(" and result[-1] == ")": + return result[1:-1] + return result + + +def get_assigned_rate_cost_item(cost_item: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + # same as in tool. Maybe just create one? + for assignment in cost_item.HasAssignments: + if assignment.RelatingControl.is_a() == "IfcCostItem": + return assignment.RelatingControl + + +def _serialise_cost_value(cost_value: ifcopenshell.entity_instance) -> str: + value = "" + if cost_value.ArithmeticOperator and cost_value.Components: + operator = arithmetic_operator_symbols[cost_value.ArithmeticOperator] + serialised_components = [] + for component in cost_value.Components: + serialised_components.append(_serialise_cost_value(component)) + value = operator.join(serialised_components) + elif cost_value.AppliedValue is not None: + value = serialise_applied_value(cost_value.AppliedValue) + + category = "" + if cost_value.Category == "*": + category = "SUM" + elif cost_value.Category: + category = cost_value.Category + + if not category and not value: + value = "0" + + if category: + return f"{category}({value})" + elif cost_value.Components: + return f"({value})" + return value + + +def serialise_applied_value(applied_value: ifcopenshell.entity_instance) -> str: + if applied_value.is_a("IfcMonetaryMeasure"): + return str(applied_value.wrappedValue) + return "?" + + +def unserialise_cost_value(formula: str, cost_value: ifcopenshell.entity_instance) -> dict[str, Any]: + unserialiser = CostValueUnserialiser() + result = unserialiser.parse(formula) + + def map_element_to_result(element: ifcopenshell.entity_instance, result: dict): + result["ifc"] = element + for i, component in enumerate(result.get("Components", [])): + if element.Components and i < len(element.Components): + map_element_to_result(element.Components[i], result["Components"][i]) + + map_element_to_result(cost_value, result) + return result + + +def get_cost_items_for_product(product: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Returns a list of cost items related to the given product. + + :param product: An object of class IfcProduct representing a product. + + :return: A list of IfcCostItem objects representing the cost items related to the product. + """ + cost_items = [] + for assignment in product.HasAssignments: + if assignment.is_a("IfcRelAssignsToControl") and assignment.RelatingControl.is_a("IfcCostItem"): + cost_items.append(assignment.RelatingControl) + return cost_items + + +def get_root_cost_items(cost_schedule: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + return [ + related_object + for rel in cost_schedule.Controls or [] + for related_object in rel.RelatedObjects + if related_object.is_a("IfcCostItem") + ] + + +def get_all_nested_cost_items( + cost_item: ifcopenshell.entity_instance, +) -> Generator[ifcopenshell.entity_instance]: + for cost_item in get_nested_cost_items(cost_item): + yield cost_item + yield from get_all_nested_cost_items(cost_item) + + +def get_nested_cost_items(cost_item: ifcopenshell.entity_instance, is_deep=False) -> list[ifcopenshell.entity_instance]: + if is_deep: + return list(get_all_nested_cost_items(cost_item)) + else: + return ifcopenshell.util.element.get_components(cost_item) + + +def get_schedule_cost_items( + cost_schedule: ifcopenshell.entity_instance, +) -> Generator[ifcopenshell.entity_instance]: + """Get all cost schedule cost items, including the nested ones.""" + for cost_item in get_root_cost_items(cost_schedule): + yield cost_item + yield from get_all_nested_cost_items(cost_item) + + +def get_cost_assignments_by_type( + cost_item: ifcopenshell.entity_instance, filter_by_type: Optional[FILTER_BY_TYPE] = None +) -> list[ifcopenshell.entity_instance]: + if filter_by_type is not None: + if filter_by_type == "PRODUCT": + filter_by_type = "IfcElement" + elif filter_by_type == "RESOURCE": + filter_by_type = "IfcResource" + elif filter_by_type == "PROCESS": + filter_by_type = "IfcProcess" + return [ + related_object + for r in cost_item.Controls or [] + for related_object in r.RelatedObjects + if not filter_by_type or related_object.is_a(filter_by_type) + ] + + +def get_cost_item_assignments( + cost_item: ifcopenshell.entity_instance, filter_by_type: Optional[FILTER_BY_TYPE] = None, is_deep: bool = False +) -> list[ifcopenshell.entity_instance]: + if not is_deep: + return get_cost_assignments_by_type(cost_item, filter_by_type) + else: + current_assignments = get_cost_assignments_by_type(cost_item, filter_by_type) + nested_assignments = [ + product + for nested_cost_item in get_all_nested_cost_items(cost_item) + for product in get_cost_assignments_by_type(nested_cost_item, filter_by_type) + ] + return current_assignments + nested_assignments + + +def get_cost_values(cost_item: ifcopenshell.entity_instance) -> list[dict[str, str]]: + results = [] + for cost_value in cost_item.CostValues or []: + label = "{0:.2f}".format(calculate_applied_value(cost_item, cost_value)) + label += " = {}".format(serialise_cost_value(cost_value)) + unit_data = {"value_component": None, "unit_component": None, "unit_symbol": ""} + if cost_value.UnitBasis: + data = cost_value.UnitBasis.get_info() + unit_data["value_component"] = data["ValueComponent"].wrappedValue + unit_data["unit_component"] = data["UnitComponent"].id() + unit_data["unit_symbol"] = get_unit_symbol(cost_value.UnitBasis.UnitComponent) + + results.append( + { + "id": cost_value.id(), + "label": label, + "name": cost_value.Name, + "category": cost_value.Category, + "applied_value": ( + get_primitive_applied_value(cost_value.AppliedValue) if cost_value.AppliedValue else None + ), + "unit_data": unit_data, + } + ) + return results + + +def get_cost_schedule_types(file: ifcopenshell.file) -> list[dict[str, str]]: + schema = ifcopenshell_wrapper.schema_by_name(file.schema_identifier) + results: list[dict[str, str]] = [] + declaration = schema.declaration_by_name("IfcCostSchedule").as_entity() + assert declaration + version = file.schema_identifier + for attribute in declaration.attributes(): + if attribute.name() == "PredefinedType": + for enumeration in ifcopenshell.util.attribute.get_enum_items(attribute): + results.append( + { + "name": enumeration, + "description": get_predefined_type_doc(version, "IfcCostSchedule", enumeration), + } + ) + break + return results + + +def get_product_quantity_names(elements: list[ifcopenshell.entity_instance]) -> list[str]: + names = set() + for element in elements or []: + potential_names = set() + qtos = get_psets(element, qtos_only=True) + for qset, quantities in qtos.items(): + potential_names.update(quantities.keys()) + names = names.intersection(potential_names) if names else potential_names + return [n for n in names if n != "id"] + + +def get_cost_schedule(cost_item: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Returns the cost schedule of a cost item.""" + for rel in cost_item.HasAssignments or []: + if rel.is_a("IfcRelAssignsToControl") and rel.RelatingControl.is_a("IfcCostSchedule"): + return rel.RelatingControl + for rel in cost_item.Nests or []: + return get_cost_schedule(rel.RelatingObject) + + +def get_cost_rate( + file: ifcopenshell_wrapper.file, cost_item: ifcopenshell.entity_instance +) -> Optional[ifcopenshell.entity_instance]: + """Returns the cost rate of a cost item.""" + # There is no direct relationship between a cost item and a cost rate in IFC, so we need to infer it, based on the assumption that cost_rate.CostValues == cost_item.CostValues. + if get_cost_schedule(cost_item).PredefinedType == "SCHEDULEOFRATES": + return None # Cost item is already a cost rate + if cost_item.CostValues: + potential_rates = file.get_inverse(cost_item.CostValues[0]) + for potential_rate in potential_rates: + schedule = get_cost_schedule(potential_rate) + if schedule.PredefinedType == "SCHEDULEOFRATES": + return potential_rate + return None + + +class CostValueUnserialiser: + def parse(self, formula: str): + l = lark.Lark( + """start: formula + formula: operand (operator operand)* + operand: value | category "(" formula ")" + value: NUMBER? + category: WORD? + operator: add | divide | multiply | subtract + add: "+" + divide: "/" + multiply: "*" + subtract: "-" + + // Embed common.lark for packaging + DIGIT: "0".."9" + HEXDIGIT: "a".."f"|"A".."F"|DIGIT + INT: DIGIT+ + SIGNED_INT: ["+"|"-"] INT + DECIMAL: INT "." INT? | "." INT + _EXP: ("e"|"E") SIGNED_INT + FLOAT: INT _EXP | DECIMAL _EXP? + SIGNED_FLOAT: ["+"|"-"] FLOAT + NUMBER: FLOAT | INT + SIGNED_NUMBER: ["+"|"-"] NUMBER + _STRING_INNER: /.*?/ + _STRING_ESC_INNER: _STRING_INNER /(?, @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import numpy as np +import ifcopenshell +from typing import Any, Union +from dataclasses import dataclass +from ifcopenshell.util.shape_builder import ShapeBuilder + + +@dataclass +class Clipping: + location: tuple[float, float, float] + normal: tuple[float, float, float] + type: str = "IfcBooleanClippingResult" + operand_type: str = "IfcHalfSpaceSolid" + + @classmethod + def parse( + cls, raw_data: Union[ifcopenshell.entity_instance, Clipping, dict[str, Any]] + ) -> Union[ifcopenshell.entity_instance, Clipping]: + """Parse various formats into a clipping object + + `raw_data` can be either: + + - IfcBooleanResult IFC entity + - `Clipping` instance + - dictionary to define `Clipping` - either `location` and `normal` + or a `matrix` where XY plane is the clipping boundary and +Z is removed. + `matrix` method will be soon to be deprecated completely. + """ + if isinstance(raw_data, ifcopenshell.entity_instance): + if not raw_data.is_a("IfcBooleanResult"): + raise Exception(f"Provided clipping of unexpected IFC class: {raw_data}") + return raw_data + elif isinstance(raw_data, Clipping): + return raw_data + elif isinstance(raw_data, dict): + if "matrix" in raw_data: + raw_data = raw_data.copy() + matrix = np.array(raw_data["matrix"])[:3] + raw_data["normal"] = matrix[:, 2].tolist() + raw_data["location"] = matrix[:, 3].tolist() + del raw_data["matrix"] + clipping_data = cls(**raw_data) + if clipping_data.type != "IfcBooleanClippingResult": + raise Exception(f'Provided clipping with unexpected result type "{clipping_data.type}"') + if clipping_data.operand_type != "IfcHalfSpaceSolid": + raise Exception(f'Provided clipping with unexpected operand type "{clipping_data.operand_type}"') + return clipping_data + raise Exception(f"Unexpected clipping type provided: {raw_data}") + + def apply( + self, ifc_file: Union[ifcopenshell.file, None], first_operand: ifcopenshell.entity_instance, unit_scale: float + ) -> ifcopenshell.entity_instance: + """Applies the clipping data as an IfcBooleanClippingResult to an operand + + :param ifc_file: The model to create the entities in + :param first_operand: The representation item to apply the boolean clipping to. + :param unit_scale: The unit scale value to convert from the Clipping's SI units to project units + :return: An IfcBooleanClippingResult which uses an IfcHalfSpaceSolid to clip the first operand + """ + + if not ifc_file: + ifc_file = first_operand.file + builder = ShapeBuilder(ifc_file) + + normal = np.array(self.normal) + if np.allclose(normal, np.array([0.0, 0.0, 1.0]), atol=1e-2) or np.allclose( + normal, np.array([0.0, 0.0, -1.0]), atol=1e-2 + ): + arbitrary_vector = np.array([0.0, 1.0, 0.0]) + else: + arbitrary_vector = np.array([0.0, 0.0, 1.0]) + + x_axis = np.cross(normal, arbitrary_vector) + x_axis /= np.linalg.norm(x_axis) + + placement = builder.create_axis2_placement_3d([i / unit_scale for i in self.location], self.normal, x_axis) + plane = ifc_file.create_entity("IfcPlane", placement) + + second_operand = ifc_file.createIfcHalfSpaceSolid(plane, False) + return ifc_file.createIfcBooleanClippingResult("DIFFERENCE", first_operand, second_operand) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/date.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/date.py new file mode 100644 index 0000000000000000000000000000000000000000..3b0761f75cd0646ae309b42e2ba4356938a5e6fa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/date.py @@ -0,0 +1,268 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import datetime +import isodate +from re import findall +from dateutil import parser +from typing import Literal, Union, Any, overload + + +def timedelta2duration(timedelta): + components = { + "days": getattr(timedelta, "days", 0), + "hours": 0, + "minutes": 0, + "seconds": getattr(timedelta, "seconds", 0), + } + if components["seconds"]: + components["hours"], components["minutes"], components["seconds"] = [ + int(i) for i in str(datetime.timedelta(seconds=components["seconds"])).split(":") + ] + return isodate.Duration(**components) + + +def ifc2datetime(element: Union[str, int, ifcopenshell.entity_instance]): + if isinstance(element, str): + if "P" in element[0:2]: # IfcDuration + duration = parse_duration(element) + if isinstance(duration, datetime.timedelta): + return timedelta2duration(duration) + return duration + elif len(element) > 3 and element[2] == ":": # IfcTime + return datetime.time.fromisoformat(element) + elif ":" in element: # IfcDateTime + return datetime.datetime.fromisoformat(element) + else: # IfcDate + return datetime.date.fromisoformat(element) + + elif isinstance(element, int): # IfcTimeStamp + return datetime.datetime.fromtimestamp(element) + + elif isinstance(element, ifcopenshell.entity_instance): + if element.is_a("IfcDateAndTime"): + return datetime.datetime( + element.DateComponent.YearComponent, + element.DateComponent.MonthComponent, + element.DateComponent.DayComponent, + element.TimeComponent.HourComponent, + element.TimeComponent.MinuteComponent, + int(element.TimeComponent.SecondComponent), + # TODO: implement TimeComponent timezone + ) + elif element.is_a("IfcCalendarDate"): + return datetime.date( + element.YearComponent, + element.MonthComponent, + element.DayComponent, + ) + + +def readable_ifc_duration(duration: str) -> str: + """Convert ISO duration to more readable string format. + + Examples: + - "P2Y3M1W4DT5H45M30S" -> "2 Y 3 M 1 W 4 D 5 h 45 m 30 s" + - "P2Y3MT30S" -> "2 Y 3 M 30 s" + - "PT2500H" -> "2500 h" (hours are not converted to days) + """ + # NOTE: we don't use isodate.parseduration as it's going to + # represent "PT2500H" as "12w 6d 4h", though user may want + # intentionally to use just hours. + + if "T" in duration: + period_duration, time_duration = duration.split("T") + period_duration = period_duration[1:] + else: + period_duration = duration[1:] + time_duration = "" + + result: list[str] = [] + for designator in ("Y", "M", "W", "D"): + if designator in period_duration: + value, period_duration = period_duration.split(designator) + if float(value): + result.append(f"{value}{designator}") + + if time_duration: + for designator in ("H", "M", "S"): + if designator in time_duration: + value, time_duration = time_duration.split(designator) + if float(value): + result.append(f"{value}{designator.lower()}") + return " ".join(result) + + +@overload +def datetime2ifc(dt: None, ifc_type: Any) -> None: ... +@overload +def datetime2ifc( + dt: Union[datetime.date, str, None], + ifc_type: Literal[ + "IfcDuration", + "IfcTimeStamp", + "IfcDateTime", + "IfcDate", + "IfcTime", + "IfcCalendarDate", + "IfcLocalTime", + ], +) -> Union[int, str, dict[str, Any], None]: ... +def datetime2ifc( + dt: Union[datetime.date, str, None], + ifc_type: Literal[ + "IfcDuration", + "IfcTimeStamp", + "IfcDateTime", + "IfcDate", + "IfcTime", + "IfcCalendarDate", + "IfcLocalTime", + ], +) -> Union[int, str, dict[str, Any], None]: + if isinstance(dt, str): + if ifc_type == "IfcDuration": + return dt + try: + dt = datetime.datetime.fromisoformat(dt) + except: + dt = datetime.time.fromisoformat(dt) + elif dt is None: + return + + if ifc_type == "IfcDuration": + return isodate.duration_isoformat(dt) + elif ifc_type == "IfcTimeStamp": + return int(dt.timestamp()) + elif ifc_type == "IfcDateTime": + if isinstance(dt, datetime.datetime): + return dt.isoformat() + elif isinstance(dt, datetime.date): + return datetime.datetime.combine(dt, datetime.datetime.min.time()).isoformat() + elif ifc_type == "IfcDate": + if isinstance(dt, datetime.datetime): + return dt.date().isoformat() + elif isinstance(dt, datetime.date): + return dt.isoformat() + elif ifc_type == "IfcTime": + if isinstance(dt, datetime.datetime): + return dt.time().isoformat() + elif isinstance(dt, datetime.time): + return dt.isoformat() + elif ifc_type == "IfcCalendarDate": + return { + "DayComponent": dt.day, + "MonthComponent": dt.month, + "YearComponent": dt.year, + } + elif ifc_type == "IfcLocalTime": + # TODO implement timezones + return { + "HourComponent": dt.hour, + "MinuteComponent": dt.minute, + "SecondComponent": dt.second, + } + + raise TypeError(f"Unsupported ifc_type for conversion from datetime.datetime = {ifc_type}, value = {dt}") + + +def string_to_date(string): + if not string: + return None + try: + return parser.isoparse(string) + except: + try: + return parser.parse(string, dayfirst=True, fuzzy=True) + except: + return None + + +def string_to_duration(duration_string): + # TODO support years, months, weeks aswell + days = 0 + hours = 0 + minutes = 0 + seconds = 0 + match = findall(r"(\d+\.?\d*)d", duration_string) + if match: + days = float(match[0]) + match = findall(r"(\d+\.?\d*)h", duration_string) + if match: + hours = float(match[0]) + match = findall(r"(\d+\.?\d*)m", duration_string) + if match: + minutes = float(match[0]) + match = findall(r"(\d+\.?\d*)s", duration_string) + if match: + seconds = float(match[0]) + return isodate.duration_isoformat(datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)) + + +def parse_duration(value: Union[str, None]) -> Union[datetime.timedelta, None]: + if not value: + return None + if isinstance(value, str): + if "P" in value: + try: + return isodate.parse_duration(value) + except: + print("Error parsing ISO string duration") + return None + else: + try: + final_string = "P" + value_upper = value.upper() + for char in value_upper: + if char.isdigit(): + final_string += char + elif char == "D": + final_string += "D" + if "H" in value_upper or "S" in value_upper or "MIN" in value_upper: + final_string += "T" + elif char == "W": + final_string += "W" + elif char == "M": + final_string += "M" + elif char == "Y": + final_string += "Y" + elif char == "H": + final_string = ( + final_string[:1] + "T" + final_string[1:] if "T" not in final_string else final_string + ) + final_string += "H" + elif char == "M": + if "MIN" in value_upper and "T" not in final_string: + final_string = final_string[:1] + "T" + final_string[1:] + final_string += "M" + elif char == "S": + final_string = ( + final_string[:1] + "T" + final_string[1:] if "T" not in final_string else final_string + ) + final_string += "S" + return isodate.parse_duration(final_string) + except: + print("error fuzzy parsing duration") + return None + + +def canonicalise_time(time: Union[datetime.datetime, None]) -> str: + if not time: + return "-" + return time.strftime("%d/%m/%y") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/doc.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/doc.py new file mode 100644 index 0000000000000000000000000000000000000000..41d6189fe4e09d590a13a8b67b969bfadecd3a07 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/doc.py @@ -0,0 +1,1120 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022, 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import json +from pathlib import Path +import copy +import ifcopenshell +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper +import ifcopenshell.util.attribute +import ifcopenshell.util.schema +from typing import Optional, Literal, Any, Union, TypedDict +from typing_extensions import NotRequired + +try: + import glob + import warnings + import requests + import urllib.parse + from markdown import markdown + from bs4 import BeautifulSoup, MarkupResemblesLocatorWarning + import zipfile + from lxml import etree + import re + import shutil +except: + pass # Only necessary if you're using it to generate the docs database + + +BASE_MODULE_PATH = Path(__file__).parent +IFC2x3_DOCS_LOCATION = BASE_MODULE_PATH / "Ifc2.3.0.1" +IFC4_DOCS_LOCATION = BASE_MODULE_PATH / "Ifc4.0.2.1" + +IFC4x3_HTML_LOCATION = BASE_MODULE_PATH / "IFC4.3-html" +IFC4x3_DEV_LOCATION = BASE_MODULE_PATH / "IFC4.3.x-development" +IFC4x3_SPEC_URL_TEMPLATE = "https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/%s.htm" + + +class BaseData(TypedDict): + description: str + spec_url: str + + +class EntityData(BaseData): + attributes: NotRequired[dict[str, str]] + predefined_types: NotRequired[dict[str, str]] + + +class PsetData(TypedDict): + # Apparently some psets in ifc4 are missing spec url / description. + description: NotRequired[str] + spec_url: NotRequired[str] + properties: dict[str, str] + + +class PropertyData(TypedDict): + description: str + # in IFC4x3 there is no children[] for properties + children: NotRequired[dict[str, "PropertyData"]] + + +class ClassesSuggestions(TypedDict): + name: str + predefined_type: NotRequired[str] + + +class SchemaData(TypedDict): + entities: dict[str, EntityData] + types: dict[str, BaseData] + properties: dict[str, PsetData] + classes_suggestions: dict[str, ClassesSuggestions] + + +SUPPORTED_SCHEMA = ifcopenshell.util.schema.IFC_SCHEMA +SCHEMA_FILES: dict[SUPPORTED_SCHEMA, dict[str, Path]] = { + "IFC2X3": { + "entities": BASE_MODULE_PATH / "schema/ifc2x3_entities.json", + "properties": BASE_MODULE_PATH / "schema/ifc2x3_properties.json", + "types": BASE_MODULE_PATH / "schema/ifc2x3_types.json", + "classes_suggestions": BASE_MODULE_PATH / "schema/ifc_classes_suggestions.json", + }, + "IFC4": { + "entities": BASE_MODULE_PATH / "schema/ifc4_entities.json", + "properties": BASE_MODULE_PATH / "schema/ifc4_properties.json", + "types": BASE_MODULE_PATH / "schema/ifc4_types.json", + "classes_suggestions": BASE_MODULE_PATH / "schema/ifc_classes_suggestions.json", + }, + "IFC4X3": { + "entities": BASE_MODULE_PATH / "schema/ifc4x3_entities.json", + "properties": BASE_MODULE_PATH / "schema/ifc4x3_properties.json", + "types": BASE_MODULE_PATH / "schema/ifc4x3_types.json", + "classes_suggestions": BASE_MODULE_PATH / "schema/ifc_classes_suggestions.json", + }, +} + +db: dict[SUPPORTED_SCHEMA, SchemaData] = None +schema_by_name: dict[SUPPORTED_SCHEMA, Optional[ifcopenshell_wrapper.schema_definition]] = { + "IFC2X3": None, + "IFC4": None, + "IFC4X3": None, +} + + +def get_db(version: ifcopenshell.util.schema.IFC_SCHEMA) -> Union[SchemaData, None]: + global db + if not db: + db = {ifc_version: dict() for ifc_version in SCHEMA_FILES} + for ifc_version in SCHEMA_FILES: + for data_type in SCHEMA_FILES[ifc_version]: + schema_path = SCHEMA_FILES[ifc_version][data_type] + if not schema_path.is_file(): + print(f"Schema file {schema_path} wasn't found.") + files_missing = True + continue + + with open(schema_path, "r") as fi: + db[ifc_version][data_type] = json.load(fi) + + version = ifcopenshell.util.schema.get_fallback_schema(version) + return db.get(version) + + +def get_schema_by_name(version: str) -> ifcopenshell_wrapper.schema_definition: + global schema_by_name + version = ifcopenshell.util.schema.get_fallback_schema(version) + if not schema_by_name[version]: + schema_by_name[version] = ifcopenshell.schema_by_name(version) + return schema_by_name[version] + + +def get_class_suggestions( + version: ifcopenshell.util.schema.IFC_SCHEMA, + class_name: str, +) -> Union[ClassesSuggestions, None]: + db = get_db(version) + if not db: + return + class_suggestions = db["classes_suggestions"].get(class_name) + return class_suggestions + + +def get_entity_doc( + version: ifcopenshell.util.schema.IFC_SCHEMA, + entity_name: str, + recursive: bool = True, +) -> Union[EntityData, None]: + db = get_db(version) + if db: + entity = copy.deepcopy(db["entities"].get(entity_name)) + if not recursive: + return entity + + ifc_schema = get_schema_by_name(version) + ifc_entity = ifc_schema.declaration_by_name(entity_name) + ifc_supertype = ifc_entity.supertype() + if ifc_supertype: + parent_entity = get_entity_doc(version, ifc_supertype.name(), recursive=True) + if "attributes" not in entity: + entity["attributes"] = dict() + for parent_attr in parent_entity.get("attributes", []): + entity["attributes"][parent_attr] = parent_entity["attributes"][parent_attr] + return entity + + +def get_attribute_doc( + version: ifcopenshell.util.schema.IFC_SCHEMA, + entity: str, + attribute: str, + recursive=True, +) -> Union[str, None]: + db = get_db(version) + if db: + entity_ = get_entity_doc(version, entity, recursive) + if entity_ and "attributes" in entity_: + return entity_["attributes"].get(attribute) + + +def get_predefined_type_doc( + version: ifcopenshell.util.schema.IFC_SCHEMA, + entity: str, + predefined_type: str, +) -> Union[str, None]: + db = get_db(version) + if db: + entity_ = db["entities"].get(entity) + if entity_: + return entity_.get("predefined_types", {}).get(predefined_type) + + +def get_property_set_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, pset: str) -> Union[PsetData, None]: + db = get_db(version) + if db: + return db["properties"].get(pset) + + +def get_property_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, pset: str, prop: str) -> Union[str, None]: + db = get_db(version) + if db: + pset_ = db["properties"].get(pset) + if pset_: + return pset_["properties"].get(prop) + + +def get_type_doc(version: ifcopenshell.util.schema.IFC_SCHEMA, ifc_type: str) -> Union[BaseData, None]: + db = get_db(version) + if db: + return db["types"].get(ifc_type) + + +# TODO: there are still some discrepancies between this method +# and the specs website because of the asymmetry +# More: https://github.com/buildingSMART/IFC4.3.x-development/issues/582 +def get_inverse_attributes(el): + inverse_attrs = [] + for a in el.all_inverse_attributes(): + attribute_type = a.attribute_reference().type_of_attribute() + # unpacking aggregation types + while isinstance(attribute_type, ifcopenshell.ifcopenshell_wrapper.aggregation_type): + attribute_type = attribute_type.type_of_element() + attribute_type = attribute_type.declared_type() + + # recursively looking for entities inside the selections + types_to_process = [attribute_type] + entity_attr_types = [] + while types_to_process: + for attr_type in types_to_process.copy(): + if isinstance(attr_type, ifcopenshell.ifcopenshell_wrapper.select_type): + types_to_process.extend([t for t in attr_type.select_list()]) + else: + entity_attr_types.append(attr_type.name()) + types_to_process.remove(attr_type) + + if el.name() in entity_attr_types: + inverse_attrs.append(a) + return inverse_attrs + + +class DocExtractor: + def clean_highlighted_words(self, text: str) -> str: + text = re.sub(r"\b_([a-zA-Z0-9]+)_\b", r"\1", text) + text = re.sub(r"\*\*([a-zA-Z0-9]+)\*\*", r"\1", text) + return text + + def clean_description(self, description): + description = description.replace("\n", " ") + description = description.replace("\u00a0", " ") + description = description.split("HISTORY:", 1)[0] + description = description.strip() + return description + + def extract_ifc2x3(self): + print("Parsing data for Ifc2.3.0.1") + if not IFC2x3_DOCS_LOCATION.is_dir(): + raise Exception( + f'Docs for IFC 2.3.0.1 expected to be in folder "{IFC2x3_DOCS_LOCATION.resolve()}\\"\n' + "For doc extraction please either setup docs as described above \n" + "or change IFC2x3_DOCS_LOCATION in the script accordingly.\n" + "You can download docs from the repository: \n" + "https://github.com/buildingSMART/IFC/tree/Ifc2.3.0.1" + ) + + # need to parse actual domains from the website + # since domains from github paths do not match domains from the websites + # probably due domains on the website being from 4_0 + # example (property set / github domain / website domain): + # Pset_AirTerminalBoxPHistory IfcControlExtension IfcHvacDomain + self.extract_ifc2x3_property_sets_site_domains() + self.extract_ifc2x3_entities() + self.extract_ifc2x3_property_sets() + self.extract_ifc2x3_types() + + def extract_ifc2x3_property_sets_site_domains(self): + property_sets_domains = dict() + r = requests.get("https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/psd/psd_index.htm") + html = BeautifulSoup(r.content, features="lxml") + for a in html.find_all("a"): + domain, pset = a["href"].removeprefix("./").removesuffix(".xml").split("/") + property_sets_domains[pset] = domain + + # export property sets data + with open(BASE_MODULE_PATH / "schema/ifc2x3_property_sets_site_domains.json", "w", encoding="utf-8") as fo: + print(f"{len(property_sets_domains)} property sets domains were parsed from the website") + json.dump(property_sets_domains, fo, sort_keys=True, indent=4) + + def setup_ifc2x3_reference_lookup(self): + # setup references look up tables to convert property hrefs to actual data paths + references_paths_lookup = dict() + glob_query = f"{IFC2x3_DOCS_LOCATION}/Constants/*/*" + parsed_paths = [filepath for filepath in glob.iglob(f"{IFC2x3_DOCS_LOCATION}/Properties/*/*", recursive=False)] + parsed_paths += [filepath for filepath in glob.iglob(f"{IFC2x3_DOCS_LOCATION}/Constants/*/*", recursive=False)] + for parsed_path in parsed_paths: + parsed_path = Path(parsed_path) + # all references omit "$" character, I've checked it on 2_3 + # need to check it if moving to next IFC version + property_reference = parsed_path.stem.replace("$", "") + references_paths_lookup[property_reference] = parsed_path + return references_paths_lookup + + def extract_ifc2x3_entities(self): + ifc2x3_references_paths_lookup = self.setup_ifc2x3_reference_lookup() + ifc4_references_paths_lookup = self.setup_ifc4_reference_lookup() + entities_dict = dict() + + # search + entities_paths = [ + filepath for filepath in glob.iglob(f"{IFC2x3_DOCS_LOCATION}/Sections/**/Entities", recursive=True) + ] + for parse_folder_path in entities_paths: + for entity_path in glob.iglob(f"{parse_folder_path}/**/"): + entity_path = Path(entity_path) + entity_name = entity_path.stem + entities_dict[entity_name] = dict() + + # utf-8-sig because of \ufeff occcurs - meaning it's utf bom encoded + md_path = entity_path / "Documentation.md" + xml_path = entity_path / "DocEntity.xml" + md_url_part = urllib.parse.quote(str(md_path.relative_to(Path(__file__).parent).as_posix())) + github_md_url = f"https://github.com/buildingSMART/IFC/blob/{md_url_part}" + + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + entity_description = BeautifulSoup(html, features="lxml").find("p").text + entity_description = entity_description.replace("\n", " ") + entity_description = entity_description.replace("\u00a0", " ") + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + + entity_attrs = dict() + predefined_types = dict() + # temporarily disable MarkupResemblesLocatorWarning + # because BeautifulSoup wrongly assume we confused + # html code for filepath and gives warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=MarkupResemblesLocatorWarning) + + for html_attr in bs_tree.find_all("docattribute"): + attr_name = html_attr["name"] + if attr_name == "PredefinedType": + # get references to all predefined types + defined_type = html_attr["definedtype"] + enum_path = xml_path.parents[2] / "Types" / defined_type / "DocEnumeration.xml" + with open(enum_path, "r", encoding="utf-8") as fi: + enum_bs_tree = BeautifulSoup(fi.read(), features="lxml") + hrefs = [i["href"] for i in enum_bs_tree.find_all("docconstant")] + + # iterate over list of predefined types + for href in hrefs: + # in IFC2X3 all documentation for constants is empty + # and as a temporary solution I'm trying to get constant's description from IFC4 + const_path = ifc4_references_paths_lookup.get( + href, ifc2x3_references_paths_lookup[href] + ) + with open(const_path, "r", encoding="utf-8") as fi: + const_bs_tree = BeautifulSoup(fi.read(), features="lxml") + const_name = const_bs_tree.find("docconstant")["name"] + description_tag = const_bs_tree.find("documentation") + const_description = "" if not description_tag else description_tag.text + predefined_types[const_name] = const_description + + else: + html_description = BeautifulSoup(html_attr.text, features="lxml") + attr_description = html_description.get_text() + + attr_description = attr_description.replace("\n", " ") + attr_description = attr_description.replace("\u00a0", " ") + attr_description = attr_description.replace("&npsp;", " ") + + # discard part of the description with changelog + # Example: + # https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/ifcpresentationdefinitionresource/lexical/ifcannotationfillarea.htm + attr_description = attr_description.split("IFC2x Edition 3 CHANGE", 1)[0] + attr_description = attr_description.split("IFC2x Edition 2 Addendum 2 CHANGE", 1)[0] + attr_description = attr_description.split("IFC2x2 Addendum 1 change", 1)[0] + attr_description = attr_description.split("IFC2x PLATFORM CHANGE", 1)[0] + attr_description = attr_description.split("IFC2x3 CHANGE", 1)[0] + attr_description = attr_description.split("IFC2x Edition3 CHANGE", 1)[0] + + attr_description = attr_description.strip().rstrip(">").strip() + entity_attrs[attr_name] = attr_description + + if entity_attrs: + entities_dict[entity_name]["attributes"] = entity_attrs + + if predefined_types: + entities_dict[entity_name]["predefined_types"] = predefined_types + + entities_dict[entity_name]["description"] = entity_description + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/" + f"{md_path.parents[2].name.lower()}/lexical/{entity_name.lower()}.htm" + ) + entities_dict[entity_name]["spec_url"] = spec_url + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc2x3_entities.json", "w", encoding="utf-8") as fo: + print(f"{len(entities_dict)} entities parsed") + json.dump(entities_dict, fo, sort_keys=True, indent=4) + + def extract_ifc2x3_property_sets(self): + property_sets_dict = dict() + property_sets_references = dict() + + # extract lists of properties and theirs references for each property set + parsed_paths = [ + filepath for filepath in glob.iglob(f"{IFC2x3_DOCS_LOCATION}/Sections/**/PropertySets", recursive=True) + ] + + # prepare property sets domains from the website we extracted earlier + with open(BASE_MODULE_PATH / "schema/ifc2x3_property_sets_site_domains.json", "r") as fi: + property_sets_site_domains = json.load(fi) + + for parse_folder_path in parsed_paths: + for property_set_path in glob.iglob(f"{parse_folder_path}/**/"): + property_set_path = Path(property_set_path) + property_set_name = property_set_path.stem + property_set_dict = dict() + + property_references = list() + xml_path = property_set_path / "DocPropertySet.xml" + md_path = property_set_path / "Documentation.md" + + if md_path.is_file(): + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + property_set_description = BeautifulSoup(html, features="lxml").find("p").text + property_set_description = property_set_description.replace("\n", " ") + property_set_description = property_set_description.split("HISTORY:", 1)[0] + property_set_description = property_set_description.strip() + property_set_dict["description"] = property_set_description + else: + print( + f"WARNING. Property set {property_set_name} has no Documentation.md, " + f"property set will be left without description." + ) + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + for html_attr in bs_tree.find_all("docproperty"): + property_references.append(html_attr["href"]) + + property_sets_references[property_set_name] = property_references + property_set_domain = property_sets_site_domains[property_set_name] + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML" + f"/psd/{property_set_domain}/{property_set_name}.xml" + ) + property_set_dict["spec_url"] = spec_url + property_sets_dict[property_set_name] = property_set_dict + + # setup references look up tables to convert property hrefs to actual data paths + references_paths_lookup = self.setup_ifc2x3_reference_lookup() + + # setup a function because we'll need to check child properties recusively + def get_property_info_by_href(href): + property_dict = dict() + property_path = references_paths_lookup[href] + + md_path = property_path / "Documentation.md" + xml_path = property_path / "DocProperty.xml" + md_url_part = urllib.parse.quote(str(md_path.relative_to(Path(__file__).parent).as_posix())) + xml_url_part = urllib.parse.quote(str(xml_path.relative_to(Path(__file__).parent).as_posix())) + github_md_url = f"https://github.com/buildingSMART/IFC/blob/{md_url_part}" + github_xml_url = f"https://github.com/buildingSMART/IFC/blob/{xml_url_part}" + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + tags = bs_tree.find_all("docproperty") + + # check for child properties - if they are present parse their data recursively + elements_tag = bs_tree.find("elements") + if elements_tag is not None: + child_tags = elements_tag.find_all("docproperty") + child_tags_dict = dict() + + for child_tag in child_tags: + child_tag_href = child_tag["href"] + child_tag_name, child_tag_dict = get_property_info_by_href(child_tag_href) + child_tags_dict[child_tag_name] = child_tag_dict + tags.remove(child_tag) + property_dict["children"] = child_tags_dict + print(f"Child nodes found inside property xml. Url: {github_xml_url}") + + if len(tags) != 1: + print( + f"WARNING. Found more properties inside property xml, " + f"only the first one was parsed (number of properties: {len(tags)}). Url: {github_xml_url}." + ) + property_name = tags[0]["name"] + + if not md_path.is_file(): + print( + f"WARNING. Property {property_name} is missing documentation.md, " + f"property will be left without description. Url: {github_xml_url}" + ) + else: + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + description = BeautifulSoup(html, features="lxml").find("p").text + description = description.replace("\n", " ") + description = description.replace("\u00a0", " ") + property_dict["description"] = description + return (property_name, property_dict) + + # lookup each property reference and save it's name and description + for property_set_name in property_sets_references: + properties_dict = dict() + for property_reference in property_sets_references[property_set_name]: + property_name, property_dict = get_property_info_by_href(property_reference) + properties_dict[property_name] = property_dict + property_sets_dict[property_set_name]["properties"] = properties_dict + + # export property sets data + with open(BASE_MODULE_PATH / "schema/ifc2x3_properties.json", "w", encoding="utf-8") as fo: + print(f"{len(property_sets_dict)} property sets parsed") + json.dump(property_sets_dict, fo, sort_keys=True, indent=4) + + def extract_ifc2x3_types(self): + types_dict = dict() + # search + types_paths = [filepath for filepath in glob.iglob(f"{IFC2x3_DOCS_LOCATION}/Sections/**/Types", recursive=True)] + for parse_folder_path in types_paths: + for type_path in glob.iglob(f"{parse_folder_path}/**/"): + type_path = Path(type_path) + type_name = type_path.stem + types_dict[type_name] = dict() + md_path = type_path / "Documentation.md" + + # utf-8-sig because of \ufeff occcurs - meaning it's utf bom encoded + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + type_description = BeautifulSoup(html, features="lxml").find("p").text + type_description = type_description.replace("\n", " ") + type_description = type_description.replace("\u00a0", " ") + type_description = type_description.replace("Definition from ISO/CD 10303-46:1992: ", "") + type_description = type_description.replace("Definition from ISO/CD 10303-42:1992 ", "") + type_description = type_description.replace("Definition from ISO/CD 10303-42:1992: ", "") + type_description = type_description.replace("Definition from ISO/CD 10303-41:1992: ", "") + + type_description = type_description.strip() + + if type_description: + types_dict[type_name]["description"] = type_description + + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/HTML/" + f"{md_path.parents[2].name.lower()}/lexical/{type_name.lower()}.htm" + ) + types_dict[type_name]["spec_url"] = spec_url + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc2x3_types.json", "w", encoding="utf-8") as fo: + print(f"{len(types_dict)} ifc types parsed") + json.dump(types_dict, fo, sort_keys=True, indent=4) + + def extract_ifc4(self): + print("Parsing data for Ifc4.0.2.1") + if not IFC4_DOCS_LOCATION.is_dir(): + raise Exception( + f'Docs for Ifc4.0.2.1 expected to be in folder "{IFC4_DOCS_LOCATION.resolve()}\\"\n' + "For doc extraction please either setup docs as described above \n" + "or change IFC4_DOCS_LOCATION in the script accordingly.\n" + "You can download docs from the repository: \n" + "https://github.com/buildingSMART/IFC/tree/Ifc4.0.2.1" + ) + + # actually domains in Ifc 4.0 are consistent between website and docs + # BUT there are two property sets that site is missing and therefore they won't have spec_url + # because of them I left the site parsing too + # missed property sets: + # Pset_BuildingElementCommon Pset_ElementCommon + self.extract_ifc4_property_sets_site_domains() + self.extract_ifc4_entities() + self.extract_ifc4_property_sets() + self.extract_ifc4_types() + + def extract_ifc4_property_sets_site_domains(self): + property_sets_domains = dict() + with requests.get( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1" + "/HTML/annex/annex-b/alphabeticalorder_psets.htm" + ) as r: + html = BeautifulSoup(r.content, features="lxml") + for a in html.find_all("a", {"class": "listing-link"}): + href_split = a["href"].split("/") + domain = href_split[3] + pset = href_split[5].removesuffix(".htm") + property_sets_domains[pset] = domain + + with requests.get( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/" + "/HTML/annex/annex-b/alphabeticalorder_qsets.htm" + ) as r: + html = BeautifulSoup(r.content, features="lxml") + for a in html.find_all("a", {"class": "listing-link"}): + href_split = a["href"].split("/") + domain = href_split[3] + pset = href_split[5].removesuffix(".htm") + property_sets_domains[pset] = domain + + # export property sets data + with open(BASE_MODULE_PATH / "schema/ifc4_property_sets_site_domains.json", "w", encoding="utf-8") as fo: + print(f"{len(property_sets_domains)} property sets domains were parsed from the website") + json.dump(property_sets_domains, fo, sort_keys=True, indent=4) + + def setup_ifc4_reference_lookup(self): + references_paths_lookup = dict() + parsed_paths = [filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Properties/*/*", recursive=False)] + parsed_paths += [filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Quantities/*/*", recursive=False)] + parsed_paths += [filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Constants/*/*", recursive=False)] + for parsed_path in parsed_paths: + parsed_path = Path(parsed_path) + # all references omit "$" character, I've checked it on 4_0 + # need to check it if moving to next IFC version + # btw no reason to check if all references were used in properties + # because there are also child properties + property_reference = parsed_path.stem.replace("$", "") + references_paths_lookup[property_reference] = parsed_path + return references_paths_lookup + + def extract_ifc4_entities(self): + references_paths_lookup = self.setup_ifc4_reference_lookup() + entities_dict = dict() + + # search + entities_paths = [ + filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Sections/**/Entities", recursive=True) + ] + for parse_folder_path in entities_paths: + for entity_path in glob.iglob(f"{parse_folder_path}/**/"): + entity_path = Path(entity_path) + entity_name = entity_path.stem + entities_dict[entity_name] = dict() + + md_path = entity_path / "Documentation.md" + xml_path = entity_path / "DocEntity.xml" + md_url_part = urllib.parse.quote(str(md_path.relative_to(Path(__file__).parent).as_posix())) + github_md_url = f"https://github.com/buildingSMART/IFC/blob/{md_url_part}" + + # utf-8-sig because of \ufeff occcurs - meaning it's utf bom encoded + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + entity_description = BeautifulSoup(html, features="lxml").find("p").text + entity_description = entity_description.replace("\n", " ") + entity_description = entity_description.replace("\u00a0", " ") + entity_description = entity_description.replace("{ .extDef}", "") + entity_description = entity_description.strip() + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + + entity_attrs = dict() + predefined_types = dict() + # temporarily disable MarkupResemblesLocatorWarning + # because BeautifulSoup wrongly assume we confused + # html code for filepath and gives warnings + with warnings.catch_warnings(): + warnings.simplefilter("ignore", category=MarkupResemblesLocatorWarning) + + for html_attr in bs_tree.find_all("docattribute"): + attr_name = html_attr["name"] + if attr_name == "PredefinedType": + # get references to all predefined types + defined_type = html_attr["definedtype"] + enum_path = xml_path.parents[2] / "Types" / defined_type / "DocEnumeration.xml" + with open(enum_path, "r", encoding="utf-8") as fi: + enum_bs_tree = BeautifulSoup(fi.read(), features="lxml") + hrefs = [i["href"] for i in enum_bs_tree.find_all("docconstant")] + + # iterate over list of predefined types + for href in hrefs: + const_path = references_paths_lookup[href] + with open(const_path, "r", encoding="utf-8") as fi: + const_bs_tree = BeautifulSoup(fi.read(), features="lxml") + const_name = const_bs_tree.find("docconstant")["name"] + description_tag = const_bs_tree.find("documentation") + const_description = "" if not description_tag else description_tag.text + predefined_types[const_name] = const_description + else: + html_description = BeautifulSoup(html_attr.text, features="lxml") + attr_description = html_description.get_text() + attr_description = attr_description.replace("\n", " ") + attr_description = attr_description.replace("\u00a0", " ") + + # discard part of the description with changelog, notes and examples etc. + # Those notes actually can be useful but we'll need a way to reformat them + # Example: + # https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML/schema/ifcsharedbldgelements/lexical/ifcrelconnectspathelements.htm + attr_description = attr_description.split("{ .change-ifc", 1)[0] + attr_description = attr_description.split("{ .note", 1)[0] + attr_description = attr_description.split("{ .examples", 1)[0] + attr_description = attr_description.split("{ .deprecated", 1)[0] + attr_description = attr_description.split("{ .history", 1)[0] + + attr_description = attr_description.strip() + entity_attrs[attr_name] = attr_description + + if entity_attrs: + entities_dict[entity_name]["attributes"] = entity_attrs + + if predefined_types: + entities_dict[entity_name]["predefined_types"] = predefined_types + + entities_dict[entity_name]["description"] = entity_description + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML/schema/" + f"{md_path.parents[2].name.lower()}/lexical/{entity_name.lower()}.htm" + ) + entities_dict[entity_name]["spec_url"] = spec_url + # entities_dict[entity_name]['github_url'] = github_md_url + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc4_entities.json", "w", encoding="utf-8") as fo: + print(f"{len(entities_dict)} entities parsed") + json.dump(entities_dict, fo, sort_keys=True, indent=4) + + def extract_ifc4_property_sets(self): + # function parses both property and quantity sets + property_sets_dict = dict() + property_sets_references = dict() + + # extract lists of properties and theirs references for each property set + parsed_paths = [ + filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Sections/**/PropertySets", recursive=True) + ] + parsed_paths += [ + filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Sections/**/QuantitySets", recursive=True) + ] + + # prepare property sets domains from the website we extracted earlier + with open(BASE_MODULE_PATH / "schema/ifc4_property_sets_site_domains.json", "r") as fi: + property_sets_site_domains = json.load(fi) + + psets_test = set() + for parse_folder_path in parsed_paths: + for property_set_path in glob.iglob(f"{parse_folder_path}/**/"): + property_set_path = Path(property_set_path) + property_set_name = property_set_path.stem + property_set_dict = dict() + + property_references = list() + property_quantity = property_set_path.parents[0].name == "QuantitySets" + xml_path = property_set_path / ("DocQuantitySet.xml" if property_quantity else "DocPropertySet.xml") + md_path = property_set_path / "Documentation.md" + + if md_path.is_file(): + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + property_set_description = BeautifulSoup(html, features="lxml").find("p").text + property_set_description = property_set_description.replace("\n", " ") + property_set_description = property_set_description.split("HISTORY:", 1)[0] + property_set_description = property_set_description.strip() + property_set_dict["description"] = property_set_description + else: + print( + f"WARNING. Property set {property_set_name} has no Documentation.md, " + f"property set will be left without description." + ) + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + for html_attr in bs_tree.find_all("docquantity" if property_quantity else "docproperty"): + property_references.append(html_attr["href"]) + + property_sets_references[property_set_name] = property_references + + if property_set_name.lower() not in property_sets_site_domains: + print( + f"WARNING. {property_set_name} was not found on the spec website, " + "this property set won't have any spec_url in schema." + ) + else: + property_set_domain = property_sets_site_domains.get(property_set_name.lower(), "") + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML" + f"/schema/{property_set_domain}" + f"/{'qset' if property_quantity else 'pset'}" + f"/{property_set_name.lower()}.htm" + ) + property_set_dict["spec_url"] = spec_url + property_sets_dict[property_set_name] = property_set_dict + + # setup references look up tables to convert property hrefs to actual data paths + references_paths_lookup = self.setup_ifc4_reference_lookup() + + # setup a function because we'll need to check child properties recusively + def get_property_info_by_href(href): + property_dict = dict() + property_path = references_paths_lookup[href] + + property_quantity = property_path.parents[1].name == "Quantities" + + md_path = property_path / "Documentation.md" + xml_path = property_path / ("DocQuantity.xml" if property_quantity else "DocProperty.xml") + md_url_part = urllib.parse.quote(str(md_path.relative_to(Path(__file__).parent).as_posix())) + github_md_url = f"https://github.com/buildingSMART/IFC/blob/{md_url_part}" + xml_url_part = urllib.parse.quote(str(xml_path.relative_to(Path(__file__).parent).as_posix())) + github_xml_url = f"https://github.com/buildingSMART/IFC/blob/{xml_url_part}" + + with open(xml_path, "r", encoding="utf-8") as fi: + bs_tree = BeautifulSoup(fi.read(), features="lxml") + tags = bs_tree.find_all("docquantity" if property_quantity else "docproperty") + + # check for child properties - if they are present parse their data recursively + elements_tag = bs_tree.find("elements") + if elements_tag is not None: + child_tags = elements_tag.find_all("docquantity" if property_quantity else "docproperty") + child_tags_dict = dict() + + for child_tag in child_tags: + child_tag_href = child_tag["href"] + child_tag_name, child_tag_dict = get_property_info_by_href(child_tag_href) + child_tags_dict[child_tag_name] = child_tag_dict + tags.remove(child_tag) + property_dict["children"] = child_tags_dict + print(f"Child nodes found inside property xml. Url: {github_xml_url}") + + if len(tags) != 1: + print( + f"WARNING. Found more properties inside property xml, " + f"only the first one was parsed (number of properties: {len(tags)}). Url: {github_xml_url}." + ) + property_name = tags[0]["name"] + + if not md_path.is_file(): + print( + f"WARNING. Property {property_name} is missing documentation.md, property will be left without description. " + f"Url: {github_xml_url}" + ) + else: + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read()) + description = BeautifulSoup(html, features="lxml").find("p").text + description = description.replace("\n", " ") + description = description.replace("\u00a0", " ") + property_dict["description"] = description + return (property_name, property_dict) + + # lookup each property reference and save it's name and description + for property_set_name in property_sets_references: + properties_dict = dict() + for property_reference in property_sets_references[property_set_name]: + property_name, property_dict = get_property_info_by_href(property_reference) + properties_dict[property_name] = property_dict + property_sets_dict[property_set_name]["properties"] = properties_dict + + # export property sets data + with open(BASE_MODULE_PATH / "schema/ifc4_properties.json", "w", encoding="utf-8") as fo: + print(f"{len(property_sets_dict)} property sets parsed") + json.dump(property_sets_dict, fo, sort_keys=True, indent=4) + + def extract_ifc4_types(self): + types_dict = dict() + # search + types_paths = [filepath for filepath in glob.iglob(f"{IFC4_DOCS_LOCATION}/Sections/**/Types", recursive=True)] + for parse_folder_path in types_paths: + for type_path in glob.iglob(f"{parse_folder_path}/**/"): + type_path = Path(type_path) + type_name = type_path.stem + types_dict[type_name] = dict() + md_path = type_path / "Documentation.md" + + # utf-8-sig because of \ufeff occcurs - meaning it's utf bom encoded + with open(md_path, "r", encoding="utf-8-sig") as fi: + # convert markdown to html for easier parsing + html = markdown(fi.read().replace("{ .extDef}", "")) + type_description = BeautifulSoup(html, features="lxml").find("p").text + type_description = type_description.replace("\n", " ") + type_description = type_description.replace("\u00a0", " ") + type_description = type_description.replace("{ .extDef}", "") + type_description = type_description.replace( + "NOTE Definition according to ISO/CD 10303-41:1992 ", "" + ) + type_description = type_description.replace("Definition from ISO/CD 10303-41:1992: ", "") + + type_description = type_description.strip() + + if type_description: + types_dict[type_name]["description"] = type_description + + spec_url = ( + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4/ADD2_TC1/HTML/schema/" + f"{md_path.parents[2].name.lower()}/lexical/{type_name.lower()}.htm" + ) + types_dict[type_name]["spec_url"] = spec_url + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc4_types.json", "w", encoding="utf-8") as fo: + print(f"{len(types_dict)} ifc types parsed") + json.dump(types_dict, fo, sort_keys=True, indent=4) + + def extract_ifc4x3(self): + print("Parsing data for Ifc4.3.0.1") + if not IFC4x3_DEV_LOCATION.is_dir(): + raise Exception( + f'Specs development repository for Ifc4.3.0.1 expected to be in folder "{IFC4x3_DEV_LOCATION.resolve()}\\"\n' + "For doc extraction please either setup docs as described above \n" + "or change IFC4x3_DEV_LOCATION in the script accordingly.\n" + "You can download docs from the repository: \n" + "https://github.com/buildingSMART/IFC4.3.x-development" + ) + if not IFC4x3_HTML_LOCATION.is_dir(): + raise Exception( + f'Formal release for Ifc4.3.0.1 expected to be in folder "{IFC4x3_HTML_LOCATION.resolve()}\\"\n' + "For doc extraction please either setup docs as described above \n" + "or change IFC4x3_HTML_LOCATION in the script accordingly.\n" + "You can download docs from the repository: \n" + "https://github.com/buildingsmart/ifc4.3-html" + ) + dev_code_path = IFC4x3_DEV_LOCATION / "code" + description_json_path = dev_code_path / "entities_description.json" + if not description_json_path.is_file(): + shutil.copy( + BASE_MODULE_PATH / "ifc4x3dev_scrape_data_for_docs.py", + dev_code_path / "ifc4x3dev_scrape_data_for_docs.py", + ) + raise Exception( + f'The entities description data expected to be located in \n"{description_json_path.resolve()}.\n' + f"To generate it `ifc4x3dev_scrape_data_for_docs.py` will be copied from current folder to \n{dev_code_path}\n" + "and you'll need to run in from `/code` folder.\nThis script will use development `server.py` " + "module to extract entities descriptions.\n\n" + "Before running it make sure you run `create_resources.sh` from `/code` folder first.\n" + "You'll need to complete at least 3 commands from `create_resources.sh`:\n" + " py extract_concepts_from_xmi.py ../schemas/IFC.xml\n" + " py to_pset.py ../schemas/IFC.xml psd\n" + " py parse_xmi.py ../schemas/IFC.xml" + ) + + self.extract_ifc4x3_entities() + self.extract_ifc4x3_property_sets() + + def extract_ifc4x3_entities(self): + with open(IFC4x3_DEV_LOCATION / "code/entities_description.json", "r") as fi: + entities_description = json.load(fi) + + entities_dict = dict() + types_dict = dict() + schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name("IFC4X3_ADD2") + + for entity in schema.declarations(): + entity_name = entity.name() + + entity_data = dict() + entity_data["spec_url"] = IFC4x3_SPEC_URL_TEMPLATE % entity_name + + if entity_name not in entities_description: + print( + f"WARNING. Entity {entity_name} is not present in data parsed from DEV DOCUMENTATION " + "even though it's present in ifcopenshell schema. It's description will be left empty." + ) + description = "" + else: + description = self.clean_highlighted_words(entities_description[entity_name]["description"]) + entity_data["description"] = description + + # types = type_declaration + enumeration_type + select_type + if not isinstance(entity, ifcopenshell.ifcopenshell_wrapper.entity): + types_dict[entity_name] = entity_data + continue + + # entities processing + # assign attributes / predef types data + parsed_attributes_data = entities_description[entity_name]["attributes"] + parsed_predefined_types_data = entities_description[entity_name]["predefined_types"] + attributes_data = dict() + predefined_types = dict() + + # iterate over forward and inverse entity attributes + # TODO: more eloquent way to get inverse attributes of the declaration? + for a in list(entity.attributes()) + get_inverse_attributes(entity): + attr_name = a.name() + # predefined types + if attr_name == "PredefinedType": + for v in ifcopenshell.util.attribute.get_enum_items(a): + if v not in parsed_predefined_types_data: + print( + f"WARNING. Predefined type {v} (of entity {entity_name}) is not present in data parsed from DEV DOCUMENTATION " + "even though it's present in ifcopenshell schema. It's description will be left empty." + ) + description = "" + else: + description = self.clean_description(parsed_predefined_types_data[v]) + predefined_types[v] = description + continue + + # attributes + if attr_name not in parsed_attributes_data: + print( + f"WARNING. Attribute {attr_name} (of entity {entity_name}) is not present in data parsed from DEV DOCUMENTATION " + "even though it's present in ifcopenshell schema. It's description will be left empty." + ) + description = "" + else: + description = self.clean_description(parsed_attributes_data[attr_name]) + attributes_data[attr_name] = description + + if attributes_data: + entity_data["attributes"] = attributes_data + if predefined_types: + entity_data["predefined_types"] = predefined_types + + entities_dict[entity_name] = entity_data + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc4x3_entities.json", "w", encoding="utf-8") as fo: + print(f"{len(entities_dict)} entities parsed") + json.dump(entities_dict, fo, sort_keys=True, indent=4) + + # export entities data + with open(BASE_MODULE_PATH / "schema/ifc4x3_types.json", "w", encoding="utf-8") as fo: + print(f"{len(types_dict)} ifc types parsed") + json.dump(types_dict, fo, sort_keys=True, indent=4) + + def extract_ifc4x3_property_sets(self): + pset_data_zip = IFC4x3_HTML_LOCATION / "IFC/RELEASE/IFC4x3/HTML/annex-a-psd.zip" + pset_data_location = BASE_MODULE_PATH / "temp/annex-a-psd" + with zipfile.ZipFile(pset_data_zip, "r") as fi_zip: + fi_zip.extractall(pset_data_location) + + property_sets_dict = dict() + + for pset_path in glob.iglob(f"{pset_data_location}/*.xml"): + pset_path = Path(pset_path) + pset_name = pset_path.stem + + # pset / qset + pset_type = True if pset_name.split("_")[0] == "Pset" else False + + pset_data = dict() + pset_data["spec_url"] = IFC4x3_SPEC_URL_TEMPLATE % pset_name + + with open(pset_path, "r", encoding="utf-8") as fi: + root_xml = etree.fromstring(fi.read()) + + description = root_xml.find("Definition").text + pset_data["description"] = self.clean_description(description) + + # parsing pset/qset properties data + prop_data = dict() + search_tag = "PropertyDef" if pset_type else "QtoDef" + props = root_xml.find(search_tag + "s").findall(search_tag) + for prop in props: + prop_name = prop.find("Name").text + prop_description = prop.find("Definition").text + if not prop_description: # it could be just `` + prop_description = "" + prop_description = self.clean_description(prop_description) + prop_data[prop_name] = {"description": prop_description} + + pset_data["properties"] = prop_data + property_sets_dict[pset_name] = pset_data + + # export property sets data + with open(BASE_MODULE_PATH / "schema/ifc4x3_properties.json", "w", encoding="utf-8") as fo: + print(f"{len(property_sets_dict)} property sets parsed") + json.dump(property_sets_dict, fo, sort_keys=True, indent=4) + + shutil.rmtree(pset_data_location) + + +def run_doc_api_examples(): + print("Entities (with parent entities attributes included):") + print(get_entity_doc("IFC2X3", "IfcWindow")) + print(get_entity_doc("IFC4", "IfcWindow")) + print(get_entity_doc("IFC4X3", "IfcWindow")) + + print("Entity attributes (with parent entities attributes included):") + print(get_attribute_doc("IFC2X3", "IfcWindow", "OwnerHistory")) + print(get_attribute_doc("IFC4", "IfcWindow", "OwnerHistory")) + print(get_attribute_doc("IFC4X3", "IfcWindow", "OwnerHistory")) + + print("Entity predefined types:") + print(get_predefined_type_doc("IFC2X3", "IfcControllerType", "FLOATING")) + print(get_predefined_type_doc("IFC4", "IfcControllerType", "FLOATING")) + print(get_predefined_type_doc("IFC4X3", "IfcControllerType", "FLOATING")) + + print("Propety sets:") + print(get_property_set_doc("IFC2X3", "Pset_ZoneCommon")) + print(get_property_set_doc("IFC4", "Pset_ZoneCommon")) + print(get_property_set_doc("IFC4X3", "Pset_ZoneCommon")) + + print("Propety sets attributes:") + print(get_property_doc("IFC2X3", "Pset_ZoneCommon", "Category")) + print(get_property_doc("IFC4", "Pset_ZoneCommon", "NetPlannedArea")) + print(get_property_doc("IFC4X3", "Pset_ZoneCommon", "NetPlannedArea")) + + print("Types:") + print(get_type_doc("IFC2X3", "IfcIsothermalMoistureCapacityMeasure")) + print(get_type_doc("IFC4", "IfcDuration")) + print(get_type_doc("IFC4X3", "IfcDuration")) + + +if __name__ == "__main__": + extractor = DocExtractor() + extractor.extract_ifc2x3() + extractor.extract_ifc4() + extractor.extract_ifc4x3() + + # run_doc_api_examples() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/element.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/element.py new file mode 100644 index 0000000000000000000000000000000000000000..7bbe8bdc9925dbc8bd680e435bf6fe66f63e1360 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/element.py @@ -0,0 +1,1847 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.guid +import ifcopenshell.util.element +import ifcopenshell.util.representation +from typing import Any, Callable, Optional, Union, Literal, overload +from collections.abc import Generator, Sequence +from collections import namedtuple + + +MATERIAL_TYPE = Literal[ + "IfcMaterial", + "IfcMaterialConstituentSet", + "IfcMaterialLayerSet", + "IfcMaterialLayerSetUsage", + "IfcMaterialProfileSet", + "IfcMaterialProfileSetUsage", + "IfcMaterialList", +] + + +def get_pset( + element: ifcopenshell.entity_instance, + name: str, + prop: Optional[str] = None, + psets_only: bool = False, + qtos_only: bool = False, + should_inherit: bool = True, + verbose: bool = False, +) -> Union[Any, dict[str, Any]]: + """Retrieve a single property set or single property + + This is more efficient than ifcopenshell.util.element.get_psets if you know + exactly which property set and property you are after. + + If should_inherit is true, the pset "id" only refers to the ID of the + occurrence, not the type's pset. + + :param element: The IFC Element entity + :param name: The name of the pset + :param prop: The name of the property + :param psets_only: Default as False. Set to true if only property sets are needed. + :param qtos_only: Default as False. Set to true if only quantities are needed. + :param should_inherit: Default as True. Set to false if you don't want to inherit property sets from the Type. + :return: A dictionary of property names and values, or a single value if a + property is specified. + + Example: + + .. code:: python + + element = ifc_file.by_type("IfcWall")[0] + psets_and_qtos = ifcopenshell.util.element.get_pset(element, "Pset_WallCommon") + """ + pset = None + type_pset = None + ifc_file = element.file + is_ifc2x3 = ifc_file.schema == "IFC2X3" + is_profile = False + + if element.is_a("IfcTypeObject"): + for definition in element.HasPropertySets or []: + if definition.Name == name: + pset = definition + break + elif ( + (is_ifc2x3_material := (is_ifc2x3 and element.is_a("IfcMaterial"))) + or element.is_a("IfcMaterialDefinition") + or (is_profile := element.is_a("IfcProfileDef")) + ): + if is_ifc2x3_material: + # Support extended props as they do have a name. + for definition in ifc_file.by_type("IfcExtendedMaterialProperties"): + if definition.Material == element and definition.Name == name: + pset = definition + break + elif is_ifc2x3 and is_profile: + # Don't support them as they don't have a name. + pass + else: + # IfcProfileDef or IfcMaterialDefinition, IFC4+. + for definition in element.HasProperties or []: + if definition.Name == name: + pset = definition + break + elif (is_defined_by := getattr(element, "IsDefinedBy", None)) is not None: + # other IfcObjectDefinition + if should_inherit: + element_type = ifcopenshell.util.element.get_type(element) + if element_type: + type_pset = get_pset(element_type, name, prop, should_inherit=False, verbose=verbose) + for relationship in is_defined_by: + if relationship.is_a("IfcRelDefinesByProperties"): + definition = relationship.RelatingPropertyDefinition + if definition.Name == name: + pset = definition + break + + if pset: + if ( + psets_only + and not pset.is_a("IfcPropertySet") + and not pset.is_a("IfcPreDefinedPropertySet") + and not (is_ifc2x3 and pset.is_a("IfcExtendedMaterialProperties")) + ): + pset = None + elif qtos_only and not pset.is_a("IfcElementQuantity"): + pset = None + + if type_pset is not None and not prop: + if psets_only or qtos_only: + type_pset_element = element.file.by_id(type_pset["id"]) + if ( + psets_only + and not type_pset_element.is_a("IfcPropertySet") + and not type_pset_element.is_a("IfcPreDefinedPropertySet") + ): + type_pset = None + elif qtos_only and not type_pset_element.is_a("IfcElementQuantity"): + type_pset = None + + if pset is None and type_pset is None: + return + + if not prop: + if type_pset: + occurrence_pset = get_property_definition(pset, verbose=verbose) + if occurrence_pset: + type_pset.update(occurrence_pset) + return type_pset + return get_property_definition(pset, verbose=verbose) + + value = get_property_definition(pset, prop=prop, verbose=verbose) + if value is None and type_pset is not None: + return type_pset + return value + + +def get_psets( + element: ifcopenshell.entity_instance, psets_only=False, qtos_only=False, should_inherit=True, verbose=False +) -> dict[str, dict[str, Any]]: + """Retrieve property sets, their related properties' names & values and ids. + + If should_inherit is true, the pset "id" only refers to the ID of the + occurrence, not the type's pset. + + :param element: The IFC Element entity + :param psets_only: Default as False. Set to true if only property sets are needed. + :param qtos_only: Default as False. Set to true if only quantities are needed. + :param should_inherit: Default as True. Set to false if you don't want to inherit property sets from the Type. + :param verbose: More detailed prop values, defaults to False. + :return: Key, value pair of psets' names and their properties' names & values + + Example: + + .. code:: python + + element = ifc_file.by_type("IfcWall")[0] + psets = ifcopenshell.util.element.get_psets(element, psets_only=True) + qsets = ifcopenshell.util.element.get_psets(element, qtos_only=True) + psets_and_qtos = ifcopenshell.util.element.get_psets(element) + """ + ifc_file = element.file + is_ifc2x3 = ifc_file.schema == "IFC2X3" + psets = {} + if element.is_a("IfcTypeObject"): + for definition in element.HasPropertySets or []: + if psets_only and not definition.is_a("IfcPropertySet") and not definition.is_a("IfcPreDefinedPropertySet"): + continue + if qtos_only and not definition.is_a("IfcElementQuantity"): + continue + psets.setdefault(definition.Name, {}).update(get_property_definition(definition, verbose=verbose)) + # NOTE: doesn't account for IFC2X3 missing HasProperties + elif ( + (is_ifc2x3_material := (is_ifc2x3 and element.is_a("IfcMaterial"))) + or element.is_a("IfcMaterialDefinition") + or element.is_a("IfcProfileDef") + ): + definitions: list[ifcopenshell.entity_instance] + if is_ifc2x3: + if is_ifc2x3_material: + # Only extended props have a name. + definitions = [d for d in ifc_file.by_type("IfcExtendedMaterialProperties") if d.Material == element] + else: + # Ignoring profiles as they don't have names. + definitions = [] + else: + definitions = getattr(element, "HasProperties", None) or [] + for definition in definitions: + if qtos_only: + continue + psets.setdefault(definition.Name, {}).update(get_property_definition(definition, verbose=verbose)) + elif (is_defined_by := getattr(element, "IsDefinedBy", None)) is not None: + # other IfcObjectDefinition + if should_inherit: + element_type = ifcopenshell.util.element.get_type(element) + if element_type: + psets = get_psets( + element_type, psets_only=psets_only, qtos_only=qtos_only, should_inherit=False, verbose=verbose + ) + for relationship in is_defined_by: + if relationship.is_a("IfcRelDefinesByProperties"): + definition = relationship.RelatingPropertyDefinition + if ( + psets_only + and not definition.is_a("IfcPropertySet") + and not definition.is_a("IfcPreDefinedPropertySet") + ): + continue + if qtos_only and not definition.is_a("IfcElementQuantity"): + continue + psets.setdefault(definition.Name, {}).update(get_property_definition(definition, verbose=verbose)) + return psets + + +@overload +def get_property_definition( + definition: Optional[ifcopenshell.entity_instance], prop: None = None, verbose=False +) -> dict[str, Any]: ... +@overload +def get_property_definition(definition: Optional[ifcopenshell.entity_instance], prop: str, verbose=False) -> Any: ... +@overload +def get_property_definition(definition: None, prop: None = None, verbose: bool = False) -> None: ... +def get_property_definition( + definition: Optional[ifcopenshell.entity_instance], prop: Optional[str] = None, verbose=False +) -> Union[Any, dict[str, Any]]: + """if prop name is not provided in `prop`, will return dict of all available properties + otherwise will return the value of the specified `prop`. + """ + if not definition: + return + + ifc_class = definition.is_a() + + if prop: + if ifc_class == "IfcElementQuantity": + return get_quantity(definition.Quantities, prop, verbose=verbose) + elif ifc_class == "IfcPropertySet": + return get_property(definition.HasProperties, prop, verbose=verbose) + elif ifc_class == "IfcMaterialProperties" or ifc_class == "IfcProfileProperties": + # IfcExtendedProperties + return get_property(definition.Properties, prop, verbose=verbose) + elif ifc_class == "IfcExtendedMaterialProperties": + # IFC2X3. + return get_property(definition.ExtendedProperties, prop, verbose=verbose) + else: + # Entity introduced in IFC4 + # definition.is_a('IfcPreDefinedPropertySet'): + for i in range(4, len(definition)): + if definition.attribute_name(i) == prop: + if (v := definition[i]) is not None: + return v + return + + props = {} + if ifc_class == "IfcElementQuantity": + # 5 IfcElementQuantity.Quantities + props.update(get_quantities(definition[5], verbose=verbose)) + elif ifc_class == "IfcPropertySet": + # 5 IfcPropertySet.HasProperties + props.update(get_properties(definition[4], verbose=verbose)) + elif ifc_class == "IfcMaterialProperties" or ifc_class == "IfcProfileProperties": + # 2 IfcExtendedProperties.Properties + props.update(get_properties(definition[2], verbose=verbose)) + elif ifc_class == "IfcExtendedMaterialProperties": + # 1 IfcExtendedMaterialProperties.ExtendedProperties + props.update(get_properties(definition[1], verbose=verbose)) + else: + # Entity introduced in IFC4 + # definition.is_a('IfcPreDefinedPropertySet'): + for prop_i in range(4, len(definition)): + if (v := definition[prop_i]) is not None: + props[definition.attribute_name(prop_i)] = v + props["id"] = definition.id() + return props + + +@overload +def get_quantity(quantities: list[ifcopenshell.entity_instance], name: str, verbose: Literal[False] = False) -> Any: ... +@overload +def get_quantity( + quantities: list[ifcopenshell.entity_instance], name: str, verbose: Literal[True] +) -> dict[str, Any]: ... +def get_quantity( + quantities: list[ifcopenshell.entity_instance], name: str, verbose=False +) -> Union[Any, dict[str, Any]]: + for quantity in quantities or []: + # 0 IfcPhysicalQuantity.Name + if quantity[0] != name: + continue + if quantity.is_a("IfcPhysicalSimpleQuantity"): + # 3 IfcPhysicalSimpleQuantity.XXXValue + result = quantity[3] + elif quantity.is_a("IfcPhysicalComplexQuantity"): + data = {k: v for k, v in quantity.get_info().items() if v is not None and k != "Name"} + data["properties"] = get_quantities(quantity.HasQuantities, verbose=verbose) + del data["HasQuantities"] + result = data + if verbose: + result = {"id": quantity.id(), "class": quantity.is_a(), "value": result} + return result + + +@overload +def get_quantities( + quantities: list[ifcopenshell.entity_instance], verbose: Literal[False] = False +) -> dict[str, Any]: ... +@overload +def get_quantities( + quantities: list[ifcopenshell.entity_instance], verbose: Literal[True] +) -> dict[str, dict[str, Any]]: ... +def get_quantities( + quantities: list[ifcopenshell.entity_instance], verbose=False +) -> dict[str, Union[Any, dict[str, Any]]]: + results = {} + for quantity in quantities or []: + # 0 IfcPhysicalQuantity.Name + quantity_name = quantity[0] + if quantity.is_a("IfcPhysicalSimpleQuantity"): + # 3 IfcPhysicalSimpleQuantity.XXXValue + results[quantity_name] = quantity[3] + if verbose: + results[quantity_name] = { + "id": quantity.id(), + "class": quantity.is_a(), + "value": results[quantity_name], + } + elif quantity.is_a("IfcPhysicalComplexQuantity"): + data = {k: v for k, v in quantity.get_info().items() if v is not None and k != "Name"} + data["properties"] = get_quantities(quantity.HasQuantities, verbose=verbose) + del data["HasQuantities"] + results[quantity_name] = data + if verbose: + results[quantity_name] = { + "id": data["id"], + "class": data["class"], + "value": results[quantity_name], + } + return results + + +@overload +def get_property(properties: list[ifcopenshell.entity_instance], name: str, verbose: Literal[False] = False) -> Any: ... +@overload +def get_property( + properties: list[ifcopenshell.entity_instance], name: str, verbose: Literal[True] +) -> dict[str, Any]: ... +def get_property( + properties: list[ifcopenshell.entity_instance], name: str, verbose=False +) -> Union[Any, dict[str, Any]]: + for prop in properties or []: + if prop.Name != name: + continue + is_single_value = False # For now we pass value type only for single values. + if prop.is_a("IfcPropertySingleValue"): + # 2 IfcPropertySingleValue.NominalValue + result = v.wrappedValue if (v := prop[2]) else None + result_type = v.is_a() if v else None + is_single_value = True + elif prop.is_a("IfcPropertyEnumeratedValue"): + # 2 IfcPropertyEnumeratedValue.EnumerationValues + result = [v.wrappedValue for v in values] if (values := prop[2]) else None + elif prop.is_a("IfcPropertyListValue"): + # 2 IfcPropertyListValue.ListValues + result = [v.wrappedValue for v in values] if (values := prop[2]) else None + elif prop.is_a("IfcPropertyBoundedValue"): + data = prop.get_info() + del data["Unit"] + result = data + elif prop.is_a("IfcPropertyTableValue"): + result = prop.get_info() + elif prop.is_a("IfcComplexProperty"): + data = {k: v for k, v in prop.get_info().items() if v is not None and k != "Name"} + data["properties"] = get_properties(prop.HasProperties, verbose=verbose) + del data["HasProperties"] + result = data + if verbose: + result = {"id": prop.id(), "class": prop.is_a(), "value": result} + if is_single_value: + result["value_type"] = result_type + return result + + +@overload +def get_properties( + properties: list[ifcopenshell.entity_instance], verbose: Literal[False] = False +) -> dict[str, Any]: ... +@overload +def get_properties( + properties: list[ifcopenshell.entity_instance], verbose: Literal[True] +) -> dict[str, dict[str, Any]]: ... +def get_properties( + properties: list[ifcopenshell.entity_instance], verbose=False +) -> dict[str, Union[Any, dict[str, Any]]]: + results = {} + for prop in properties or []: + ifc_class = prop.is_a() + prop_name = prop[0] # 0 IfcProperty.Name + if ifc_class == "IfcPropertySingleValue": + # 2 IfcPropertySingleValue.NominalValue + results[prop_name] = v.wrappedValue if (v := prop[2]) else None + if verbose: + results[prop_name] = { + "id": prop.id(), + "class": prop.is_a(), + "value": results[prop_name], + "value_type": v.is_a() if v else None, + } + elif ifc_class == "IfcPropertyEnumeratedValue": + # 2 IfcPropertyEnumeratedValue.EnumerationValues + results[prop_name] = [v.wrappedValue for v in values] if (values := prop[2]) else None + if verbose: + results[prop_name] = { + "id": prop.id(), + "class": prop.is_a(), + "value": results[prop_name], + } + elif ifc_class == "IfcPropertyListValue": + # 2 IfcPropertyListValue.ListValues + results[prop_name] = [v.wrappedValue for v in values] if (values := prop[2]) else None + if verbose: + results[prop_name] = { + "id": prop.id(), + "class": prop.is_a(), + "value": results[prop_name], + } + elif ifc_class == "IfcPropertyBoundedValue": + data = prop.get_info() + del data["Unit"] + results[prop_name] = data + if verbose: + results[prop_name] = { + "id": data["id"], + "class": data["type"], + "value": results[prop_name], + } + elif ifc_class == "IfcPropertyTableValue": + data = prop.get_info() + results[prop_name] = data + if verbose: + results[prop_name] = { + "id": data["id"], + "class": data["type"], + "value": results[prop_name], + } + elif ifc_class == "IfcComplexProperty": + data = {k: v for k, v in prop.get_info().items() if v is not None and k != "Name"} + data["properties"] = get_properties(prop.HasProperties, verbose=verbose) + del data["HasProperties"] + results[prop_name] = data + if verbose: + results[prop_name] = {"id": data["id"], "class": data["class"], "value": results[prop_name]} + return results + + +def get_elements_by_pset(pset: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + """Retrieve the elements (or element types) that are using the provided property set.""" + is_ifc2x3 = pset.file.schema == "IFC2X3" + elements = set() + if pset.is_a("IfcPropertySet") or pset.is_a("IfcPreDefinedPropertySet") or pset.is_a("IfcElementQuantity"): + rels = pset.PropertyDefinitionOf if is_ifc2x3 else pset.DefinesOccurrence + for rel in rels: + elements.update(rel.RelatedObjects) + for element_type in pset.DefinesType: + elements.add(element_type) + elif pset.is_a("IfcProfileProperties"): + elements.add(pset.ProfileDefinition) + elif pset.is_a("IfcMaterialProperties"): + elements.add(pset.Material) + else: + raise Exception(f"Unexpected pset type: '{pset.is_a()}' ({pset}).") + return elements + + +def get_element_mass_density(element: ifcopenshell.entity_instance) -> Union[float, None]: + """Calculate object mass density based on material's Pset_MaterialCommon.MassDensity. + + :param element: IFC element entity. + :return: ``float`` mass density in project units if calculation was successful, ``None`` if element either + doesn't have a material or this type of material is not supported. + """ + material = ifcopenshell.util.element.get_material(element) + if material is None: + return + + if ( + material.is_a("IfcMaterialLayerSet") + or material.is_a("IfcMaterialProfileSet") + or material.is_a("IfcMaterialConstituentSet") + ): + return + + if material.is_a("IfcMaterial"): + material_mass_density = ifcopenshell.util.element.get_pset(material, "Pset_MaterialCommon", "MassDensity") + return material_mass_density + + if material.is_a("IfcMaterialLayerSetUsage"): + material_layers = material.ForLayerSet.MaterialLayers + densities = [] + thicknesses = [] + obj_mass_density = 0 + for material_layer in material_layers: + material_mass_density = ifcopenshell.util.element.get_pset( + material_layer.Material, "Pset_MaterialCommon", "MassDensity" + ) + if material_mass_density is None: + return + densities.append(material_mass_density) + thickness = material_layer.LayerThickness + thicknesses.append(thickness) + obj_mass_density = obj_mass_density + (material_mass_density * thickness) + total_thickness = sum(thicknesses) + obj_mass_density = obj_mass_density / total_thickness + return obj_mass_density + + if material.is_a("IfcMaterialProfileSetUsage"): + material_profiles = material.ForProfileSet.MaterialProfiles + if len(material_profiles) == 1: + material_mass_density = ifcopenshell.util.element.get_pset( + material_profiles[0].Material, "Pset_MaterialCommon", "MassDensity" + ) + return material_mass_density + else: + return + + +def get_predefined_type(element: ifcopenshell.entity_instance) -> Union[str, None]: + """Retrieves the PrefefinedType attribute of an element. + + If the predefined type is user defined, the custom type (such as object + type, element type, or process type depending on the class) is returned + instead. Predefined types from the associated type element are also + considered first. + + :param element: The IFC Element entity + :return: The predefined type of the element + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + predefined_type = ifcopenshell.util.element.get_predefined_type(element) + """ + if element_type := get_type(element): + predefined_type = getattr(element_type, "PredefinedType", None) + if predefined_type == "USERDEFINED" or not predefined_type: + predefined_type = getattr(element_type, "ElementType", ...) + if predefined_type == ...: + predefined_type = getattr(element_type, "ProcessType", None) + if predefined_type and predefined_type != "NOTDEFINED": + return predefined_type + + predefined_type = getattr(element, "PredefinedType", None) + if predefined_type == "USERDEFINED" or not predefined_type: + predefined_type = getattr(element, "ObjectType", None) + return predefined_type + + +def is_userdefined_type(element: ifcopenshell.entity_instance) -> bool: + """Checks if the predefined type is userdefined + + :param element: The IFC Element entity + :return: True if userdefined + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + is_userdefined_type = ifcopenshell.util.element.is_userdefined_type(element) + """ + if element_type := get_type(element): + predefined_type = getattr(element_type, "PredefinedType", None) + if predefined_type == "USERDEFINED": + return True + elif not predefined_type: + predefined_type = getattr(element_type, "ElementType", ...) + if predefined_type == ...: + predefined_type = getattr(element_type, "ProcessType", None) + if predefined_type: + return True + if predefined_type and predefined_type != "NOTDEFINED": + return False + + predefined_type = getattr(element, "PredefinedType", None) + if predefined_type == "USERDEFINED": + return True + elif not predefined_type: + return bool(getattr(element, "ObjectType", None)) + return False + + +def get_type(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """Retrieves the construction type element of an element occurrence. + + Note: `get_type(type_element) == type_element`. + + :param element: The element occurrence (IfcObject) + :return: The related type element + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + element_type = ifcopenshell.util.element.get_type(element) + """ + if element.is_a("IfcTypeObject"): + return element + + schema = element.file.schema + if schema != "IFC2X3": + if is_typed_by := getattr(element, "IsTypedBy", ()): + return is_typed_by[0].RelatingType + return + + if is_defined_by := getattr(element, "IsDefinedBy", ()): # IFC2X3 + for relationship in is_defined_by: + if relationship.is_a("IfcRelDefinesByType"): + return relationship.RelatingType + + +def get_types(type: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """Get all the occurrences of a type element + + :param type: The type element + :return: A list of occurrences of that type + + Example: + + .. code:: python + + element_type = ifcopenshell.by_type("IfcWallType")[0] + walls = ifcopenshell.util.element.get_types(element_type) + """ + if type.file.schema == "IFC2X3": + if object_type_of := getattr(type, "ObjectTypeOf", ()): + return object_type_of[0].RelatedObjects + else: + if types := getattr(type, "Types", ()): + return types[0].RelatedObjects + return [] + + +def get_shape_aspects( + element: ifcopenshell.entity_instance, + should_inherit: bool = True, +) -> list[ifcopenshell.entity_instance]: + """Get element's shape aspects. + + :param element: IfcProduct or IfcTypeProduct. + :param should_inherit: If True, the shape aspects of the element's type will be considered. + Useful in cases when IfcShapeAspects are assigned to the type's IfcRepresentationMap + instead of the element's IfcProductDefinitionShape. + :return: The associated shape aspects of the element. + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + shape_aspect = ifcopenshell.util.element.get_shape_aspects(element) + """ + + # IfcProduct + if (representation := getattr(element, "Representation", ...)) != ...: + shape_aspects: list[ifcopenshell.entity_instance] = [] + if should_inherit and (element_type := get_type(element)): + shape_aspects.extend(get_shape_aspects(element_type)) + shape_aspects.extend(representation.HasShapeAspects) + return shape_aspects + + if element.file.schema == "IFC2X3": + return [] + + # IfcTypeProduct + shape_aspects = [] + for representation_map in element.RepresentationMaps or []: + shape_aspects += representation_map.HasShapeAspects + return shape_aspects + + +def get_material( + element: ifcopenshell.entity_instance, should_skip_usage=False, should_inherit=True +) -> Union[ifcopenshell.entity_instance, None]: + """Gets the material of the element + + The material may be a single material, material set (layered, profiled, or + constituent), or a material set usage. + + :param element: The element to get the material of. + :param should_skip_usage: If set to True, if the material is a material set + usage, the material set itself will be returned. Useful if you don't + care about occurrence usage parameters. If False, the usage will be + returned. + :param should_inherit: If True, any inherited materials from associated + types will be considered. + :return: The associated material of the element or `None`. + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + material = ifcopenshell.util.element.get_material(element) + """ + if (has_associations := getattr(element, "HasAssociations", None)) is not None and has_associations: + for relationship in has_associations: + if relationship.is_a("IfcRelAssociatesMaterial"): + if should_skip_usage: + relating_material = relationship.RelatingMaterial + if relating_material.is_a("IfcMaterialLayerSetUsage"): + return relating_material.ForLayerSet + elif relating_material.is_a("IfcMaterialProfileSetUsage"): + return relating_material.ForProfileSet + return relationship.RelatingMaterial + if should_inherit: + relating_type = get_type(element) + if relating_type != element and (has_associations := getattr(relating_type, "HasAssociations", None)): + return get_material(relating_type, should_skip_usage) + + +def get_materials( + element: ifcopenshell.entity_instance, should_inherit: bool = True +) -> list[ifcopenshell.entity_instance]: + """Gets individual materials of an element + + If the element has a material set, the individual materials of that set are + returned as a list. + + :param element: The element to get the materials of. + :param should_inherit: If True, any inherited materials from associated + types will be considered. + :return: The associated materials of the element. + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + materials = ifcopenshell.util.element.get_materials(element) + """ + material = get_material(element, should_skip_usage=True, should_inherit=should_inherit) + if not material: + return [] + elif material.is_a("IfcMaterial"): + return [material] + elif material.is_a("IfcMaterialLayerSet"): + return [l.Material for l in material.MaterialLayers] + elif material.is_a("IfcMaterialProfileSet"): + return [p.Material for p in material.MaterialProfiles] + elif material.is_a("IfcMaterialConstituentSet"): + return [c.Material for c in material.MaterialConstituents] + elif material.is_a("IfcMaterialList"): + return list(material.Materials) + else: + assert False, f"Unexpected material type: {material.is_a()}" + + +def get_styles(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """Retrieves the styles used in an element's representation. + + Styles may be retreived from the material or the body representation. + + :param element: The element to get the styles of. + :return: A list of surface styles + + Example: + + .. code:: python + + wall = file.by_type("IfcWall")[0] + styles = ifcopenshell.util.element.get_styles(wall) + """ + styles = [] + + materials = ifcopenshell.util.element.get_materials(element) + for material in materials: + for material_definition_representation in material.HasRepresentation or []: + for representation in material_definition_representation.Representations: + for item in representation.Items: + styles.extend([s for s in item.Styles if s.is_a("IfcSurfaceStyle")]) + + body = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW") + if not body: + return styles + + for representation in [body]: + queue = list(representation.Items) + while queue: + item = queue.pop() + if item.is_a("IfcMappedItem"): + queue.extend(item.MappingSource.MappedRepresentation.Items) + if item.is_a("IfcBooleanResult"): + queue.append(item.FirstOperand) + queue.append(item.SecondOperand) + if item.StyledByItem: + styles.extend([s for s in item.StyledByItem[0].Styles if s.is_a("IfcSurfaceStyle")]) + return styles + + +# TODO: ifc_file argument is unnecessary for some methods now +# since we have entity_instance.file, so we can deprecate it. +def get_elements_by_material( + ifc_file: Union[ifcopenshell.file, None], material: ifcopenshell.entity_instance +) -> set[ifcopenshell.entity_instance]: + """Retrieves the elements related to a material. + + This includes elements using the material as part of a material set or set + usage. + + :param ifc_file: The IFC file + :param material: The IFC Material entity + :return: A set of elements using the to the material + + Example: + + .. code:: python + + material = file.by_type("IfcMaterial")[0] + elements = ifcopenshell.util.element.get_elements_by_material(file, material) + """ + if not ifc_file: + ifc_file = material.file + results = set() + for inverse in ifc_file.get_inverse(material): + if inverse.is_a("IfcRelAssociatesMaterial"): + results.update(inverse.RelatedObjects or []) # See Revit bug #675 + elif inverse.is_a("IfcMaterialLayer"): + for material_set in inverse.ToMaterialLayerSet: + results.update(get_elements_by_material(ifc_file, material_set)) + elif inverse.is_a("IfcMaterialProfile"): + for material_set in inverse.ToMaterialProfileSet: + results.update(get_elements_by_material(ifc_file, material_set)) + elif inverse.is_a("IfcMaterialConstituent"): + for material_set in inverse.ToMaterialConstituentSet: + results.update(get_elements_by_material(ifc_file, material_set)) + elif inverse.is_a("IfcMaterialLayerSetUsage"): + results.update(get_elements_by_material(ifc_file, inverse)) + elif inverse.is_a("IfcMaterialProfileSetUsage"): + results.update(get_elements_by_material(ifc_file, inverse)) + elif inverse.is_a("IfcMaterialList"): + results.update(get_elements_by_material(ifc_file, inverse)) + return results + + +def get_elements_by_style( + ifc_file: Union[ifcopenshell.file, None], style: ifcopenshell.entity_instance +) -> set[ifcopenshell.entity_instance]: + """Retrieves the elements whose geometric representation uses a style + + :param ifc_file: The IFC file + :param style: The IfcPresentationStyle entity + :return: The elements related to the style + + Example: + + .. code:: python + + style = file.by_type("IfcSurfaceStyle")[0] + elements = ifcopenshell.util.element.get_elements_by_style(file, style) + """ + if not ifc_file: + ifc_file = style.file + results = set() + inverses = list(ifc_file.get_inverse(style)) + while inverses: + inverse = inverses.pop() + inverse_class = inverse.is_a() + # IfcPresentationStyleAssignment for < IFC4X3. + # IfcFillAreaStyleHatching->IfcFillAreaStyle only for IfcCurveStyle. + # IfcFillAreaStyleTiles->IfcFillAreaStyle is not restricted to IfcCurveStyle. + if inverse_class in ( + "IfcPresentationStyleAssignment", + "IfcFillAreaStyleHatching", + "IfcFillAreaStyle", + "IfcFillAreaStyleTiles", + ): + inverses.extend(ifc_file.get_inverse(inverse)) + continue + if not inverse.is_a("IfcStyledItem"): + continue + if geometry_item := inverse.Item: + for inverse_ in ifc_file.get_inverse(geometry_item): + if inverse_.is_a("IfcShapeRepresentation"): + results.update(get_elements_by_representation(ifc_file, inverse_)) + # IfcFillAreaStyleTiles requires .Item to be set. + inverses.extend(ifc_file.get_inverse(inverse)) + else: + styled_reps = [i for i in ifc_file.get_inverse(inverse) if i.is_a("IfcStyledRepresentation")] + for styled_rep in styled_reps: + for material_def_rep in styled_rep.OfProductRepresentation: + results.update(get_elements_by_material(ifc_file, material_def_rep.RepresentedMaterial)) + return results + + +def get_elements_by_representation( + ifc_file: Union[ifcopenshell.file, None], representation: ifcopenshell.entity_instance +) -> set[ifcopenshell.entity_instance]: + """Gets all elements using a geometric representation + + :param ifc_file: The IFC file + :param representation: The IfcShapeRepresentation representation + :return: The elements using the geometric representation + + Example: + + .. code:: python + + representation = file.by_type("IfcShapeRepresentation")[0] + elements = ifcopenshell.util.element.get_elements_by_representation(file, representation) + """ + if not ifc_file: + ifc_file = representation.file + results = set() + [results.update(pr.ShapeOfProduct) for pr in representation.OfProductRepresentation] + for rep_map in representation.RepresentationMap: + for inverse in ifc_file.get_inverse(rep_map): + if inverse.is_a("IfcTypeProduct"): + results.add(inverse) + elif inverse.is_a("IfcMappedItem"): + [ + results.update(get_elements_by_representation(ifc_file, rep)) + for rep in ifc_file.get_inverse(inverse) + if rep.is_a("IfcShapeRepresentation") + ] + return results + + +def get_elements_by_profile(profile: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + """Get all elements using provided IfcProfileDef. + + Skip elements that have the profile in IfcMaterialProfileSet + but not actually use it in their representations. + + :param profile: IfcProfileDef: + :return: The elements using the profile. + """ + ifc_file = profile.file + queue = ifc_file.get_inverse(profile) + processed: set[ifcopenshell.entity_instance] = set() + representations: set[ifcopenshell.entity_instance] = set() + while queue: + item = queue.pop() + if item.is_a("IfcRepresentationItem"): + queue.update(i for i in ifc_file.get_inverse(item) if i not in processed) + elif item.is_a("IfcShapeRepresentation"): + representations.add(item) + else: + pass + processed.add(item) + + elements = set() + for representation in representations: + elements.update(get_elements_by_representation(ifc_file, representation)) + return elements + + +def get_elements_by_layer( + ifc_file: Union[ifcopenshell.file, None], layer: ifcopenshell.entity_instance +) -> set[ifcopenshell.entity_instance]: + """Get all the elements that are used by a presentation layer + + :param ifc_file: The IFC file + :param layer: The IfcPresentationLayerAssignment layer + :return: The elements using the geometric representation + """ + if not ifc_file: + ifc_file = layer.file + results = set() + for item in layer.AssignedItems or []: + if item.is_a("IfcShapeRepresentation"): + results.update(get_elements_by_representation(ifc_file, item)) + elif item.is_a("IfcRepresentationItem"): + for inverse in ifc_file.get_inverse(item): + if inverse.is_a("IfcShapeRepresentation"): + results.update(get_elements_by_representation(ifc_file, inverse)) + return results + + +def get_layers( + ifc_file: Union[ifcopenshell.file, None], element: ifcopenshell.entity_instance +) -> list[ifcopenshell.entity_instance]: + """Get the CAD layers that an element is part of + + An element may have portions or all of its geometry assigned to a + traditional CAD presentation layer. + + :param ifc_file: The IFC file object + :param element: The IFC element to interrogate + :return: A list of IfcPresentationLayerAssignment + + Example: + + .. code:: python + + element = ifcopenshell.by_type("IfcWall")[0] + layers = ifcopenshell.util.element.get_layers(element) + """ + if not ifc_file: + ifc_file = element.file + layers = [] + representations = [] + if representation := getattr(element, "Representation", None): + representations = [representation] + elif representation_maps := getattr(element, "RepresentationMaps", None): + representations = representation_maps + for representation in representations: + for subelement in ifc_file.traverse(representation): + if subelement.is_a("IfcShapeRepresentation"): + layers.extend(subelement.LayerAssignments or []) + elif subelement.is_a("IfcGeometricRepresentationItem"): + if ifc_file.schema == "IFC2X3": + layers.extend(subelement.LayerAssignments or []) + else: + layers.extend(subelement.LayerAssignment or []) + return layers + + +def get_container( + element: ifcopenshell.entity_instance, should_get_direct: bool = False, ifc_class: Optional[str] = None +) -> Union[ifcopenshell.entity_instance, None]: + """ + Retrieves the spatial structure container of an element. + + :param element: The IFC element + :param should_get_direct: If True, a result is only returned if the element + is directly contained in a spatial structure element. If False, an + indirect spatial container may be returned, such as if an element is a + part of an aggregate, and then if that aggregate is contained in a + spatial structure element. + :param ifc_class: Optionally filter the type of container you're after. For + example, you may be after the storey, not a space. + :return: The direct or indirect container of the element or None. + + Example: + + .. code:: python + + element = file.by_type("IfcWall")[0] + container = ifcopenshell.util.element.get_container(element) + """ + if should_get_direct: + if ( + contained_in_structure := getattr(element, "ContainedInStructure", None) + ) is not None and contained_in_structure: + container = contained_in_structure[0].RelatingStructure + if not ifc_class: + return container + if container.is_a(ifc_class): + return container + elif contained_in_structure := getattr(element, "ContainedInStructure", None): + container = contained_in_structure[0].RelatingStructure + if not ifc_class: + return container + while container: + if container.is_a(ifc_class): + return container + container = get_aggregate(container) + elif parent := get_parent(element): + return get_container(parent, should_get_direct, ifc_class) + + +def get_referenced_structures(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """Retreives a list of referenced spatial elements + + Typically useful for multistorey elements, such as columns or facade + elements, or elements that span multiple spaces or in-between spaces, such + as stairs, doors, etc. + + :param element: The IFC element + :return: A list of IfcSpatialElement + + Example: + + .. code:: python + + element = file.by_type("IfcWall")[0] + print(ifcopenshell.util.element.get_referenced_structures(element)) + """ + return [r.RelatingStructure for r in getattr(element, "ReferencedInStructures", [])] + + +def get_structure_referenced_elements(structure: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + """Retreives a set of elements referenced by a structure + + :param structure: IfcSpatialElement + :return: A set of referenced elements, IfcSpatialReferenceSelect + + Example: + + .. code:: python + + element = file.by_type("IfcBuildingStorey")[0] + print(ifcopenshell.util.element.get_structure_referenced_elements(element)) + """ + referenced = set() + for rel in structure.ReferencesElements: + referenced.update(rel.RelatedElements) + return referenced + + +def get_decomposition(element: ifcopenshell.entity_instance, is_recursive=True) -> set[ifcopenshell.entity_instance]: + """ + Retrieves all subelements of an element based on the spatial decomposition + hierarchy. This includes all subspaces and elements contained in subspaces, + parts of an aggregate, all openings, and all fills of any openings. + + :param element: The IFC element + :return: The decomposition of the element + + Example: + + .. code:: python + + element = file.by_type("IfcProject")[0] + decomposition = ifcopenshell.util.element.get_decomposition(element) + """ + queue = [element] + results = set() + while queue: + element = queue.pop() + for rel in getattr(element, "ContainsElements", []): + related = rel.RelatedElements + queue.extend(related) + results.update(related) + for rel in getattr(element, "IsDecomposedBy", []): + related = rel.RelatedObjects + queue.extend(related) + results.update(related) + for rel in getattr(element, "HasOpenings", []): + related = rel.RelatedOpeningElement + queue.append(related) + results.add(related) + for rel in getattr(element, "HasFillings", []): + related = rel.RelatedBuildingElement + queue.append(related) + results.add(related) + for rel in getattr(element, "IsNestedBy", []): + related = rel.RelatedObjects + queue.extend(related) + results.update(related) + if not is_recursive: + break + return results + + +def get_grouped_by( + element: ifcopenshell.entity_instance, is_recursive: bool = True +) -> list[ifcopenshell.entity_instance]: + """Retrieves all subelements of an element based on the group. + + :param element: IfcGroup entity + :return: All subelements of the group + + Example: + + .. code:: python + + element = file.by_type("IfcGroup")[0] + subelements = ifcopenshell.util.element.get_grouped_by(element) + """ + queue = [element] + results = [] + while queue: + element = queue.pop() + for rel in getattr(element, "IsGroupedBy", []): + related_objects = rel.RelatedObjects + queue.extend(related_objects) + results.extend(related_objects) + if not is_recursive: + break + return results + + +def get_groups(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the groups of an element. + + :param element: The IFC element + :return: List of IfcGroups element is assigned to. + + Example: + + .. code:: python + + wall = file.by_type("IfcWall")[0] + group = ifcopenshell.util.element.get_groups(element)[0] + """ + groups = [] + for rel in element.HasAssignments: + if rel.is_a("IfcRelAssignsToGroup"): + groups.append(rel.RelatingGroup) + return groups + + +def get_controls(element: ifcopenshell.entity_instance) -> Generator[ifcopenshell.entity_instance]: + """ + Retrieves the controls of an element. + + :param element: The IFC element + :return: Generator of IfcControl elements assigned to the element. + + Example: + + .. code:: python + + task = file.by_type("IfcTask")[0] + control = ifcopenshell.util.element.get_controls(task)[0] + """ + for rel in element.HasAssignments: + if rel.is_a("IfcRelAssignsToControl"): + yield rel.RelatingControl + + +def get_parent(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """Get the parent in the spatial heirarchy + + IFC features a spatial hierarchy tree of all objects. Each spatial element + or physical element must be located inside this hierarchy exactly once. + + The top level parent of this tree is the IfcProject, which has no parent. + + All children may have parent-child relationships of one of the following types: + + - Spatial containment: a physical object is located in a space + - Aggregation: a physical object is broken up into parts, or a spatial location is split into sub locations + - Nesting: components are attached to a host parent + - Filling: the physical element fills an opening, such as a window filling a hole + - Voiding: the opening voids another physical element, such as a hole in a wall + + :param element: Any physical or spatial element in the tree + :return: Its parent. This must exist for any valid file, or None if we've reached the IfcProject. + + Example: + + .. code:: python + + element = file.by_type("IfcWall")[0] + parent = ifcopenshell.util.element.get_parent(element) + """ + return ( + get_container(element, should_get_direct=True) + or get_aggregate(element) + or get_nest(element) + or get_filled_void(element) + or get_voided_element(element) + ) + + +def get_filled_void(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """If the element is filling a void, get the void + + Examples include windows and doors which fill a opening inside a wall. + + :param element: The building element, typically a window or door + :return: The IfcOpeningElement that it is filling + + Example: + + .. code:: python + + window = file.by_type("IfcWindow")[0] + opening = ifcopenshell.util.element.get_filled_void(window) + """ + if rel := getattr(element, "FillsVoids", None): + return rel[0].RelatingOpeningElement + + +def get_voided_element(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """For an opening, get the building element that the opening is voiding + + For all valid models, this should never return None. + + :param element: The IfcOpeningElement + :return: The building element, such as a wall or slab + + Example: + + .. code:: python + + opening = file.by_type("IfcOpeningElement")[0] + element = ifcopenshell.util.element.get_voided_element(opening) + """ + if rel := getattr(element, "VoidsElements", None): + return rel[0].RelatingBuildingElement + + +def get_aggregate(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """ + Retrieves the aggregate parent of an element. + + :param element: The IFC element + :return: The aggregate of the element + + Example: + + .. code:: python + + element = file.by_type("IfcBeam")[0] + aggregate = ifcopenshell.util.element.get_aggregate(element) + """ + if not (decomposes := getattr(element, "Decomposes", None)): + return + is_ifc2x3 = element.file.schema == "IFC2X3" + rel: ifcopenshell.entity_instance = decomposes[0] + if is_ifc2x3 and not rel.is_a("IfcRelAggregates"): + # In IFCF2X3 Decomposes is used for both aggregates and nests, + # but only for 1 at the time. + return + return rel.RelatingObject + + +def get_nest(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + """ + Retrieves the nest parent of an element. + + :param element: The IFC element + :return: The nested whole of the element + + Example: + + .. code:: python + + element = file.by_type("IfcBeam")[0] + aggregate = ifcopenshell.util.element.get_nest(element) + """ + is_ifc2x3 = element.file.schema == "IFC2X3" + if is_ifc2x3: + if not (decomposes := getattr(element, "Decomposes", None)): + return + if decomposes[0].is_a("IfcRelNests"): + return decomposes[0].RelatingObject + else: + if nests := getattr(element, "Nests", None): + return nests[0].RelatingObject + + +def get_parts(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the parts of an element that have an aggregation relationship. + + :param element: The IFC element + :return: The parts of the element + + Example: + + .. code:: python + + element = file.by_type("IfcElementAssembly")[0] + parts = ifcopenshell.util.element.get_parts(element) + """ + objects: list[ifcopenshell.entity_instance] = [] + is_not_ifc2x3 = element.file.schema != "IFC2X3" + if is_decomposed_by := getattr(element, "IsDecomposedBy", ()): + for rel in is_decomposed_by: + if is_not_ifc2x3 or rel.is_a("IfcRelAggregates"): + objects.extend(rel.RelatedObjects) + return objects + + +def get_contained(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the contained elements of spatial element. + + :param element: The IFC element + :return: The parts of the element + + Example: + + .. code:: python + + element = file.by_type("IfcBuildingStorey")[0] + elements = ifcopenshell.util.element.get_contained(element) + """ + objects: list[ifcopenshell.entity_instance] = [] + if contains_elements := getattr(element, "ContainsElements", ()): + for rel in contains_elements: + objects.extend(rel.RelatedElements) + return objects + + +def get_components( + element: ifcopenshell.entity_instance, include_ports: bool = False +) -> list[ifcopenshell.entity_instance]: + """ + Retrieves the components of an element that have an nest relationship. + + For nested ports, see ifcopenshell.util.system. + + :param element: The IFC element + :param include_ports: Default as False. Set to true if you also want to get ports. + :return: The components of the element + + Example: + + .. code:: python + + element = file.by_type("IfcElementAssembly")[0] + components = ifcopenshell.util.element.get_components(element) + """ + objects: list[ifcopenshell.entity_instance] = [] + is_ifc2x3 = element.file.schema == "IFC2X3" + if is_ifc2x3: + if is_decomposed_by := getattr(element, "IsDecomposedBy", ()): + for rel in is_decomposed_by: + if rel.is_a("IfcRelNests"): + objects.extend(rel.RelatedObjects) + else: + if is_nested_by := getattr(element, "IsNestedBy", None): + for rel in is_nested_by: + objects.extend(rel.RelatedObjects) + if include_ports: + return objects + return [e for e in objects if not e.is_a("IfcPort")] + + +ReferenceData = namedtuple("ReferenceData", "inverse_attribute, rel_class, relating_element_attribute") + +# References below are omitted because they do not introduce +# any additional referenced objects besides the objects +# from their supertype IfcExternalReference +# - IfcExternallyDefinedHatchStyle +# - IfcExternallyDefinedSurfaceStyle +# - IfcExternallyDefinedTextFont + +REFERENCE_TYPES: dict[str, ReferenceData] = { + "IfcClassificationReference": ReferenceData( + "ClassificationRefForObjects", + "IfcRelAssociatesClassification", + "RelatingClassification", + ), + "IfcDocumentReference": ReferenceData("DocumentRefForObjects", "IfcRelAssociatesDocument", "RelatingDocument"), + "IfcLibraryReference": ReferenceData("LibraryRefForObjects", "IfcRelAssociatesLibrary", "RelatingLibrary"), + "IfcClassification": ReferenceData( + "ClassificationForObjects", "IfcRelAssociatesClassification", "RelatingClassification" + ), + "IfcDocumentInformation": ReferenceData("DocumentInfoForObjects", "IfcRelAssociatesDocument", "RelatingDocument"), + "IfcLibraryInformation": ReferenceData("LibraryInfoForObjects", "IfcRelAssociatesLibrary", "RelatingLibrary"), +} + + +def get_referenced_elements(reference: ifcopenshell.entity_instance) -> set[ifcopenshell.entity_instance]: + """Get all elements with assigned `reference` + + :param reference: IfcExternalReference/IfcExternalInformation subtype reference + :return: The elements with assigned `reference` + + Example: + + .. code:: python + + reference = file.by_type("IfcClassificationReference")[0] + elements = ifcopenshell.util.element.get_referenced_elements(reference) + """ + + related_objects: set[ifcopenshell.entity_instance] = set() + ifc_file = reference.file + ifc_class = reference.is_a() + + if ifc_file.schema == "IFC2X3": + reference_data = REFERENCE_TYPES.get(ifc_class) + if reference_data: + for rel in ifc_file.by_type(reference_data.rel_class): + if getattr(rel, reference_data.relating_element_attribute) == reference: + related_objects.update(rel.RelatedObjects) + + else: + if reference.is_a("IfcExternalReference"): + # IfcExternalReference + for external_rel in reference.ExternalReferenceForResources: + related_objects.update(external_rel.RelatedResourceObjects) + + reference_data = REFERENCE_TYPES.get(ifc_class) + if reference_data: + for rel in getattr(reference, reference_data.inverse_attribute): + related_objects.update(rel.RelatedObjects) + + return related_objects + + +def replace_element(element: ifcopenshell.entity_instance, replacement: ifcopenshell.entity_instance) -> None: + for inverse in element.file.get_inverse(element): + replace_attribute(inverse, element, replacement) + + +def replace_attribute(element: ifcopenshell.entity_instance, old: Any, new: Any) -> None: + for i, attribute_value in enumerate(element): + if has_element_reference(attribute_value, old): + element[i] = element.walk(lambda v: v == old, lambda v: new, attribute_value) + + +def has_element_reference(value: Any, element: ifcopenshell.entity_instance) -> bool: + if isinstance(value, (tuple, list)): + for v in value: + if has_element_reference(v, element): + return True + return False + return value == element + + +def remove_deep(ifc_file: Union[ifcopenshell.file, None], element: ifcopenshell.entity_instance) -> None: + """Recursively purges a subgraph safely. + + Do not use, use remove_deep2() instead. + """ + # @todo maybe some sort of try-finally mechanism. + if not ifc_file: + ifc_file = element.file + ifc_file.batch() + subgraph = list(ifc_file.traverse(element, breadth_first=True)) + subgraph_set = set(subgraph) + for ref in subgraph[::-1]: + if ref.id() and len(set(ifc_file.get_inverse(ref)) - subgraph_set) == 0: + ifc_file.remove(ref) + ifc_file.unbatch() + + +def batch_remove_deep2(ifc_file: ifcopenshell.file) -> None: + """Enable batch removal after running remove_deep2 using serialisation + + See #944 and #3226. Removing elements in an IFC graph is slow as a lot of + mappings need to be edited. In larger models (>100MB) and when removing + many elements (>10000), it is faster to serialise the IFC, remove elements + using string replacement, and then reload the modified serialised IFC. + + The trade-off is that extra memory will be used, and string replacement + only works with remove_deep2 where the removed elements have no inverses. + In addition, transaction history will be lost, and any scripts using this + method will have to refetch elements from the reloaded IFC and cannot rely + on existing variables in memory. + + :param ifc_file: The IFC file object + + Example: + + .. code:: python + + element1 = model.by_id(123) + element2 = model.by_id(456) + + ifcopenshell.util.element.batch_remove_deep2(model) + ifcopenshell.util.element.remove_deep2(model, element2) + + # Notice how we reload the model. + model = ifcopenshell.util.element.unbatch_remove_deep2(model) + + print(element1) # Don't call element1! + """ + ifc_file.to_delete = set() + + +def unbatch_remove_deep2(ifc_file: ifcopenshell.file) -> ifcopenshell.file: + """Finish removing elements batched from remove_deep2 using string replacement + + See documentation for batch_remove_deep2. + + :param ifc_file: The IFC file object + :return: A newly loaded file with the elements removed. + """ + assert ifc_file.to_delete is not None + ifc_string = ifc_file.to_string() + lines = iter(ifc_string.split("\n")) + ids_to_delete = iter(sorted([e.id() for e in ifc_file.to_delete])) + id_to_delete = next(ids_to_delete, None) + result: list[str] = [] + + for line in lines: + if id_to_delete is None: + result.append(line) + continue + + if line.startswith(f"#{id_to_delete}="): + id_to_delete = next(ids_to_delete, None) + else: + result.append(line) + + ifc_file.to_delete = None + return ifcopenshell.file.from_string("\n".join(result)) + + +def remove_deep2( + ifc_file: Union[ifcopenshell.file, None], + element: ifcopenshell.entity_instance, + also_consider: list[ifcopenshell.entity_instance] = [], + do_not_delete: set[ifcopenshell.entity_instance] = set(), +) -> None: + """Recursively purges a subgraph safely, starting at an element + + This should always be used instead of remove_deep. See #1812. The start + element must have no inverses. The subgraph to be purged is calculated using + all forward relationships determined by the traverse() function. + + The deletion process starts at element and traverses forward through the + subgraph. Each subelement is checked for any inverses outside the subgraph. + If there are no inverses outside, it may be safely purged. If there are + inverses that aren't part of this subgraph, that subelement, and all of its + subelements (i.e. that entire branch of subelements) will not be deleted as + it is used elsewhere. + + For simple subgraphs, traverse() is sufficient to fully represent all + related subelements. When it isn't, the ``also_consider`` argument may be + used. These are typically inverses futher down the subelement chain. + + Note that remove_deep2 will _not_ remove elements in also_consider. Instead, + it is only used as a consideration for whether or not an element has all + inverses fully contained in the subgraph. + + The do_not_delete argument contains all elements that may be part of the + subgraph but are protected from deletion. + + :param ifc_file: The IFC file object + :param also_consider: elements to also consider as a part of a subgraph + Order could matter for perfomance - elements that reference `element` + directly should go first for the better performance. + :param do_not_delete: elements to protect from deletion + :param element: The starting element that defines the subgraph + """ + # ifc_file.batch() + if not ifc_file: + ifc_file = element.file + total_inverses = ifc_file.get_total_inverses(element) + if total_inverses > 0: + + def are_inverses_contained() -> bool: + also_considered_inverses = 0 + + for considered_element in also_consider: + traverse = ifc_file.traverse(considered_element, max_levels=1) + if element in traverse: + also_considered_inverses += 1 + if total_inverses == also_considered_inverses: + return True + return False + + if not are_inverses_contained(): + return + + to_delete: set[ifcopenshell.entity_instance] = set() + subgraph = list(ifc_file.traverse(element, breadth_first=True)) + subgraph.extend(also_consider) + subgraph_set = set(subgraph) + subelement_queue = [element] + + # Cache already processed entities to avoid traversing them multiple time. + # E.g. lots of IFCINDEXEDPOLYCURVES may reference the same IFCCARTESIANPOINTLIST2D. + processed_ids: set[int] = set() + + while subelement_queue: + subelement = subelement_queue.pop(0) + subelement_id = subelement.id() + if ( + subelement_id + and subelement_id not in processed_ids + and subelement not in do_not_delete + and ( + # 0 or 1 inverses guarantees that the subelement only exists in this subgraph + ifc_file.get_total_inverses(subelement) < 2 + # Alternatively, let's ensure all inverses are within the subgraph + or len(set(ifc_file.get_inverse(subelement)) - subgraph_set) == 0 + ) + ): + to_delete.add(subelement) + subelement_queue.extend(ifc_file.traverse(subelement, max_levels=1)[1:]) + # See #3052. IfcOpenShell is extremely slow in removing elements if + # the element has an inverse, and that inverse references that + # element in a big list. The most common example is an + # IfcPolygonalFaceSet with a Faces attribute of tens of thousands + # of IfcIndexedPolygonalFace. In this situation, removing a + # IfcIndexedPolygonalFace will take very, very long. If we are + # going to delete an element (i.e. added to the to_delete set), we + # clear any large lists (10 is an arbitrary threshold) to prevent + # this issue. + for i, attribute in enumerate(subelement): + if isinstance(attribute, tuple) and len(attribute) > 10: + subelement[i] = [] + processed_ids.add(subelement_id) + + if ifc_file.to_delete is not None: + ifc_file.to_delete.update(to_delete) + return + + # We delete elements from subgraph in reverse order to allow batching to work + for subelement in filter(lambda e: e in to_delete, subgraph[::-1]): + ifc_file.remove(subelement) + # ifc_file.unbatch() + + +def copy( + ifc_file: Union[ifcopenshell.file, None], element: ifcopenshell.entity_instance +) -> ifcopenshell.entity_instance: + """ + Copy a single element. Any referenced elements are not copied. + + GlobalIds are regenerated. + + :param ifc_file: The IFC file object + :param element: The IFC element to copy + :return: The newly copied element + """ + if not ifc_file: + ifc_file = element.file + new = ifc_file.create_entity(element.is_a()) + for i, attribute in enumerate(element): + if attribute is None: + continue + if new.attribute_name(i) == "GlobalId": + new[i] = ifcopenshell.guid.new() + else: + new[i] = attribute + return new + + +def copy_deep( + ifc_file: Union[ifcopenshell.file, None], + element: ifcopenshell.entity_instance, + exclude: Optional[Sequence[str]] = None, + exclude_callback: Optional[Callable[[ifcopenshell.entity_instance], bool]] = None, + copied_entities: Optional[dict[int, ifcopenshell.entity_instance]] = None, +) -> ifcopenshell.entity_instance: + """ + Recursively copy an element and all of its directly related subelements. + + GlobalIds are regenerated. + + :param ifc_file: The IFC file object + :param element: The IFC element to copy + :param exclude: An optional list of strings of IFC class names to not copy. + If any of the subelement is this class, it will not be copied and the + original instance will be referenced. + :param exclude_callback: A callback to determine whether or not to exclude + an entity or not. Returns True to exclude and False to exclude. + :param copied_entities: A dictionary of IDs as keys and entities as values + to reuse when coming across the same entity twice. This can typically + be left as None. + :return: The newly copied element + """ + if not ifc_file: + ifc_file = element.file + if copied_entities is None: + copied_entities = {} + else: + copied_entity = copied_entities.get(element.id(), None) + if copied_entity: + return copied_entity + new = ifc_file.create_entity(element.is_a()) + if element.id(): + copied_entities[element.id()] = new + for i, attribute in enumerate(element): + if attribute is None: + continue + if isinstance(attribute, ifcopenshell.entity_instance): + if exclude and any([attribute.is_a(e) for e in exclude]): + pass + elif exclude_callback and exclude_callback(attribute): + pass + else: + attribute = copy_deep( + ifc_file, + attribute, + exclude=exclude, + copied_entities=copied_entities, + exclude_callback=exclude_callback, + ) + elif isinstance(attribute, tuple) and attribute and isinstance(attribute[0], ifcopenshell.entity_instance): + if exclude and any([attribute[0].is_a(e) for e in exclude]): + pass + elif exclude_callback and exclude_callback(attribute[0]): + pass + else: + attribute = list(attribute) + for j, item in enumerate(attribute): + attribute[j] = copy_deep( + ifc_file, + item, + exclude=exclude, + exclude_callback=exclude_callback, + copied_entities=copied_entities, + ) + if new.attribute_name(i) == "GlobalId": + new[i] = ifcopenshell.guid.new() + else: + new[i] = attribute + return new + + +def has_property(product: ifcopenshell.entity_instance, property_name: str) -> bool: + """ + Check if a product has a property with a given name. + + :param product: The IFC product + :param property_name: The property name + :return: True if the product has the property, False otherwise + + Example: + + .. code:: python + + product = file.by_type("IfcWall")[0] + has_property = ifcopenshell.util.element.has_property(product, "NetArea") + """ + if not property_name: + return True + qtos = get_psets(product, qtos_only=True) + return any(property_name in quantities.keys() for quantities in qtos.values()) + + +def get_openings(element: ifcopenshell.entity_instance) -> Generator[ifcopenshell.entity_instance, None, None]: + """Get element openings as IfcRelVoidsElements. + + Use `.RelatedOpeningElement` to get the opening element. + + :param element: IfcElement. + :return: Generator of IfcRelVoidsElements. + """ + for element_rel in getattr(element, "HasOpenings", ()): + yield element_rel + + if aggregate := get_aggregate(element): + yield from get_openings(aggregate) + + +def has_openings(element: ifcopenshell.entity_instance) -> bool: + """Check if the element has openings. + + :param element: IfcElement. + :return: True if element has openings. + """ + return bool(next(get_openings(element), False)) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_2x3.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_2x3.json new file mode 100644 index 0000000000000000000000000000000000000000..85fd88ca9b599bc6fa36915c1a63b6202e0ef8fb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_2x3.json @@ -0,0 +1,424 @@ +{ + "IfcBeam": [ + "IfcBeamType" + ], + "IfcBuilding": [ + "IfcSpaceType" + ], + "IfcBuildingElement": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcBuildingElementComponent": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcBuildingElementPart": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcBuildingElementProxy": [ + "IfcBuildingElementProxyType" + ], + "IfcBuildingStorey": [ + "IfcSpaceType" + ], + "IfcChamferEdgeFeature": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcColumn": [ + "IfcColumnType" + ], + "IfcCovering": [ + "IfcCoveringType" + ], + "IfcCurtainWall": [ + "IfcCurtainWallType" + ], + "IfcDiscreteAccessory": [ + "IfcDiscreteAccessoryType", + "IfcVibrationIsolatorType" + ], + "IfcDistributionChamberElement": [ + "IfcDistributionChamberElementType" + ], + "IfcDistributionControlElement": [ + "IfcActuatorType", + "IfcAlarmType", + "IfcControllerType", + "IfcFlowInstrumentType", + "IfcSensorType" + ], + "IfcDistributionElement": [ + "IfcDistributionElementType" + ], + "IfcDistributionFlowElement": [ + "IfcDistributionChamberElementType" + ], + "IfcDoor": [ + "IfcDoorStyle" + ], + "IfcEdgeFeature": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcElectricDistributionPoint": [ + "IfcAirTerminalBoxType", + "IfcDamperType", + "IfcElectricTimeControlType", + "IfcFlowMeterType", + "IfcProtectiveDeviceType", + "IfcSwitchingDeviceType", + "IfcValveType" + ], + "IfcElectricalElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcElementAssembly": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcElementComponent": [ + "IfcDiscreteAccessoryType", + "IfcFastenerType" + ], + "IfcEnergyConversionDevice": [ + "IfcAirToAirHeatRecoveryType", + "IfcBoilerType", + "IfcChillerType", + "IfcCoilType", + "IfcCondenserType", + "IfcCooledBeamType", + "IfcCoolingTowerType", + "IfcElectricGeneratorType", + "IfcElectricMotorType", + "IfcEvaporativeCoolerType", + "IfcEvaporatorType", + "IfcHeatExchangerType", + "IfcHumidifierType", + "IfcMotorConnectionType", + "IfcSpaceHeaterType", + "IfcTransformerType", + "IfcTubeBundleType", + "IfcUnitaryEquipmentType" + ], + "IfcEquipmentElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcFastener": [ + "IfcFastenerType", + "IfcMechanicalFastenerType" + ], + "IfcFeatureElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcFeatureElementAddition": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcFeatureElementSubtraction": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcFlowController": [ + "IfcAirTerminalBoxType", + "IfcDamperType", + "IfcElectricTimeControlType", + "IfcFlowMeterType", + "IfcProtectiveDeviceType", + "IfcSwitchingDeviceType", + "IfcValveType" + ], + "IfcFlowFitting": [ + "IfcCableCarrierFittingType", + "IfcDuctFittingType", + "IfcJunctionBoxType", + "IfcPipeFittingType" + ], + "IfcFlowMovingDevice": [ + "IfcCompressorType", + "IfcFanType", + "IfcPumpType" + ], + "IfcFlowSegment": [ + "IfcCableCarrierSegmentType", + "IfcCableSegmentType", + "IfcDuctSegmentType", + "IfcPipeSegmentType" + ], + "IfcFlowStorageDevice": [ + "IfcElectricFlowStorageDeviceType", + "IfcTankType" + ], + "IfcFlowTerminal": [ + "IfcAirTerminalType", + "IfcElectricApplianceType", + "IfcElectricHeaterType", + "IfcFireSuppressionTerminalType", + "IfcGasTerminalType", + "IfcLampType", + "IfcLightFixtureType", + "IfcOutletType", + "IfcSanitaryTerminalType", + "IfcStackTerminalType", + "IfcWasteTerminalType" + ], + "IfcFlowTreatmentDevice": [ + "IfcDuctSilencerType", + "IfcFilterType" + ], + "IfcFooting": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcFurnishingElement": [ + "IfcFurnishingElementType", + "IfcFurnitureType", + "IfcSystemFurnitureElementType" + ], + "IfcMechanicalFastener": [ + "IfcMechanicalFastenerType" + ], + "IfcMember": [ + "IfcMemberType" + ], + "IfcOpeningElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcPile": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcPlate": [ + "IfcPlateType" + ], + "IfcProjectionElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcRailing": [ + "IfcRailingType" + ], + "IfcRamp": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcRampFlight": [ + "IfcRampFlightType" + ], + "IfcReinforcingBar": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcReinforcingElement": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcReinforcingMesh": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcRoof": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcRoundedEdgeFeature": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcSite": [ + "IfcSpaceType" + ], + "IfcSlab": [ + "IfcSlabType" + ], + "IfcSpace": [ + "IfcSpaceType" + ], + "IfcSpatialStructureElement": [ + "IfcSpaceType" + ], + "IfcStair": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcStairFlight": [ + "IfcStairFlightType" + ], + "IfcTendon": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcTendonAnchor": [ + "IfcBeamType", + "IfcBuildingElementProxyType", + "IfcColumnType", + "IfcCoveringType", + "IfcCurtainWallType", + "IfcMemberType", + "IfcPlateType", + "IfcRailingType", + "IfcRampFlightType", + "IfcSlabType", + "IfcStairFlightType", + "IfcWallType" + ], + "IfcTransportElement": [ + "IfcTransportElementType" + ], + "IfcVirtualElement": [ + "IfcDistributionElementType", + "IfcFurnishingElementType", + "IfcTransportElementType" + ], + "IfcWall": [ + "IfcWallType" + ], + "IfcWallStandardCase": [ + "IfcWallType" + ], + "IfcWindow": [ + "IfcWindowStyle" + ] +} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4.json new file mode 100644 index 0000000000000000000000000000000000000000..4e47c2934d9135172c6db595c0d9da35df42ef03 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4.json @@ -0,0 +1,384 @@ +{ + "IfcActuator": [ + "IfcActuatorType" + ], + "IfcAirTerminal": [ + "IfcAirTerminalType" + ], + "IfcAirTerminalBox": [ + "IfcAirTerminalBoxType" + ], + "IfcAirToAirHeatRecovery": [ + "IfcAirToAirHeatRecoveryType" + ], + "IfcAlarm": [ + "IfcAlarmType" + ], + "IfcAudioVisualAppliance": [ + "IfcAudioVisualApplianceType" + ], + "IfcBeam": [ + "IfcBeamType" + ], + "IfcBeamStandardCase": [ + "IfcBeamType" + ], + "IfcBoiler": [ + "IfcBoilerType" + ], + "IfcBuildingElementPart": [ + "IfcBuildingElementPartType" + ], + "IfcBuildingElementProxy": [ + "IfcBuildingElementProxyType" + ], + "IfcBurner": [ + "IfcBurnerType" + ], + "IfcCableCarrierFitting": [ + "IfcCableCarrierFittingType" + ], + "IfcCableCarrierSegment": [ + "IfcCableCarrierSegmentType" + ], + "IfcCableFitting": [ + "IfcCableFittingType" + ], + "IfcCableSegment": [ + "IfcCableSegmentType" + ], + "IfcChiller": [ + "IfcChillerType" + ], + "IfcChimney": [ + "IfcChimneyType" + ], + "IfcCivilElement": [ + "IfcCivilElementType" + ], + "IfcCoil": [ + "IfcCoilType" + ], + "IfcColumn": [ + "IfcColumnType" + ], + "IfcColumnStandardCase": [ + "IfcColumnType" + ], + "IfcCommunicationsAppliance": [ + "IfcCommunicationsApplianceType" + ], + "IfcCompressor": [ + "IfcCompressorType" + ], + "IfcCondenser": [ + "IfcCondenserType" + ], + "IfcController": [ + "IfcControllerType" + ], + "IfcCooledBeam": [ + "IfcCooledBeamType" + ], + "IfcCoolingTower": [ + "IfcCoolingTowerType" + ], + "IfcCovering": [ + "IfcCoveringType" + ], + "IfcCurtainWall": [ + "IfcCurtainWallType" + ], + "IfcDamper": [ + "IfcDamperType" + ], + "IfcDiscreteAccessory": [ + "IfcDiscreteAccessoryType" + ], + "IfcDistributionChamberElement": [ + "IfcDistributionChamberElementType" + ], + "IfcDistributionControlElement": [ + "IfcDistributionElementType" + ], + "IfcDistributionElement": [ + "IfcDistributionElementType" + ], + "IfcDistributionFlowElement": [ + "IfcDistributionElementType" + ], + "IfcDoor": [ + "IfcDoorType", + "IfcDoorStyle" + ], + "IfcDoorStandardCase": [ + "IfcDoorType", + "IfcDoorStyle" + ], + "IfcDuctFitting": [ + "IfcDuctFittingType" + ], + "IfcDuctSegment": [ + "IfcDuctSegmentType" + ], + "IfcDuctSilencer": [ + "IfcDuctSilencerType" + ], + "IfcElectricAppliance": [ + "IfcElectricApplianceType" + ], + "IfcElectricDistributionBoard": [ + "IfcElectricDistributionBoardType" + ], + "IfcElectricFlowStorageDevice": [ + "IfcElectricFlowStorageDeviceType" + ], + "IfcElectricGenerator": [ + "IfcElectricGeneratorType" + ], + "IfcElectricMotor": [ + "IfcElectricMotorType" + ], + "IfcElectricTimeControl": [ + "IfcElectricTimeControlType" + ], + "IfcElementAssembly": [ + "IfcElementAssemblyType" + ], + "IfcEnergyConversionDevice": [ + "IfcDistributionElementType" + ], + "IfcEngine": [ + "IfcEngineType" + ], + "IfcEvaporativeCooler": [ + "IfcEvaporativeCoolerType" + ], + "IfcEvaporator": [ + "IfcEvaporatorType" + ], + "IfcFan": [ + "IfcFanType" + ], + "IfcFastener": [ + "IfcFastenerType" + ], + "IfcFilter": [ + "IfcFilterType" + ], + "IfcFireSuppressionTerminal": [ + "IfcFireSuppressionTerminalType" + ], + "IfcFlowController": [ + "IfcDistributionElementType" + ], + "IfcFlowFitting": [ + "IfcDistributionElementType" + ], + "IfcFlowInstrument": [ + "IfcFlowInstrumentType" + ], + "IfcFlowMeter": [ + "IfcFlowMeterType" + ], + "IfcFlowMovingDevice": [ + "IfcDistributionElementType" + ], + "IfcFlowSegment": [ + "IfcDistributionElementType" + ], + "IfcFlowStorageDevice": [ + "IfcDistributionElementType" + ], + "IfcFlowTerminal": [ + "IfcDistributionElementType" + ], + "IfcFlowTreatmentDevice": [ + "IfcDistributionElementType" + ], + "IfcFooting": [ + "IfcFootingType" + ], + "IfcFurnishingElement": [ + "IfcFurnishingElementType" + ], + "IfcFurniture": [ + "IfcFurnitureType" + ], + "IfcGeographicElement": [ + "IfcGeographicElementType" + ], + "IfcHeatExchanger": [ + "IfcHeatExchangerType" + ], + "IfcHumidifier": [ + "IfcHumidifierType" + ], + "IfcInterceptor": [ + "IfcInterceptorType" + ], + "IfcJunctionBox": [ + "IfcJunctionBoxType" + ], + "IfcLamp": [ + "IfcLampType" + ], + "IfcLightFixture": [ + "IfcLightFixtureType" + ], + "IfcMechanicalFastener": [ + "IfcMechanicalFastenerType" + ], + "IfcMedicalDevice": [ + "IfcMedicalDeviceType" + ], + "IfcMember": [ + "IfcMemberType" + ], + "IfcMemberStandardCase": [ + "IfcMemberType" + ], + "IfcMotorConnection": [ + "IfcMotorConnectionType" + ], + "IfcOutlet": [ + "IfcOutletType" + ], + "IfcPile": [ + "IfcPileType" + ], + "IfcPipeFitting": [ + "IfcPipeFittingType" + ], + "IfcPipeSegment": [ + "IfcPipeSegmentType" + ], + "IfcPlate": [ + "IfcPlateType" + ], + "IfcPlateStandardCase": [ + "IfcPlateType" + ], + "IfcProtectiveDevice": [ + "IfcProtectiveDeviceType" + ], + "IfcProtectiveDeviceTrippingUnit": [ + "IfcProtectiveDeviceTrippingUnitType" + ], + "IfcPump": [ + "IfcPumpType" + ], + "IfcRailing": [ + "IfcRailingType" + ], + "IfcRamp": [ + "IfcRampType" + ], + "IfcRampFlight": [ + "IfcRampFlightType" + ], + "IfcReinforcingBar": [ + "IfcReinforcingBarType" + ], + "IfcReinforcingMesh": [ + "IfcReinforcingMeshType" + ], + "IfcRoof": [ + "IfcRoofType" + ], + "IfcSanitaryTerminal": [ + "IfcSanitaryTerminalType" + ], + "IfcSensor": [ + "IfcSensorType" + ], + "IfcShadingDevice": [ + "IfcShadingDeviceType" + ], + "IfcSlab": [ + "IfcSlabType" + ], + "IfcSlabElementedCase": [ + "IfcSlabType" + ], + "IfcSlabStandardCase": [ + "IfcSlabType" + ], + "IfcSolarDevice": [ + "IfcSolarDeviceType" + ], + "IfcSpace": [ + "IfcSpaceType" + ], + "IfcSpaceHeater": [ + "IfcSpaceHeaterType" + ], + "IfcSpatialZone": [ + "IfcSpatialZoneType" + ], + "IfcStackTerminal": [ + "IfcStackTerminalType" + ], + "IfcStair": [ + "IfcStairType" + ], + "IfcStairFlight": [ + "IfcStairFlightType" + ], + "IfcSwitchingDevice": [ + "IfcSwitchingDeviceType" + ], + "IfcSystemFurnitureElement": [ + "IfcSystemFurnitureElementType" + ], + "IfcTank": [ + "IfcTankType" + ], + "IfcTendon": [ + "IfcTendonType" + ], + "IfcTendonAnchor": [ + "IfcTendonAnchorType" + ], + "IfcTransformer": [ + "IfcTransformerType" + ], + "IfcTransportElement": [ + "IfcTransportElementType" + ], + "IfcTubeBundle": [ + "IfcTubeBundleType" + ], + "IfcUnitaryControlElement": [ + "IfcUnitaryControlElementType" + ], + "IfcUnitaryEquipment": [ + "IfcUnitaryEquipmentType" + ], + "IfcValve": [ + "IfcValveType" + ], + "IfcVibrationIsolator": [ + "IfcVibrationIsolatorType" + ], + "IfcWall": [ + "IfcWallType" + ], + "IfcWallElementedCase": [ + "IfcWallType" + ], + "IfcWallStandardCase": [ + "IfcWallType" + ], + "IfcWasteTerminal": [ + "IfcWasteTerminalType" + ], + "IfcWindow": [ + "IfcWindowType", + "IfcWindowStyle" + ], + "IfcWindowStandardCase": [ + "IfcWindowType", + "IfcWindowStyle" + ] +} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4x3.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4x3.json new file mode 100644 index 0000000000000000000000000000000000000000..6d712fcada996ae58043372fcd14334d01852de5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/entity_to_type_map_4x3.json @@ -0,0 +1,428 @@ +{ + "IfcActuator": [ + "IfcActuatorType" + ], + "IfcAirTerminal": [ + "IfcAirTerminalType" + ], + "IfcAirTerminalBox": [ + "IfcAirTerminalBoxType" + ], + "IfcAirToAirHeatRecovery": [ + "IfcAirToAirHeatRecoveryType" + ], + "IfcAlarm": [ + "IfcAlarmType" + ], + "IfcAudioVisualAppliance": [ + "IfcAudioVisualApplianceType" + ], + "IfcBeam": [ + "IfcBeamType" + ], + "IfcBearing": [ + "IfcBearingType" + ], + "IfcBoiler": [ + "IfcBoilerType" + ], + "IfcBuildingElementPart": [ + "IfcBuildingElementPartType" + ], + "IfcBuildingElementProxy": [ + "IfcBuildingElementProxyType" + ], + "IfcBuiltElement": [ + "IfcBuiltElementType" + ], + "IfcBurner": [ + "IfcBurnerType" + ], + "IfcCableCarrierFitting": [ + "IfcCableCarrierFittingType" + ], + "IfcCableCarrierSegment": [ + "IfcCableCarrierSegmentType" + ], + "IfcCableFitting": [ + "IfcCableFittingType" + ], + "IfcCableSegment": [ + "IfcCableSegmentType" + ], + "IfcCaissonFoundation": [ + "IfcCaissonFoundationType" + ], + "IfcChiller": [ + "IfcChillerType" + ], + "IfcChimney": [ + "IfcChimneyType" + ], + "IfcCivilElement": [ + "IfcCivilElementType" + ], + "IfcCoil": [ + "IfcCoilType" + ], + "IfcColumn": [ + "IfcColumnType" + ], + "IfcCommunicationsAppliance": [ + "IfcCommunicationsApplianceType" + ], + "IfcCompressor": [ + "IfcCompressorType" + ], + "IfcCondenser": [ + "IfcCondenserType" + ], + "IfcController": [ + "IfcControllerType" + ], + "IfcConveyorSegment": [ + "IfcConveyorSegmentType" + ], + "IfcCooledBeam": [ + "IfcCooledBeamType" + ], + "IfcCoolingTower": [ + "IfcCoolingTowerType" + ], + "IfcCourse": [ + "IfcCourseType" + ], + "IfcCovering": [ + "IfcCoveringType" + ], + "IfcCurtainWall": [ + "IfcCurtainWallType" + ], + "IfcDamper": [ + "IfcDamperType" + ], + "IfcDeepFoundation": [ + "IfcDeepFoundationType" + ], + "IfcDiscreteAccessory": [ + "IfcDiscreteAccessoryType" + ], + "IfcDistributionBoard": [ + "IfcDistributionBoardType" + ], + "IfcDistributionChamberElement": [ + "IfcDistributionChamberElementType" + ], + "IfcDistributionControlElement": [ + "IfcDistributionElementType" + ], + "IfcDistributionElement": [ + "IfcDistributionElementType" + ], + "IfcDistributionFlowElement": [ + "IfcDistributionElementType" + ], + "IfcDoor": [ + "IfcDoorType" + ], + "IfcDuctFitting": [ + "IfcDuctFittingType" + ], + "IfcDuctSegment": [ + "IfcDuctSegmentType" + ], + "IfcDuctSilencer": [ + "IfcDuctSilencerType" + ], + "IfcEarthworksElement": [ + "IfcBuiltElementType" + ], + "IfcEarthworksFill": [ + "IfcBuiltElementType" + ], + "IfcElectricAppliance": [ + "IfcElectricApplianceType" + ], + "IfcElectricDistributionBoard": [ + "IfcElectricDistributionBoardType" + ], + "IfcElectricFlowStorageDevice": [ + "IfcElectricFlowStorageDeviceType" + ], + "IfcElectricFlowTreatmentDevice": [ + "IfcElectricFlowTreatmentDeviceType" + ], + "IfcElectricGenerator": [ + "IfcElectricGeneratorType" + ], + "IfcElectricMotor": [ + "IfcElectricMotorType" + ], + "IfcElectricTimeControl": [ + "IfcElectricTimeControlType" + ], + "IfcElementAssembly": [ + "IfcElementAssemblyType" + ], + "IfcEnergyConversionDevice": [ + "IfcDistributionElementType" + ], + "IfcEngine": [ + "IfcEngineType" + ], + "IfcEvaporativeCooler": [ + "IfcEvaporativeCoolerType" + ], + "IfcEvaporator": [ + "IfcEvaporatorType" + ], + "IfcFan": [ + "IfcFanType" + ], + "IfcFastener": [ + "IfcFastenerType" + ], + "IfcFilter": [ + "IfcFilterType" + ], + "IfcFireSuppressionTerminal": [ + "IfcFireSuppressionTerminalType" + ], + "IfcFlowController": [ + "IfcDistributionElementType" + ], + "IfcFlowFitting": [ + "IfcDistributionElementType" + ], + "IfcFlowInstrument": [ + "IfcFlowInstrumentType" + ], + "IfcFlowMeter": [ + "IfcFlowMeterType" + ], + "IfcFlowMovingDevice": [ + "IfcDistributionElementType" + ], + "IfcFlowSegment": [ + "IfcDistributionElementType" + ], + "IfcFlowStorageDevice": [ + "IfcDistributionElementType" + ], + "IfcFlowTerminal": [ + "IfcDistributionElementType" + ], + "IfcFlowTreatmentDevice": [ + "IfcDistributionElementType" + ], + "IfcFooting": [ + "IfcFootingType" + ], + "IfcFurnishingElement": [ + "IfcFurnishingElementType" + ], + "IfcFurniture": [ + "IfcFurnitureType" + ], + "IfcGeographicElement": [ + "IfcGeographicElementType" + ], + "IfcHeatExchanger": [ + "IfcHeatExchangerType" + ], + "IfcHumidifier": [ + "IfcHumidifierType" + ], + "IfcImpactProtectionDevice": [ + "IfcImpactProtectionDeviceType" + ], + "IfcInterceptor": [ + "IfcInterceptorType" + ], + "IfcJunctionBox": [ + "IfcJunctionBoxType" + ], + "IfcKerb": [ + "IfcKerbType" + ], + "IfcLamp": [ + "IfcLampType" + ], + "IfcLightFixture": [ + "IfcLightFixtureType" + ], + "IfcLiquidTerminal": [ + "IfcLiquidTerminalType" + ], + "IfcMechanicalFastener": [ + "IfcMechanicalFastenerType" + ], + "IfcMedicalDevice": [ + "IfcMedicalDeviceType" + ], + "IfcMember": [ + "IfcMemberType" + ], + "IfcMobileTelecommunicationsAppliance": [ + "IfcMobileTelecommunicationsApplianceType" + ], + "IfcMooringDevice": [ + "IfcMooringDeviceType" + ], + "IfcMotorConnection": [ + "IfcMotorConnectionType" + ], + "IfcNavigationElement": [ + "IfcNavigationElementType" + ], + "IfcOutlet": [ + "IfcOutletType" + ], + "IfcPavement": [ + "IfcPavementType" + ], + "IfcPile": [ + "IfcPileType" + ], + "IfcPipeFitting": [ + "IfcPipeFittingType" + ], + "IfcPipeSegment": [ + "IfcPipeSegmentType" + ], + "IfcPlate": [ + "IfcPlateType" + ], + "IfcProtectiveDevice": [ + "IfcProtectiveDeviceType" + ], + "IfcProtectiveDeviceTrippingUnit": [ + "IfcProtectiveDeviceTrippingUnitType" + ], + "IfcPump": [ + "IfcPumpType" + ], + "IfcRail": [ + "IfcRailType" + ], + "IfcRailing": [ + "IfcRailingType" + ], + "IfcRamp": [ + "IfcRampType" + ], + "IfcRampFlight": [ + "IfcRampFlightType" + ], + "IfcReinforcedSoil": [ + "IfcBuiltElementType" + ], + "IfcReinforcingBar": [ + "IfcReinforcingBarType" + ], + "IfcReinforcingMesh": [ + "IfcReinforcingMeshType" + ], + "IfcRoof": [ + "IfcRoofType" + ], + "IfcSanitaryTerminal": [ + "IfcSanitaryTerminalType" + ], + "IfcSensor": [ + "IfcSensorType" + ], + "IfcShadingDevice": [ + "IfcShadingDeviceType" + ], + "IfcSign": [ + "IfcSignType" + ], + "IfcSignal": [ + "IfcSignalType" + ], + "IfcSlab": [ + "IfcSlabType" + ], + "IfcSolarDevice": [ + "IfcSolarDeviceType" + ], + "IfcSpace": [ + "IfcSpaceType" + ], + "IfcSpaceHeater": [ + "IfcSpaceHeaterType" + ], + "IfcSpatialZone": [ + "IfcSpatialZoneType" + ], + "IfcStackTerminal": [ + "IfcStackTerminalType" + ], + "IfcStair": [ + "IfcStairType" + ], + "IfcStairFlight": [ + "IfcStairFlightType" + ], + "IfcSwitchingDevice": [ + "IfcSwitchingDeviceType" + ], + "IfcSystemFurnitureElement": [ + "IfcSystemFurnitureElementType" + ], + "IfcTank": [ + "IfcTankType" + ], + "IfcTendon": [ + "IfcTendonType" + ], + "IfcTendonAnchor": [ + "IfcTendonAnchorType" + ], + "IfcTendonConduit": [ + "IfcTendonConduitType" + ], + "IfcTrackElement": [ + "IfcTrackElementType" + ], + "IfcTransformer": [ + "IfcTransformerType" + ], + "IfcTransportElement": [ + "IfcTransportElementType" + ], + "IfcTubeBundle": [ + "IfcTubeBundleType" + ], + "IfcUnitaryControlElement": [ + "IfcUnitaryControlElementType" + ], + "IfcUnitaryEquipment": [ + "IfcUnitaryEquipmentType" + ], + "IfcValve": [ + "IfcValveType" + ], + "IfcVehicle": [ + "IfcVehicleType" + ], + "IfcVibrationDamper": [ + "IfcVibrationDamperType" + ], + "IfcVibrationIsolator": [ + "IfcVibrationIsolatorType" + ], + "IfcWall": [ + "IfcWallType" + ], + "IfcWallStandardCase": [ + "IfcWallType" + ], + "IfcWasteTerminal": [ + "IfcWasteTerminalType" + ], + "IfcWindow": [ + "IfcWindowType" + ] +} \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/file.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/file.py new file mode 100644 index 0000000000000000000000000000000000000000..4875ddf3b7949d4045481b1636c432da423b9699 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/file.py @@ -0,0 +1,115 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import zipfile +from typing import IO, Union, TypedDict +from typing_extensions import NotRequired + + +class HeaderMetadata(TypedDict): + name: NotRequired[str] + # FILE_DESCRIPTION, not the description from FILE_NAME. + description: NotRequired[str] + implementation_level: NotRequired[str] + time_stamp: NotRequired[str] + schema_name: NotRequired[str] + + +class IfcHeaderExtractor: + """An utility class for extracting header information from IFC files. + + This class provides functionality to extract key metadata from the header section of + IFC files without recreating the entire file as `ifcopenshell.file`. + For optimization, extractor will search only for the first 50 lines + of the IFC file for metadata. + + Supported formats: .ifc, .ifczip. + + Metadata available by the extraction is presented in the example below. + + + Example: + + .. code:: python + + from ifcopenshell.util.file import IfcHeaderExtractor + + extractor = IfcHeaderExtractor("path/to/your/file.ifc") + # Get dictionary of the extracted metadata. + header_info = extractor.extract() + + # Print the extracted information + + # ViewDefinition[DesignTransferView] + print("File Description:", header_info.get("description")) + + # 2;1 + print("Implementation Level:", header_info.get("implementation_level")) + + # file.ifc + print("File Name:", header_info.get("name")) + + # 2024-06-25T15:48:10+05:00 + print("Time Stamp:", header_info.get("time_stamp")) + + # IFC4X3_ADD2 + print("Schema Name:", header_info.get("schema_name")) + """ + + def __init__(self, filepath: str): + self.filepath = filepath + + def extract(self) -> HeaderMetadata: + extension = self.filepath.split(".")[-1] + if extension.lower() == "ifc": + with open(self.filepath) as ifc_file: + return self.extract_ifc_spf(ifc_file) + elif extension.lower() == "ifczip": + return self.extract_ifc_zip() + elif extension.lower() == "ifcsqlite": + return {} # TODO + raise ValueError(f"Unsupported file extension: '{extension}'.") + + def extract_ifc_spf(self, ifc_file: Union[IO[bytes], IO[str]]) -> HeaderMetadata: + # https://www.steptools.com/stds/step/IS_final_p21e3.html#clause-8 + data = HeaderMetadata() + max_lines_to_parse = 50 + for _ in range(max_lines_to_parse): + line = next(ifc_file) + if isinstance(line, bytes): + line = line.decode("utf-8") + if line.startswith("FILE_DESCRIPTION"): + for i, part in enumerate(line.split("'")): + if i == 1: + data["description"] = part + elif i == 3: + data["implementation_level"] = part + elif line.startswith("FILE_NAME"): + for i, part in enumerate(line.split("'")): + if i == 1: + data["name"] = part + elif i == 3: + data["time_stamp"] = part + elif line.startswith("FILE_SCHEMA"): + data["schema_name"] = line.split("'")[1] + break + return data + + def extract_ifc_zip(self) -> HeaderMetadata: + archive = zipfile.ZipFile(self.filepath, "r") + return self.extract_ifc_spf(archive.open(archive.filelist[0])) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/fm.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/fm.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b1977e4ec8cad3974a151e06004f13c04b5eb8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/fm.py @@ -0,0 +1,184 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell +import ifcopenshell.ifcopenshell_wrapper as W +import ifcopenshell.util.attribute +from typing import Literal +from typing_extensions import assert_never + +# COBie actually uses an exclusion list, but this inclusion list is equivalent. +cobie_type_classes = [ + "IfcDoorStyle", + "IfcBuildingElementProxyType", + "IfcChimneyType", + "IfcCoveringType", + "IfcDoorType", + "IfcFootingType", + "IfcPileType", + "IfcRoofType", + "IfcShadingDeviceType", + "IfcWindowType", + "IfcDistributionControlElementType", + "IfcDistributionChamberElementType", + "IfcEnergyConversionDeviceType", + "IfcFlowControllerType", + "IfcFlowMovingDeviceType", + "IfcFlowStorageDeviceType", + "IfcFlowTerminalType", + "IfcFlowTreatmentDeviceType", + "IfcElementAssemblyType", + "IfcBuildingElementPartType", + "IfcDiscreteAccessoryType", + "IfcMechanicalFastenerType", + "IfcReinforcingElementType", + "IfcVibrationIsolatorType", + "IfcFurnishingElementType", + "IfcGeographicElementType", + "IfcTransportElementType", + "IfcSpatialZoneType", + "IfcWindowStyle", +] + +cobie_component_classes = [ + "IfcBuildingElementProxy", + "IfcChimney", + "IfcCovering", + "IfcDoor", + "IfcShadingDevice", + "IfcWindow", + "IfcDistributionControlElement", + "IfcDistributionChamberElement", + "IfcEnergyConversionDevice", + "IfcFlowController", + "IfcFlowMovingDevice", + "IfcFlowStorageDevice", + "IfcFlowTerminal", + "IfcFlowTreatmentDevice", + "IfcDiscreteAccessory", + "IfcTendon", + "IfcTendonAnchor", + "IfcVibrationIsolator", + "IfcFurnishingElement", + "IfcGeographicElement", + "IfcTransportElement", +] + +fmhem_classes_ifc4 = [ + "IfcDoorType", + "IfcWindowType", + "IfcShadingDeviceType", + "IfcDistributionControlElementType", + "IfcEnergyConversionDeviceType", + "IfcFlowControllerType", + "IfcFlowMovingDeviceType", + "IfcFlowStorageDeviceType", + "IfcFlowTerminalType", + "IfcFlowTreatmentDeviceType", + "IfcFurnishingElementType", + "IfcTransportElementType", +] + +fmhem_classes_ifc2x3 = [ + "IfcDoorStyle", + "IfcWindowStyle", + "IfcShadingDeviceType", + "IfcDistributionControlElementType", + "IfcEnergyConversionDeviceType", + "IfcFlowControllerType", + "IfcFlowMovingDeviceType", + "IfcFlowStorageDeviceType", + "IfcFlowTerminalType", + "IfcFlowTreatmentDeviceType", + "IfcFurnishingElementType", + "IfcTransportElementType", +] + +fmhem_excluded_classes = [ + "IfcCooledBeamType", + "IfcBurnerType", + "IfcCoilType", + "IfcLampType", +] + + +def get_cobie_types(ifc_file: ifcopenshell.file) -> list[ifcopenshell.entity_instance]: + elements = [] + for ifc_class in cobie_type_classes: + try: + elements += ifc_file.by_type(ifc_class) + except: + pass + return elements + + +def get_cobie_components(ifc_file: ifcopenshell.file) -> list[ifcopenshell.entity_instance]: + elements = [] + for ifc_class in cobie_component_classes: + try: + elements += ifc_file.by_type(ifc_class) + except: + pass + return elements + + +def get_fmhem_types(ifc_file: ifcopenshell.file) -> list[ifcopenshell.entity_instance]: + elements = [] + if ifc_file.schema == "IFC2X3": + fmhem_classes = fmhem_classes_ifc2x3 + else: + fmhem_classes = fmhem_classes_ifc4 + for ifc_class in fmhem_classes: + try: + elements += [e for e in ifc_file.by_type(ifc_class) if e.is_a() not in fmhem_excluded_classes] + except: + pass + return elements + + +def get_fmhem_classes(schema: Literal["IFC4", "IFC2X3"] = "IFC4") -> dict[str, list[str]]: + results = {} + + def get_fmhem_class(declaration: W.entity) -> None: + if declaration.name() in fmhem_excluded_classes: + pass + elif declaration.is_abstract(): + pass + else: + types = [] + for attribute in declaration.all_attributes(): + if attribute.name() == "PredefinedType": + types = list(ifcopenshell.util.attribute.get_enum_items(attribute)) + if "NOTDEFINED" in types: + types.remove("NOTDEFINED") + results[declaration.name()] = types + + for subtype in declaration.subtypes(): + get_fmhem_class(subtype) + + if schema == "IFC4": + classes = fmhem_classes_ifc4 + elif schema == "IFC2X3": + classes = fmhem_classes_ifc2x3 + else: + assert_never(schema) + schema_ = ifcopenshell.schema_by_name(schema) + for ifc_class in classes: + declaration = schema_.declaration_by_name(ifc_class) + get_fmhem_class(declaration) + return results diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/generate_pset_templates.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/generate_pset_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..44d5bc28cf2dacd9bd5045c81ec6b50e279dd0ca --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/generate_pset_templates.py @@ -0,0 +1,425 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +RUN_FROM_DEV_REPO = False + +import ifcopenshell.ifcopenshell_wrapper as W +import ifcopenshell.api.unit +import ifcopenshell.api.project +import ifcopenshell.guid +import ifcopenshell.util.attribute +import glob +import sys +from pathlib import Path +from lxml import etree +from itertools import chain +from typing import cast + + +if not RUN_FROM_DEV_REPO: + import zipfile + import shutil + +BASE_MODULE_PATH = Path(__file__).parent + +if not RUN_FROM_DEV_REPO: + IFC4x3_HTML_ZIP_LOCATION = BASE_MODULE_PATH / "annex-a-psd.zip" + IFC4x3_OUTPUT_PATH = BASE_MODULE_PATH / "schema/Pset_IFC4X3.ifc" +else: + IFC4x3_PSD_LOCATION = BASE_MODULE_PATH / "../output/psd" + try: + IFC4x3_OUTPUT_PATH = sys.argv[1] + except: + IFC4x3_OUTPUT_PATH = BASE_MODULE_PATH / "../output/Pset_IFC4X3.ifc" + +IFC2x3_HTML_ZIP_LOCATION = BASE_MODULE_PATH / "IFC2x3_TC1_HTML_distribution-pset_errata.zip" +IFC2x3_OUTPUT_PATH = BASE_MODULE_PATH / "schema/Pset_IFC2X3.ifc" + +PROPERTY_TYPES_DICT = { + "TypePropertySingleValue": ("P_SINGLEVALUE", "type"), + # in IFC2X3 weirdly xmls have TypeSimpleProperty + # which is actually more P_REFERENCEVALUE value, not P_SINGLEVALUE + # because it utilizes IfcTimeSeries + "TypeSimpleProperty": ("P_REFERENCEVALUE", "type"), + "TypePropertyListValue": ("P_LISTVALUE", "type"), + "TypePropertyBoundedValue": ("P_BOUNDEDVALUE", "type"), + "TypePropertyReferenceValue": ("P_REFERENCEVALUE", "reftype"), + "TypePropertyEnumeratedValue": ("P_ENUMERATEDVALUE", ""), + "TypePropertyTableValue": ("P_TABLEVALUE", "type"), + "TypeComplexProperty": ("P_COMPLEX", ""), +} + + +class PsetTemplatesGenerator: + def parse_ifc4x3_data(self): + print("Starting parsing data for IFC4X3...") + + if not RUN_FROM_DEV_REPO: + if not IFC4x3_HTML_ZIP_LOCATION.is_file(): + raise Exception( + f'ISO release for Ifc4.3.2.0 expected to be located in "{IFC4x3_HTML_ZIP_LOCATION.resolve()}"\n' + "For generating ifc pset library please either setup docs as described above \n" + "or change IFC4x3_HTML_ZIP_LOCATION in the script accordingly.\n" + "You can download docs from the repository: \n" + "https://standards.buildingsmart.org/IFC/RELEASE/IFC4_3/HTML/annex-a-psd.zip" + ) + # unzip the data + pset_data_location = BASE_MODULE_PATH / "temp/annex-a-psd" + with zipfile.ZipFile(IFC4x3_HTML_ZIP_LOCATION, "r") as fi_zip: + fi_zip.extractall(pset_data_location) + else: + if not IFC4x3_PSD_LOCATION.is_dir(): + raise Exception( + f'Psets xmls files expected to be in folder "{IFC4x3_PSD_LOCATION.resolve()}\\"\n' + "For generating ifc pset library please either setup docs as described above \n" + "or change IFC4x3_PSD_LOCATION in the script accordingly." + ) + pset_data_location = IFC4x3_PSD_LOCATION + + pset_data_glob = f"{pset_data_location}/*.xml" + self.parse_psets_data("IFC4X3", pset_data_glob, "IFC4X3 Property Set Templates", str(IFC4x3_OUTPUT_PATH)) + + if not RUN_FROM_DEV_REPO: + shutil.rmtree(pset_data_location) + + def parse_ifc2x3_data(self): + print("Starting parsing data for IFC2X3...") + if not IFC2x3_HTML_ZIP_LOCATION.is_file(): + raise Exception( + f'ISO release for IFC2x3 TC1 expected to be located in "{IFC2x3_HTML_ZIP_LOCATION.resolve()}"\n' + "For doc extraction please either setup docs as described above \n" + "or change IFC2x3_HTML_LOCATION in the script accordingly.\n" + "You can download docs from the url: \n" + "https://standards.buildingsmart.org/IFC/RELEASE/IFC2x3/TC1/IFC2x3_TC1_HTML_distribution-pset_errata.zip" + ) + + # unzip the data + pset_data_location = BASE_MODULE_PATH / "temp/ifc2x3_html" + with zipfile.ZipFile(IFC2x3_HTML_ZIP_LOCATION, "r") as fi_zip: + fi_zip.extractall(pset_data_location) + + pset_data_glob = f"{pset_data_location}/**/pset*.xml" + # we're using IFC4X3 since IfcPropertySetTemplate and IfcRelDeclares + # are not available in IFC2X3 + self.parse_psets_data("IFC4X3", pset_data_glob, "IFC2X3 Property Set Templates", str(IFC2x3_OUTPUT_PATH)) + shutil.rmtree(pset_data_location) + + def ifc_entity(self, entity_name, **kwargs): + entity = self.ifc_file.create_entity(entity_name, **kwargs) + return entity + + def parse_psets_data(self, schema_name, pset_data_glob, project_name, ifc_output_path): + schema_name = schema_name.upper() + self.ifc_file = ifcopenshell.api.project.create_file(version=schema_name) + self.units = dict() + schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name(self.ifc_file.schema_identifier) + + derived_unit_enum = schema.declaration_by_name("IfcDerivedUnitEnum").as_enumeration_type() + assert derived_unit_enum + self.ifc_derived_unit_enum = derived_unit_enum.enumeration_items() + + ifc_unit_enum = schema.declaration_by_name("IfcUnitEnum").as_enumeration_type() + assert ifc_unit_enum + self.ifc_unit_enum = ifc_unit_enum.enumeration_items() + + value_select = schema.declaration_by_name("IfcValue").as_select_type() + assert value_select + select_types = cast(tuple[W.select_type, ...], value_select.select_list()) + self.ifc_value_types = [t.name() for t in chain(*[select_type.select_list() for select_type in select_types])] + + project = self.ifc_entity("IfcProject", Name=project_name, GlobalId=ifcopenshell.guid.new()) + psets_list = [] + if schema_name == "IFC2X3": + rel = None + else: + rel = self.ifc_entity( + "IfcRelDeclares", + RelatedDefinitions=psets_list, + RelatingContext=project, + GlobalId=ifcopenshell.guid.new(), + ) + + # in IFC4 there is also + # IFCLIBRARYREFERENCE after each (sometimes multiple of them if there are several languages involved) + # 1) enumeration item (also with IFCRELASSOCIATESLIBRARY) + # 2) enumeration + # 3) property set (also with IFCRELASSOCIATESLIBRARY) + # 4) property definition (also with IFCRELASSOCIATESLIBRARY) + # but in ifc4x3 there is no data for those library references + # TODO: need to add it to .ifc for IFC4X3 too + # if https://github.com/buildingSMART/IFC4.3.x-development/issues/587 is resolved + + # iterate through all xmls files + for pset_path in glob.iglob(pset_data_glob, recursive=True): + pset_path = Path(pset_path) + + with open(pset_path, "r", encoding="utf-8") as fi: + root_xml = etree.fromstring(fi.read()) + pset_name = root_xml.find("Name").text + # pset / qset + pset_type = True if pset_name.split("_")[0] == "Pset" else False + + # TODO: if guids provided in xml should use them instead + pset_guid = ifcopenshell.guid.new() + applicable_entities = [i.text for i in root_xml.find("ApplicableClasses").findall("ClassName")] + pset = self.ifc_entity( + "IfcPropertySetTemplate", + GlobalId=pset_guid, + TemplateType=root_xml.get("templatetype"), + Name=pset_name, + Description=root_xml.find("Definition").text, + ApplicableEntity=",".join(applicable_entities).strip(), + ) + if project_name.startswith("IFC2X3"): + pset.TemplateType = self.get_pset_template_type_ifc2x3(pset) + else: + pset.TemplateType = root_xml.get("templatetype") + + # NOTE: there is also Applicability tag + # but it's seems always empty in ifc4 and ifc4x3 + # in ifc2x3 it's present but contains just applicability string description + # e.g. "IfcElectricMotorType, IfcFlowMovingDeviceType entities." for "Pset_ElectricMotorTypeCommon" + + pdef_entities = [] + for pdef in root_xml.find("PropertyDefs" if pset_type else "QtoDefs").getchildren(): + pset_property = self.get_property_from_pdef(pset_name, pset_type, pdef) + if not pset_property: + continue + pdef_entities.append(pset_property) + pset.HasPropertyTemplates = pdef_entities + psets_list.append(pset) + + print(f"{len(psets_list)} psets parsed.") + if rel: + rel.RelatedDefinitions = psets_list + self.ifc_file.write(ifc_output_path) + + def get_property_from_pdef(self, pset_name, pset_type, pdef): + pset_prop_guid = ifcopenshell.guid.new() + pset_property_name = pdef.find("Name").text + + # figuring pset property types and related values + if not pset_type: + property_type_tag = None + else: + try: + assert len(pdef.find("PropertyType").getchildren()) == 1, "Not implemented case" + except AssertionError: + warning_message = ( + f"WARNING: met not handles case with multiple property types " + f"- {pset_name}/{pset_property_name}." + "This property may have incorrect data parsed." + ) + print(warning_message) + + property_type_tag = pdef.find("PropertyType").getchildren()[0].tag + if property_type_tag not in PROPERTY_TYPES_DICT: + warning_message = ( + f"WARNING: not implemented property type " + f"{property_type_tag} ({pset_name}/{pset_property_name}). " + "This property will be skipped. Need to rework the code to support that type of property." + ) + print(warning_message) + return + + # NOTE: there is also ValueDef tag + # which could have two subtags - MinValue and MaxValue + # but it's seems to be present only in ifc2x3 and everywhere values are either "", "0", "?" + # so just ignoring it + + # create pset property + if not pset_type or property_type_tag != "TypeComplexProperty": + pset_property = self.ifc_entity("IfcSimplePropertyTemplate") + # tested on IFC4_ADD2.ifc - all props are READWRITE by default + pset_property.AccessState = "READWRITE" + else: + pset_property = self.ifc_entity("IfcComplexPropertyTemplate") + complex_prop_xml = pdef.find("PropertyType/TypeComplexProperty") + child_properties = [ + self.get_property_from_pdef(pset_name, pset_type, child_pdef) + for child_pdef in complex_prop_xml.findall("PropertyDef") + ] + pset_property.UsageName = complex_prop_xml.get("name") + pset_property.HasPropertyTemplates = child_properties + + pset_property.GlobalId = pset_prop_guid + pset_property.Description = pdef.find("Definition").text + pset_property.Name = pset_property_name + + self.add_prop_type_params_to_prop(pset_type, pdef, pset_property, property_type_tag) + return pset_property + + def get_unit(self, unit_type): + # to define USERDEFINED unit type we'd need more info + # like UserDefinedType name and elements for IfcDerivedUnit + # which is not provided in .xmls + if unit_type != "USERDEFINED": + return None + + if unit_type in self.units: + return self.units[unit_type] + + unit_entity = None + if unit_type in self.ifc_derived_unit_enum: + # TODO: define derived units if there will be someday api like `ifcopenshell.api.unit.add_derived_unit(...)` + # since creating IfcDerivedUnit is more complex and requiring settting up elements it consists of + # and related IfcNamedUnits + # unit_entity = ifcopenshell.api.unit.add_derived_unit(self.ifc_file, unit_type=unit_type) + pass + elif unit_type in self.ifc_unit_enum: + unit_entity = ifcopenshell.api.unit.add_si_unit(self.ifc_file, unit_type=unit_type) + elif unit_type == "IFCMONETARYUNIT": + self.ifc_entity("IFCMONETARYUNIT", Currency="") + else: + print(f"WARNING. Wasn't able to find units {unit_type} in schema.") + self.units[unit_type] = unit_entity + return unit_entity + + def add_prop_type_params_to_prop(self, pset_type, pdef, pset_property, property_type_tag): + if not pset_type: + property_type = pdef.find("QtoType").text + else: + property_type, property_type_parse = PROPERTY_TYPES_DICT[property_type_tag] + + pset_property.TemplateType = property_type + + if not pset_type or property_type == "P_COMPLEX": + # qsets and complex props don't have measure types + return + + property_type_path = f"PropertyType/{property_type_tag}" + property_type_xml = pdef.find(property_type_path) + + # usually it's only for P_TABLEVALUE + expression_xml = property_type_xml.find("Expression") + if expression_xml is not None and expression_xml.text != "-": + pset_property.Expression = expression_xml.text + + # figure measure type for property sets + if property_type == "P_ENUMERATEDVALUE": + # always create new enumeration for the new properties + # even if the same enumeration was already used before + # example of reoccuring enumeration in .ifc for ifc4 - PEnum_ElementStatus + enum_items = [i.text for i in property_type_xml.findall(f"EnumList/EnumItem")] + enum_items = [self.ifc_entity("IfcLabel", wrappedValue=i) for i in enum_items] + prop_enumeration = self.ifc_entity( + "IfcPropertyEnumeration", + Name=property_type_xml.find("EnumList").get("name"), + EnumerationValues=enum_items, + ) + pset_property.Enumerators = prop_enumeration + pset_property.PrimaryMeasureType = "IfcLabel" + + elif property_type == "P_TABLEVALUE": + pset_property.PrimaryMeasureType = property_type_xml.find("DefiningValue/DataType").get("type") + pset_property.SecondaryMeasureType = property_type_xml.find("DefinedValue/DataType").get("type") + else: + if property_type == "P_REFERENCEVALUE": + if property_type_tag == "TypeSimpleProperty": + type_xml = property_type_xml.find("DataType") + primary_measure_type = type_xml.get(property_type_parse) + unit_type = property_type_xml.find("UnitType") + secondary_measure_type = ( + unit_type.get(property_type_parse).strip() if unit_type is not None else None + ) + + if primary_measure_type != "IfcTimeSeries": + unit = self.get_unit(secondary_measure_type) + secondary_measure_type = primary_measure_type + primary_measure_type = "IfcTimeSeries" + pset_property.PrimaryUnit = unit + + pset_property.PrimaryMeasureType = primary_measure_type + pset_property.SecondaryMeasureType = secondary_measure_type + else: + pset_property.PrimaryMeasureType = property_type_xml.get(property_type_parse) + # TODO: ifc4add2 seems to have some secondary measure types + # need to add it in ifc4x3 too + # if https://github.com/buildingSMART/IFC4.3.x-development/issues/586 is resolved + else: + if property_type == "P_LISTVALUE": + property_type_node = "ListValue" + if property_type in ("P_SINGLEVALUE", "P_BOUNDEDVALUE"): + property_type_node = "DataType" + + # only used only in ifc2x3, omitted in ifc4 and ifc4x3 + unit_type_xml = property_type_xml.find("UnitType") + + if unit_type_xml is not None: + unit_type = unit_type_xml.get(property_type_parse).strip() + unit_entity = self.get_unit(unit_type) + pset_property.PrimaryUnit = unit_entity + + type_xml = property_type_xml.find(property_type_node) + if property_type_node == "ListValue": + # for ListValue data type is contained in a single + primary_measure_type = type_xml.find("DataType").get(property_type_parse) + else: + primary_measure_type = type_xml.get(property_type_parse) + + primary_measure_type = primary_measure_type.strip() + if property_type == "P_SINGLEVALUE" and primary_measure_type not in self.ifc_value_types: + print( + f"Error assinging {primary_measure_type} as PrimaryMeasureType - it's not IfcValue, {property_type_tag}" + ) + + pset_property.PrimaryMeasureType = primary_measure_type + + def get_pset_template_type_ifc2x3(self, pset_template: ifcopenshell.entity_instance) -> str: + def declaration_is_a(declaration: ifcopenshell_wrapper.declaration, ifc_class: str) -> bool: + if declaration.name() == ifc_class: + return True + super_type = declaration.supertype() + if not super_type: + return False + return declaration_is_a(super_type, ifc_class) + + name = pset_template.Name + applicability = pset_template.ApplicableEntity + schema = ifcopenshell.schema_by_name("IFC2X3") + + if "PHistory" in name: + return "PSET_PERFORMANCEDRIVEN" + applicable_types = applicability.replace(", ", ",").split(",") + for applicable_type in applicable_types: + if not applicable_type: + continue + parts = applicable_type.split("/") + assert 3 > len(parts) > 0 + if parts[0].isupper(): # IFC2X3 thing + applicable_type = parts[1] + else: + applicable_type = parts[0] + applicable_type = applicable_type.strip() + + declaration = schema.declaration_by_name(applicable_type) + if declaration_is_a(declaration, "IfcTypeObject"): + return "PSET_TYPEDRIVENOVERRIDE" + # ifc4x3+ + elif declaration_is_a(declaration, "IfcProfileDef"): + return "PSET_PROFILEDRIVEN" + elif declaration_is_a(declaration, "IfcMaterialDefinition"): + return "PSET_MATERIALDRIVEN" + return "PSET_OCCURRENCEDRIVEN" + + +if __name__ == "__main__": + templates_generator = PsetTemplatesGenerator() + templates_generator.parse_ifc4x3_data() + if not RUN_FROM_DEV_REPO: + templates_generator.parse_ifc2x3_data() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/geolocation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/geolocation.py new file mode 100644 index 0000000000000000000000000000000000000000..748ba8f3c39c41b524ee372d94e111d667360200 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/geolocation.py @@ -0,0 +1,680 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import math +import numpy as np +import ifcopenshell +import ifcopenshell.util.element +import ifcopenshell.util.placement +from typing import NamedTuple, Optional, Union +from decimal import Decimal, ROUND_HALF_UP + +MatrixType = ifcopenshell.util.placement.MatrixType + + +class HelmertTransformation(NamedTuple): + e: float + n: float + h: float + xaa: float + xao: float + scale: float + factor_x: float + factor_y: float + factor_z: float + + +def dms2dd(degrees: int, minutes: int, seconds: int, us: int = 0) -> float: + """Convert degrees, minutes, and (micro)seconds to decimal degrees + All components must be either positive or negative. + + :param degrees: The degrees component + :param minutes: The minutes component + :param seconds: The seconds component + :param us: The microseconds component + :return: The angle in decimal degrees. + """ + all_positive_or_zero = degrees >= 0 and minutes >= 0 and seconds >= 0 and us >= 0 + all_negative_or_zero = degrees <= 0 and minutes <= 0 and seconds <= 0 and us <= 0 + assert all_positive_or_zero or all_negative_or_zero + return degrees + minutes / 60.0 + seconds / 3600.0 + us / 3600000000.0 + + +def dd2dms(dd: float, use_us: bool = False) -> Union[tuple[int, int, int, int], tuple[int, int, float]]: + """Convert decimal degrees to degrees, minutes, and (micro)seconds format + + :param dd: The decimal degrees + :param use_us: True if to include microseconds and false otherwise. Defaults to false. + :return: The angle in a tuple of either 3 or 4 values, + 4 values: integer number of degrees, integer number of minutes, integer number of seconds and integer number of microseconds + 3 values: integer number of degrees, integer number of minutes, and a float number for seconds + :note: the tuple follows the format of IfcCompoundPlaneAngleMeasure. Namely all of its components are either positive or negative. + """ + dd_decimal = Decimal(str(dd)) + + degrees = int(dd_decimal) + degrees_decimal = Decimal(degrees) + + fractional_part = dd_decimal - degrees_decimal + + minutes_decimal = fractional_part * Decimal(60) + minutes = int(minutes_decimal) + minutes_decimal_int = Decimal(minutes) + + seconds_decimal = (minutes_decimal - minutes_decimal_int) * Decimal(60) + + if use_us: + seconds = int(seconds_decimal) + seconds_decimal_int = Decimal(seconds) + microseconds_decimal = (seconds_decimal - seconds_decimal_int) * Decimal(1000000) + microseconds = int(microseconds_decimal.quantize(Decimal(1), rounding=ROUND_HALF_UP)) + return (degrees, minutes, seconds, microseconds) + else: + seconds_float = float(seconds_decimal) + return (degrees, minutes, seconds_float) + + +def xyz2enh( + x: float, + y: float, + z: float, + eastings: float = 0.0, + northings: float = 0.0, + orthogonal_height: float = 0.0, + x_axis_abscissa: float = 1.0, + x_axis_ordinate: float = 0.0, + scale: float = 1.0, + factor_x: float = 1.0, + factor_y: float = 1.0, + factor_z: float = 1.0, +) -> tuple[float, float, float]: + """Manually convert local XYZ coordinates to map eastings, northings, and height + + This function is for advanced users as it allows you to specify your own + helmert transformation parameters (i.e. those typically stored in + IfcMapConversion). This manual approach is useful for tests or in case your + are setting your helmert transformations in non-standard locations, or if + you are applying your own temporary false origin (such as when federating + models for digital twins of large cities). + + For most scenarios you should use :func:`auto_xyz2enh` instead. + + :param x: The X local engineering coordinate. + :param y: The Y local engineering coordinate. + :param z: The Z local engineering coordinate. + :param eastings: The eastings offset to apply. + :param northings: The northings offset to apply. + :param orthogonal_height: The orthogonal height offset to apply. + :param x_axis_abscissa: The X axis abscissa (i.e. first coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param x_axis_ordinate: The X axis ordinate (i.e. second coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param scale: The unit scale such that local ordinate * scale = map + ordinate. E.g. if your project is in millimeters but your CRS is in + meters, your scale should be 0.001. + :param factor_x: The combined scale factor for the X value to convert from + local coordinates to map coordinates. Your surveyor will typically know + this number and approximate it as a constant on a small site. Typically + factor_x and factor_y will be identical, and factor_z will be 1. + :param factor_y: Same but for the Y value. + :param factor_z: Same but for the Z value. + :return: A tuple of three ordinates representing the easting, northing and height. + """ + theta = math.atan2(x_axis_ordinate, x_axis_abscissa) + eastings = (scale * factor_x * math.cos(theta) * x) - (scale * factor_y * math.sin(theta) * y) + eastings + northings = (scale * factor_x * math.sin(theta) * x) + (scale * factor_y * math.cos(theta) * y) + northings + height = (scale * factor_z * z) + orthogonal_height + return (eastings, northings, height) + + +def auto_xyz2enh( + ifc_file: ifcopenshell.file, x: float, y: float, z: float, should_return_in_map_units: bool = True +) -> tuple[float, float, float]: + """Convert from local XYZ coordinates to global map coordinate eastings, northings, and heights + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the coordinates are returned unchanged. + + For IFC2X3, the map conversion is detected from the IfcProject's + ePSet_MapConversion. See the "User Guide for Geo-referencing in IFC": + https://www.buildingsmart.org/standards/bsi-standards/standards-library/ + + :param ifc_file: The IFC file + :param x: The X local engineering coordinate provided in project length units. + :param y: The Y local engineering coordinate provided in project length units. + :param z: The Z local engineering coordinate provided in project length units. + :param should_return_in_map_units: If true, the result is given in map units. + If false, the result will be converted back into project units. + :return: The global map coordinate eastings, northings, and height. + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return x, y, z + wcs = get_wcs(ifc_file) + if wcs is not None: + x, y, z = (np.linalg.inv(wcs) @ np.array((x, y, z, 1)))[:3] + enh = xyz2enh(x, y, z, *parameters) + if should_return_in_map_units: + return enh + return enh[0] / parameters.scale, enh[1] / parameters.scale, enh[2] / parameters.scale + + +def auto_enh2xyz( + ifc_file: ifcopenshell.file, easting: float, northing: float, height: float, is_specified_in_map_units: bool = True +) -> tuple[float, float, float]: + """Convert from global map coordinate eastings, northings, and heights to local XYZ coordinates + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the Z coordinate is returned unchanged. + + For IFC2X3, the map conversion is detected from the IfcProject's + ePSet_MapConversion. See the "User Guide for Geo-referencing in IFC": + https://www.buildingsmart.org/standards/bsi-standards/standards-library/ + + :param ifc_file: The IFC file + :param easting: The global easting map coordinate provided in map units. + :param northing: The global northing map coordinate provided in map units. + :param height: The global height map coordinate provided in map units. + :param is_specified_in_map_units: True if the input eastings, northing, and height are in map units. + :return: The local engineering XYZ coordinates in project length units. + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return easting, northing, height + if not is_specified_in_map_units: + easting *= parameters.scale + northing *= parameters.scale + height *= parameters.scale + xyz = enh2xyz(easting, northing, height, *parameters) + wcs = get_wcs(ifc_file) + if wcs is not None: + xyz = tuple((wcs @ np.array((*xyz, 1)))[:3]) + return xyz + + +def get_helmert_transformation_parameters(ifc_file: ifcopenshell.file) -> Optional[HelmertTransformation]: + """Retrieves the parameters of a helmert transformation that represents a + coordinate operation + + This coordinate operation is typically what is used to convert between + local engineering coordinates and map coordinates. + + :param ifc_file: The IFC model, typically containing an + IfcCoordinateOperation such as an IfcMapConversion. + :return: The parameters of the transformation. + """ + if ifc_file.schema == "IFC2X3": + project = ifc_file.by_type("IfcProject")[0] + conversion = ifcopenshell.util.element.get_pset(project, "ePSet_MapConversion") + if not conversion: + return + e = conversion.get("Eastings", None) or 0 + n = conversion.get("Northings", None) or 0 + h = conversion.get("OrthogonalHeight", None) or 0 + xaa = conversion.get("XAxisAbscissa", None) or 0 + xao = conversion.get("XAxisOrdinate", None) or 0 + scale = conversion.get("Scale", None) or 1 + factor_x = factor_y = factor_z = 1 + else: + conversion = ifc_file.by_type("IfcCoordinateOperation") + if not conversion: + return + conversion = conversion[0] + + if conversion.is_a("IfcMapConversion"): + e = conversion.Eastings or 0 + n = conversion.Northings or 0 + h = conversion.OrthogonalHeight or 0 + xaa = conversion.XAxisAbscissa or 0 + xao = conversion.XAxisOrdinate or 0 + scale = conversion.Scale or 1 + if conversion.is_a() == "IfcMapConversionScaled": + factor_x = conversion.FactorX + factor_y = conversion.FactorY + factor_z = conversion.FactorZ + else: + factor_x = factor_y = factor_z = 1 + elif conversion.is_a() == "IfcRigidOperation": + e = conversion.FirstCoordinate.wrappedValue + n = conversion.SecondCoordinate.wrappedValue + h = conversion.Height or 0 + xaa = 1.0 + xao = 0.0 + scale = factor_x = factor_y = factor_z = 1 + + if not xaa and not xao: + xaa = 1.0 + xao = 0.0 + + return HelmertTransformation(e, n, h, xaa, xao, scale, factor_x, factor_y, factor_z) + + +def auto_z2e(ifc_file: ifcopenshell.file, z: float, should_return_in_map_units: bool = True) -> float: + """Convert a Z coordinate to an elevation using model georeferencing data + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the Z coordinate is returned unchanged. + + For IFC2X3, the map conversion is detected from the IfcProject's + ePSet_MapConversion. See the "User Guide for Geo-referencing in IFC": + https://www.buildingsmart.org/standards/bsi-standards/standards-library/ + + :param ifc_file: The IFC file + :param z: The Z local engineering coordinate provided in project length units. + :return: The elevation in project length units. + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return z + e = z2e(z, parameters.h, parameters.scale, parameters.factor_z) + if should_return_in_map_units: + return e + return e / parameters.scale + + +def z2e(z: float, orthogonal_height: float = 0.0, scale: float = 1.0, factor_z: float = 1.0) -> float: + """Manually convert a Z coordinate to a map elevation + + This function is for advanced users as it allows you to specify your own + orthogonal height offset and transformation parameters. + + For most scenarios you should use :func:`auto_z2e` instead. + + :param z: The Z local engineering coordinate provided in project length units. + :param orthogonal_height: The orthogonal height offset to apply. + :param scale: The unit scale such that local ordinate * scale = map + ordinate. E.g. if your project is in millimeters but your CRS is in + meters, your scale should be 0.001. + :param factor_x: The combined scale factor for the Z value to convert from + local coordinates to map coordinates. Your surveyor will typically know + this number and approximate it as a constant on a small site. This is + typically just 1.0, as average combined scale factors usually only + affect the XY axes. + :return: The elevation in map units. + """ + return (scale * factor_z * z) + orthogonal_height + + +def enh2xyz( + e: float, + n: float, + h: float, + eastings: float = 0.0, + northings: float = 0.0, + orthogonal_height: float = 0, + x_axis_abscissa: float = 1.0, + x_axis_ordinate: float = 0.0, + scale: float = 1.0, + factor_x: float = 1.0, + factor_y: float = 1.0, + factor_z: float = 1.0, +) -> tuple[float, float, float]: + """Manually convert map eastings, northings, and height to local XYZ coordinates + + This function is for advanced users as it allows you to specify your own + helmert transformation parameters (i.e. those typically stored in + IfcMapConversion). This manual approach is useful for tests or in case your + are setting your helmert transformations in non-standard locations, or if + you are applying your own temporary false origin (such as when federating + models for digital twins of large cities). + + For most scenarios you should use :func:`auto_enh2xyz` instead. + + :param e: The global easting map coordinate. + :param n: The global northing map coordinate. + :param h: The global height map coordinate. + :param eastings: The eastings offset to apply. + :param northings: The northings offset to apply. + :param orthogonal_height: The orthogonal height offset to apply. + :param x_axis_abscissa: The X axis abscissa (i.e. first coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param x_axis_ordinate: The X axis ordinate (i.e. second coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param scale: The unit scale such that local ordinate * scale = map + ordinate. E.g. if your project is in millimeters but your CRS is in + meters, your scale should be 0.001. + :param factor_x: The combined scale factor for the X value to convert from + local coordinates to map coordinates. Your surveyor will typically know + this number and approximate it as a constant on a small site. Typically + factor_x and factor_y will be identical, and factor_z will be 1. + :param factor_y: Same but for the Y value. + :param factor_z: Same but for the Z value. + :return: A tuple of three ordinates representing XYZ. + """ + theta = math.atan2(x_axis_ordinate, x_axis_abscissa) + sint = math.sin(theta) + cost = math.cos(theta) + x = (((e - eastings) * cost) + ((n - northings) * sint)) / (scale * factor_x) + y = (((eastings - e) * sint) + ((n - northings) * cost)) / (scale * factor_y) + z = ((h - orthogonal_height) / scale) / factor_z + return (x, y, z) + + +def local2global( + matrix: MatrixType, + eastings: float = 0.0, + northings: float = 0.0, + orthogonal_height: float = 0.0, + x_axis_abscissa: float = 1.0, + x_axis_ordinate: float = 0.0, + scale: float = 1.0, + factor_x: float = 1.0, + factor_y: float = 1.0, + factor_z: float = 1.0, +) -> MatrixType: + """Manually convert a 4x4 matrix from local to global coordinates + + This function is for advanced users as it allows you to specify your own + helmert transformation parameters (i.e. those typically stored in + IfcMapConversion). This manual approach is useful for tests or in case your + are setting your helmert transformations in non-standard locations, or if + you are applying your own temporary false origin (such as when federating + models for digital twins of large cities). + + For most scenarios you should use :func:`auto_local2global` instead. + + :param matrix: A 4x4 numpy matrix representing local coordinates. + :param eastings: The eastings offset to apply. + :param northings: The northings offset to apply. + :param orthogonal_height: The orthogonal height offset to apply. + :param x_axis_abscissa: The X axis abscissa (i.e. first coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param x_axis_ordinate: The X axis ordinate (i.e. second coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param scale: The combined scale factor to convert from local coordinates + to map coordinates. + :return: A numpy 4x4 array matrix representing global coordinates. + """ + theta = math.atan2(x_axis_ordinate, x_axis_abscissa) + scale_and_factor_matrix = np.array( + [ + [scale * factor_x, 0, 0, 0], + [0, scale * factor_y, 0, 0], + [0, 0, scale * factor_z, 0], + [0, 0, 0, 1], + ] + ) + rotation_matrix = np.array( + [ + [math.cos(theta), -math.sin(theta), 0, 0], + [math.sin(theta), math.cos(theta), 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ] + ) + result = rotation_matrix @ scale_and_factor_matrix @ matrix + result[:3, 0] /= np.linalg.norm(result[:3, 0]) + result[:3, 1] /= np.linalg.norm(result[:3, 1]) + result[:3, 2] /= np.linalg.norm(result[:3, 2]) + result[0, 3] += eastings + result[1, 3] += northings + result[2, 3] += orthogonal_height + return result + + +def auto_local2global( + ifc_file: ifcopenshell.file, matrix: MatrixType, should_return_in_map_units: bool = True +) -> MatrixType: + """Convert a local matrix to a global map matrix + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the matrix is returned unchanged. + + :param ifc_file: The IFC file + :param matrix: A 4x4 numpy matrix representing local coordinates. + :param should_return_in_map_units: If true, the result is given in map units. + If false, the result will be converted back into project units. + :return: A numpy 4x4 array matrix representing global coordinates. + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return matrix.copy() + wcs = get_wcs(ifc_file) + if wcs is not None: + matrix = np.linalg.inv(wcs) @ matrix + result = local2global(matrix, *parameters) + if should_return_in_map_units: + return result + result[:3, 3] /= parameters.scale + return result + + +def global2local( + matrix: MatrixType, + eastings: float = 0.0, + northings: float = 0.0, + orthogonal_height: float = 0.0, + x_axis_abscissa: float = 1.0, + x_axis_ordinate: float = 0.0, + scale: float = 1.0, + factor_x: float = 1.0, + factor_y: float = 1.0, + factor_z: float = 1.0, +) -> MatrixType: + """Manually convert a 4x4 matrix from global to local coordinates + + This function is for advanced users as it allows you to specify your own + helmert transformation parameters (i.e. those typically stored in + IfcMapConversion). This manual approach is useful for tests or in case your + are setting your helmert transformations in non-standard locations, or if + you are applying your own temporary false origin (such as when federating + models for digital twins of large cities). + + :param matrix: A 4x4 numpy matrix representing global coordinates. + :param eastings: The eastings offset to apply. + :param northings: The northings offset to apply. + :param orthogonal_height: The orthogonal height offset to apply. + :param x_axis_abscissa: The X axis abscissa (i.e. first coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param x_axis_ordinate: The X axis ordinate (i.e. second coordinate) of the + 2D vector that points to the local X axis when in map coordinates. + :param scale: The combined scale factor to convert from local coordinates + to map coordinates. + :return: A numpy 4x4 array matrix representing local coordinates. + """ + theta = math.atan2(x_axis_ordinate, x_axis_abscissa) + scale_and_factor_matrix = np.array( + [ + [scale * factor_x, 0, 0, 0], + [0, scale * factor_y, 0, 0], + [0, 0, scale * factor_z, 0], + [0, 0, 0, 1], + ] + ) + rotation_matrix = np.array( + [ + [math.cos(theta), -math.sin(theta), 0, 0], + [math.sin(theta), math.cos(theta), 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1], + ] + ) + result = matrix.copy() + result[0, 3] -= eastings + result[1, 3] -= northings + result[2, 3] -= orthogonal_height + result = np.linalg.inv(scale_and_factor_matrix) @ np.linalg.inv(rotation_matrix) @ result + result[:3, 0] /= np.linalg.norm(result[:3, 0]) + result[:3, 1] /= np.linalg.norm(result[:3, 1]) + result[:3, 2] /= np.linalg.norm(result[:3, 2]) + return result + + +def auto_global2local( + ifc_file: ifcopenshell.file, matrix: MatrixType, is_specified_in_map_units: bool = True +) -> MatrixType: + """Convert a global map matrix to a local matrix + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the matrix is returned unchanged. + + :param ifc_file: The IFC file + :param matrix: A 4x4 numpy matrix representing local coordinates. + :param should_return_in_map_units: If true, the result is given in map units. + If false, the result will be converted back into project units. + :param is_specified_in_map_units: True if the input matrix is in map units. + :return: A numpy 4x4 array matrix representing global coordinates. + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return matrix.copy() + if not is_specified_in_map_units: + matrix = matrix.copy() + matrix[:3, 3] *= parameters.scale + result = global2local(matrix, *parameters) + wcs = get_wcs(ifc_file) + if wcs is not None: + return wcs @ result + return result + + +def xaxis2angle(x: float, y: float) -> float: + """Converts X axis abscissa and ordinates to an angle in decimal degrees + + The X axis abscissa and ordinate is how IFC stores grid north. + + This X axis vector indicates "where is project east, if grid north is up + the page?". See the diagram on the IfcGeometricRepresentationContext + documentation for clarification. + + The angle indicates "how do I rotate project east to get to grid east?". + Alternatively: "how do I rotate project north to get to grid north?". + Positive angles are anticlockwise. + + :param x: The X axis abscissa + :param y: The X axis ordinate + :return: The equivalent angle in decimal degrees from the X axis + """ + return math.degrees(math.atan2(y, x)) * -1 + + +def yaxis2angle(x: float, y: float) -> float: + """Converts Y axis abscissa and ordinates to an angle in decimal degrees + + The Y axis abscissa and ordinate is how IFC stores true north. + + This Y axis vector indicates "where is true north, if project north is up + the page?". See the diagram on the IfcGeometricRepresentationContext + documentation for clarification. + + The angle indicates "how do I rotate project north to get to true north?". + Positive angles are anticlockwise. + + :param x: The Y axis abscissa + :param y: The Y axis ordinate + :return: The equivalent angle in decimal degrees from the Y axis + """ + angle = math.degrees(math.atan2(y, x)) - 90 + if angle < -180: + angle += 360 + elif angle > 180: + angle -= 360 + return angle + + +def get_grid_north(ifc_file: ifcopenshell.file) -> float: + """Get an angle pointing to map grid north + + Anticlockwise is positive. + + The necessary georeferencing map conversion is automatically detected from + the IFC map conversion parameters present in the IFC model. If no map + conversion is present, then the Z coordinate is returned unchanged. + + For IFC2X3, the map conversion is detected from the IfcProject's + ePSet_MapConversion. See the "User Guide for Geo-referencing in IFC": + https://www.buildingsmart.org/standards/bsi-standards/standards-library/ + + :param ifc_file: The IFC file + :return: An angle to grid north in decimal degrees + """ + parameters = get_helmert_transformation_parameters(ifc_file) + if not parameters: + return 0 + return xaxis2angle(parameters.xaa, parameters.xao) + + +def get_true_north(ifc_file: ifcopenshell.file) -> float: + """Get an angle pointing to global true north + + Anticlockwise is positive. + + Always remember that true north is not a constant! (Unless you are working + in polar coordinates) This true north is only a reference value useful for + things like solar analysis on small sites (<1km). If you're after the north + that your surveyor is using, you're probably after :func:`get_grid_north` + instead. + + :param ifc_file: The IFC file + :return: An angle to true north in decimal degrees + """ + try: + for context in ifc_file.by_type("IfcGeometricRepresentationContext", include_subtypes=False): + if context.TrueNorth: + return yaxis2angle(*context.TrueNorth.DirectionRatios[0:2]) + except: + return 0 + return 0 + + +def angle2xaxis(angle: float) -> tuple[float, float]: + """Converts an angle into an X axis abscissa and ordinate + + The inverse of :func:`xaxis2angle`. + + :param angle: The angle in decimal degrees where anticlockwise is positive. + :return: A tuple of X axis abscissa and ordinate + """ + angle_rad = math.radians(angle) + x = math.cos(angle_rad) + y = -math.sin(angle_rad) + return x, y + + +def angle2yaxis(angle: float) -> tuple[float, float]: + """Converts an angle into an Y axis abscissa and ordinate + + The inverse of :func:`yaxis2angle`. + + :param angle: The angle in decimal degrees where anticlockwise is positive. + :return: A tuple of Y axis abscissa and ordinate + """ + angle_rad = math.radians(angle) + x = -math.sin(angle_rad) + y = math.cos(angle_rad) + return x, y + + +def get_wcs(ifc_file: ifcopenshell.file) -> Optional[MatrixType]: + """Gets the WCS (prioritising 3D contexts) as a matrix + + :param: The IFC file + :return: A 4x4 matrix in project units + """ + wcs = None + for context in ifc_file.by_type("IfcGeometricRepresentationContext", include_subtypes=False): + wcs = context.WorldCoordinateSystem + if context.ContextType == "Model": + break + if wcs: + return ifcopenshell.util.placement.get_axis2placement(wcs) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4_to_brick.json b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4_to_brick.json new file mode 100644 index 0000000000000000000000000000000000000000..d76d2c0c8073e5daae419d4543f9aa3e6e771542 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4_to_brick.json @@ -0,0 +1,35 @@ +{ + "IfcAudioVisualAppliance.CAMERA": "Camera", + "IfcUnitaryEquipment.AIRHANDLER": "AHU", + "IfcBoiler": "Boiler", + "IfcUnitaryEquipment.AIRCONDITIONINGUNIT": "CRAC", + "IfcChiller": "Chiller", + "IfcCompressor": "Compressor", + "IfcCondenser": "Condenser", + "IfcCoolingTower": "Cooling_Tower", + "IfcDamper": "Damper", + "IfcFan": "Fan", + "IfcFilter": "Filter", + "IfcHeatExchanger": "Heat_Exchanger", + "IfcHumidifier": "Humidifier", + "IfcPump": "Pump", + "IfcAirTerminalBox": "TerminalUnit", + "IfcAirTerminalBox.CONSTANTFLOW": "CAV", + "IfcAirTerminalBox.VARIABLEFLOWPRESSUREDEPENDANT": "VAV", + "IfcAirTerminalBox.VARIABLEFLOWPRESSUREINDEPENDANT": "VAV", + "IfcValve": "Valve", + "IfcUnitaryControlElement.THERMOSTAT": "Thermostat", + "IfcUnitaryControlElement.WEATHERSTATION": "Weather_Station", + "IfcLightFixture": "Luminaire", + "IfcFlowMeter": "Meter", + "IfcFlowMeter.ENERGYMETER": "Electric_Meter", + "IfcFlowMeter.GASMETER": "Gas_Meter", + "IfcFlowMeter.WATERMETER": "Water_Meter", + "IfcElectricMotor": "Motor", + "IfcSolarDevice.SOLARPANEL": "PV_Panel", + "IfcBuilding": "https://w3id.org/rec#Building", + "IfcBuildingStorey": "https://w3id.org/rec#Level", + "IfcSpace": "https://w3id.org/rec#Room", + "IfcSpatialZone": "https://w3id.org/rec#Zone", + "IfcSpatialZone.THERMAL": "https://w3id.org/rec#HVACZone" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4x3dev_scrape_data_for_docs.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4x3dev_scrape_data_for_docs.py new file mode 100644 index 0000000000000000000000000000000000000000..02e4f1f4913cbb3c4b5aebac7a16146b19a53fc9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/ifc4x3dev_scrape_data_for_docs.py @@ -0,0 +1,219 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +try: + from server import get_resource_path, resource_documentation_builder, process_markdown, R +except ModuleNotFoundError as e: + print( + "ERROR. Failed to import `server.py`.\n" + "Make sure you run this script from `/code` folder of https://github.com/buildingSMART/IFC4.3.x-development\n" + ) + raise e + +import itertools +import operator +import json +import ifcopenshell +from collections import Counter +from bs4 import BeautifulSoup +from typing import Any, Union + + +# Hacky modified functions from server.py to make parser work +def get_definition_from_md(resource: str, mdc: str) -> str: + # Only match up to the first h2 + lines = [] + for line in mdc.split("\n"): + if line.startswith("## "): + break + if line.startswith("### "): + words = line.split(" ") + line = " ".join((words[0], "", *words[1:])) + lines.append(line) + mdc = "\n".join(lines) + mdc_splitted = mdc.split("\n\n") + return mdc_splitted[1] if len(mdc_splitted) > 1 else "" + + +def get_type_values(resource: str, mdc: str) -> dict[str, Any]: + values = R.type_values.get(resource) + if not values: + return + has_description = values[0] == values[0].upper() + if has_description: + soup = BeautifulSoup(process_markdown(resource, mdc), features="lxml") + described_values = [] + for value in values: + description = None + for h in soup.findAll("h3"): + if h.text != value: + continue + description = BeautifulSoup(features="lxml") + for sibling in h.find_next_siblings(): + if sibling.name == "h3": + break + description.append(sibling) + description = str(description) + described_values.append({"name": value, "description": description}) + values = described_values + return {"number": 0, "has_description": has_description, "schema_values": values} + + +def get_attributes_keep_md(resource, builder): + attrs = builder.attributes + supertype_counts = Counter() + supertype_counts.update([a[0] for a in attrs]) + attrs = [a[1:] for a in attrs] + supertype_counts = list(supertype_counts.items())[::-1] + insertion_points = [0] + list(itertools.accumulate(map(operator.itemgetter(1), supertype_counts[::-1])))[:-1] + group_data = supertype_counts[::-1] + + groups = [] + for i, attr in enumerate(attrs): + if i in insertion_points: + name, total_attributes = group_data[insertion_points.index(i)] + group = { + "name": name, + "attributes": [], + "is_inherited": insertion_points[-1] != i, + "total_attributes": total_attributes, + } + groups.append(group) + + attribute = { + "number": attr[0], + "name": attr[1], + "type": attr[2][0] if isinstance(attr[2], list) else attr[2], + "formal": attr[2][1] if isinstance(attr[2], list) else None, + # @nb we're not really talking about markdown anymore + # since the new attribute parser operates on a converted + # dom, but it appears to work nonetheless. + "description": attr[3], + "is_inverse": not attr[0], + } + if attribute["name"] == "PredefinedType" and not attribute["description"]: + description = "A list of types to further identify the object. Some property sets may be specifically applicable to one of these types." + if "Type" not in group["name"]: + description += "\n> NOTE If the object has an associated IfcTypeObject with a _PredefinedType_, then this attribute shall not be used." + attribute["description"] = description + group["attributes"].append(attribute) + + total_inherited_attributes = sum([g["total_attributes"] for g in groups if g["is_inherited"]]) + + inherited_groups_with_attributes = [g for g in groups if g["is_inherited"] and g["total_attributes"]] + if inherited_groups_with_attributes: + inherited_groups_with_attributes[-1]["is_last_inherited_group"] = True + + return { + "number": None, + "groups": groups, + "total_inherited_attributes": total_inherited_attributes, + } + + +# ------------------------- + +# Temporary fix for https://github.com/buildingSMART/IFC4.3.x-development/issues/754. +_original_get_resource_path = get_resource_path + + +def get_resource_path(resource: str, abort_on_error=False) -> Union[str, None]: + md = _original_get_resource_path(resource, abort_on_error) + if md and resource == "IfcURIReference": + md = md.replace("IfcMeasureResource", "IfcExternalReferenceResource") + return md + + +def get_description_json(resource: str) -> str: + md = get_resource_path(resource, abort_on_error=False) + if not md: + raise Exception(f"No resource path found for '{resource}'.") + mdc = open(md, "r", encoding="utf-8").read() + description = get_definition_from_md(resource, mdc) + return description + + +def get_attributes_json(resource): + builder = resource_documentation_builder(resource) + attrs = get_attributes_keep_md(resource, builder) + if not attrs["groups"]: + return [] + attrs = [a for a in attrs["groups"] if a["name"] == resource] + if not attrs: + return [] + + return attrs[0]["attributes"] + + +def get_predefined_type_values_json(resource): + md = get_resource_path(resource, abort_on_error=False) + if not md: + raise Exception(f"No resource path found for '{resource}'.") + mdc = open(md, "r", encoding="utf-8").read() + return get_type_values(resource, mdc)["schema_values"] + + +def save_entities_data(entities: list[str]) -> None: + entities_description = dict() + for entity in entities: + entity_data = dict() + + try: + entity_data["description"] = get_description_json(entity) + except Exception as e: + md = get_resource_path(entity, abort_on_error=False) + if md: + print(f"server returned markdown file path ('{md}') but there was some other parsing error, see below.") + raise e + print( + f"WARNING. Cannot find resource path for `{entity}` in DEV DOCUMENTATION even though it's present in ifcopenshell schema. It will be skipped." + ) + continue + + attrs = get_attributes_json(entity) + attributes_data = dict() + predefined_types_data = dict() + for a in attrs: + if a["name"] == "PredefinedType": + predefined_type_name_enum = a["type"].split()[-1] + predef_values = get_predefined_type_values_json(predefined_type_name_enum) + for v in predef_values: + description = v["description"] + description = description.strip() if description else "" + if description: + description = BeautifulSoup(description, features="lxml").find("p").text + predefined_types_data[v["name"]] = description + continue + + description = a["description"] + description = description.strip() if description else "" + if description: + description = BeautifulSoup(description, features="lxml").find("p").text + attributes_data[a["name"]] = description + entity_data["attributes"] = attributes_data + entity_data["predefined_types"] = predefined_types_data + entities_description[entity] = entity_data + + with open("entities_description.json", "w") as fo: + json.dump(entities_description, fo, sort_keys=True, indent=4) + + +if __name__ == "__main__": + schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name("IFC4X3_ADD2") + entities: list[str] = [e.name() for e in schema.declarations()] + save_entities_data(entities) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/mvd_info.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/mvd_info.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ca36039dc737a46e7e3a795e03465ed7bf4693 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/mvd_info.py @@ -0,0 +1,343 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations + +try: + from lark import Lark, Transformer + from lark.exceptions import UnexpectedCharacters, UnexpectedEOF, UnexpectedToken + + LARK_AVAILABLE = True +except ImportError: + LARK_AVAILABLE = False + +from typing import Callable, Union +import re + +if LARK_AVAILABLE: + mvd_grammar = r""" + start: entry+ + + entry: "ViewDefinition" "[" simple_value_list "]" -> view_definition + | "Comment" "[" simple_value_list "]" -> comment + | "ExchangeRequirement" "[" other_keyword "]" -> exchangerequirement + | "Option" "[" other_keyword "]" -> option + | GENERIC_KEYWORD "[" dynamic_option_word "]" -> dynamic_option + + GENERIC_KEYWORD: /[A-Za-z0-9_]+/ + + simple_value_list: value ("," value)* + + value_list_set: value_set (";" value_set)* + + value_set: set_name ":" simple_value_list + + set_name: /[A-Za-z0-9_]+/ + + value: /[A-Za-z0-9 _\.-]+/ + + other_keyword: /[^\[\]]+/ + + dynamic_option_word: /[^\[\]]+/ + + %import common.WS + %ignore WS + """ + + parser = Lark(mvd_grammar, parser="lalr") + + class DescriptionTransform(Transformer): + def __init__(self): + self.view_definitions = [] + self.keywords = set() + self.comments = "" + self.exchange_requirements = "" + self.options = "" + self._dynamic = {} + + def view_definition(self, args): + self.keywords.add("view_definitions") + self.view_definitions.extend(args[0]) + + def store_text_attribute(self, args, keyword): + self.keywords.add(keyword) + setattr(self, keyword, " ".join(" ".join(str(child) for child in args[0].children).split())) + + def comment(self, args): + self.keywords.add("comments") + self.comments = args[0] if len(args[0]) > 1 else args[0][0] + + def exchangerequirement(self, args): + self.store_text_attribute(args, "exchange_requirements") + + def option(self, args): + if v := parse_semicolon_separated_kv(" ".join(" ".join(str(child) for child in args[0].children).split())): + setattr(self, "options", v) + else: + self.store_text_attribute(args, "options") + + def dynamic_option(self, args): + try: + original_keyword = str(args[0]) + key = original_keyword.lower() + raw_text = args[1].children[0].value + parsed_value = parse_semicolon_separated_kv(raw_text) + self._dynamic[key] = (parsed_value, original_keyword) + self.keywords.add(key) + setattr(self, key, parsed_value) + except Exception: + setattr(self, key, None) + + def simple_value_list(self, args): + return [str(arg) for arg in args] + + def value_list_set(self, args): + return args + + def value_set(self, args): + return [str(args[0])] + args[1] + + def value(self, args): + return str(args[0]) + + def set_name(self, args): + return str(args[0]) + + def parse_mvd(description): + text = " ".join(description) + parsed_description = DescriptionTransform() + try: + if not text: + parsed_description.view_definitions = None + return parsed_description + parse_tree = parser.parse(text) + parsed_description.transform(parse_tree) + except (UnexpectedCharacters, UnexpectedEOF, UnexpectedToken): + parsed_description.view_definitions = None + return parsed_description + + def parse_semicolon_separated_kv(text: str) -> dict[str, str | list[str]] | None: + if not re.search(r"\w+\s*:\s*[^:]+", text): + return None + result = {} + try: + pairs = text.split(";") + for pair in pairs: + if ":" in pair: + key, value = pair.split(":", 1) + key = key.strip() + values = [v.strip() for v in value.split(",")] + result[key] = values[0] if len(values) == 1 else values + return result + except Exception: + return None + +else: + + def parse_mvd(description): + return None + + +class MvdInfo: + def __init__(self, header): + self._header = header + self._parsed = None + + def _ensure_parsed(self): + if not LARK_AVAILABLE: + return + if self._parsed is None: + self._parsed = parse_mvd(self._header.file_description.description) + + @property + def description(self) -> list[str]: + return self._header.file_description.description + + @description.setter + def description(self, new_description: list[str]): + self._header.file_description.description = tuple(new_description) + self._parsed = None + + @property + def view_definitions(self): + self._ensure_parsed() + if not self._parsed or self._parsed.view_definitions is None: + return None # + + vd = self._parsed.view_definitions + vd_list = vd if isinstance(vd, list) else [vd] if vd else [] + return AutoCommitList( + vd_list, + callback=lambda val: (self._update_keyword("ViewDefinition", val), setattr(self, "_parsed", None)), + formatter=lambda lst: ",".join(str(i) for i in lst), + ) + + @view_definitions.setter + def view_definitions(self, new_value: Union[str, list[str]]): + if isinstance(new_value, list): + value = ", ".join(new_value) + else: + value = str(new_value) + self._update_keyword("ViewDefinition", value) + + @property + def comments(self): + self._ensure_parsed() + comments = self._parsed.comments + comment_list = comments if isinstance(comments, list) else [comments] if comments else [] + return AutoCommitList( + comment_list, + callback=lambda val: self._update_keyword("Comment", val), + formatter=lambda lst: ", ".join(str(i) for i in lst), + ) + + @comments.setter + def comments(self, new_value: Union[str, list[str]]): + if isinstance(new_value, list): + value = ", ".join(new_value) + else: + value = str(new_value) + self._update_keyword("Comment", value) + + @property + def exchange_requirements(self): + self._ensure_parsed() + return self._parsed.exchange_requirements if self._parsed else None + + @exchange_requirements.setter + def exchange_requirements(self, new_value: str): + self._update_keyword("ExchangeRequirement", new_value) + + @property + def options(self): + self._ensure_parsed() + if isinstance(self._parsed.options, dict): + return DictionaryHandler(self._parsed.options, self, "Option") + return self._parsed.options if self._parsed else None + + @options.setter + def options(self, new_value: str): + self._update_keyword("Option", new_value) + + @property + def keywords(self): + self._ensure_parsed() + return self._parsed.keywords if self._parsed else set() + + def _update_keyword(self, keyword: str, new_value: str): + updated = False + new_line = f"{keyword} [{new_value}]" + lines = [] + for line in self.description: + if line.strip().startswith(f"{keyword} ["): + lines.append(new_line) + updated = True + else: + lines.append(line) + if not updated: + lines.append(new_line) + self.description = lines + + def __getattr__(self, name): + self._ensure_parsed() + if hasattr(self._parsed, "_dynamic"): + name_lc = name.lower() + if name_lc in self._parsed._dynamic: + value, original_keyword = self._parsed._dynamic[name_lc] + return DictionaryHandler(value, self, original_keyword) + raise AttributeError(f"'MvdInfo' object has no attribute '{name}'") + + def __dir__(self): + base = super().__dir__() + if self._parsed and hasattr(self._parsed, "_dynamic"): + return base + [kw for _, kw in self._parsed._dynamic.values()] + return base + + +class DictionaryHandler(dict): + def __init__(self, initial_data, mvdinfo, keyword): + super().__init__() + self._mvdinfo = mvdinfo + self._keyword = keyword + for k, v in initial_data.items(): + if isinstance(v, list): + super().__setitem__(k, AutoCommitList(v, self._commit)) + else: + super().__setitem__(k, v) + + def _commit(self): + new_value = "; ".join(f"{k}: {', '.join(v) if isinstance(v, list) else v}" for k, v in self.items()) + self._mvdinfo._update_keyword(self._keyword, new_value) + + def __setitem__(self, key, value): + if isinstance(value, list): + value = AutoCommitList(value, self._commit) + super().__setitem__(key, value) + self._commit() + + def __delitem__(self, key): + super().__delitem__(key) + self._commit() + + +class AutoCommitList(list): + "ensures keyword attributes are written back to ifcopenshell.file.header" + + def __init__(self, iterable, callback, formatter=None): + super().__init__(iterable) + self._callback = callback + self._formatter = formatter + + def _commit(self): + if self._formatter: + self._callback(self._formatter(self)) + else: + self._callback() + + def append(self, item): + super().append(item) + self._commit() + + def extend(self, iterable): + super().extend(iterable) + self._commit() + + def insert(self, index, item): + super().insert(index, item) + self._commit() + + def remove(self, item): + super().remove(item) + self._commit() + + def pop(self, index=-1): + item = super().pop(index) + self._commit() + return item + + def clear(self): + super().clear() + self._commit() + + def __setitem__(self, index, value): + super().__setitem__(index, value) + self._commit() + + def __delitem__(self, index): + super().__delitem__(index) + self._commit() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/placement.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/placement.py new file mode 100644 index 0000000000000000000000000000000000000000..e7e7b99a682822d3403f41b0fbf75609be1d70d4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/placement.py @@ -0,0 +1,235 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import numpy.typing as npt +import ifcopenshell +from typing import Literal, Optional +from collections.abc import Iterable + +MatrixType = npt.NDArray[np.float64] +"""`npt.NDArray[np.float64]`""" + + +def a2p(o: Iterable[float], z: Iterable[float], x: Iterable[float]) -> MatrixType: + """Converts a location, X, and Z axis vector to a 4x4 transformation matrix + + IFC uses a right-handed coordinate system, so it is not necessary to + provide the Y axis. + + :param o: The origin (i.e. location) of the matrix + :param z: The +Z vector / axis of the matrix + :param x: The +X vector / axis of the matrix + :return: A 4x4 numpy matrix + """ + x = x / np.linalg.norm(x) + z = z / np.linalg.norm(z) + y = np.cross(z, x) + y = y / np.linalg.norm(y) + r = np.eye(4) + r[:-1, :-1] = x, y, z + r[-1, :-1] = o + return r.T + + +def get_axis2placement(placement: ifcopenshell.entity_instance) -> MatrixType: + """Parses an IfcAxis2Placement (2D or 3D) to a 4x4 transformation matrix + + Note that this function only parses a single placement axis. If you want to + get the placement of an element instead, element placements often are made + out of multiple placement axes or other alternative placement methods. You + should use ``get_local_placement`` instead. + + :param placement: The IfcLocalPlacement enitity + :return: A 4x4 numpy matrix + """ + ifc_class = placement.is_a() + if ifc_class in ("IfcAxis2Placement3D", "IfcAxis2PlacementLinear"): + z = np.array(placement.Axis.DirectionRatios if placement.Axis else (0, 0, 1)) + x = np.array(placement.RefDirection.DirectionRatios if placement.RefDirection else (1, 0, 0)) + location = placement.Location + if coordinates := getattr(location, "Coordinates", None): + o = coordinates + else: + import ifcopenshell.geom + + settings = ifcopenshell.geom.settings() + settings.set("convert-back-units", True) + shape = ifcopenshell.geom.create_shape(settings, placement) + return np.array(shape.matrix).reshape((4, 4), order="F") + elif ifc_class == "IfcAxis2Placement2D": + z = np.array((0, 0, 1)) + if placement.RefDirection: + x = np.array(placement.RefDirection.DirectionRatios) + x.resize(3) + else: + x = np.array((1, 0, 0)) + o = (*placement.Location.Coordinates, 0.0) + + elif ifc_class == "IfcAxis1Placement": + axis = placement.Axis + z = np.array(axis.DirectionRatios if axis else (0, 0, 1)) + x = np.array((1, 0, 0)) + o = placement.Location.Coordinates + + return a2p(o, z, x) + + +def get_local_placement(placement: Optional[ifcopenshell.entity_instance] = None) -> MatrixType: + """Parse a local placement into a 4x4 transformation matrix + + This is typically used to find the location and rotation of an element. The + transformation matrix takes the form of: + + .. code:: + + [ [ x_x, y_x, z_x, x ] + [ x_y, y_y, z_y, y ] + [ x_z, y_z, z_z, z ] + [ 0.0, 0.0, 0.0, 1.0 ] ] + + Example: + + .. code:: python + + placement = file.by_type("IfcBeam")[0].ObjectPlacement + matrix = ifcopenshell.util.placement.get_local_placement(placement) + + :param placement: The IfcLocalPlacement entity + :return: A 4x4 numpy matrix + """ + if placement is None: + return np.eye(4) + if (rel_to := placement.PlacementRelTo) is None: + parent = np.eye(4) + else: + parent = get_local_placement(rel_to) + return np.dot(parent, get_axis2placement(placement.RelativePlacement)) + + +def get_cartesiantransformationoperator3d(inst: ifcopenshell.entity_instance) -> MatrixType: + """Parses an IfcCartesianTransformationOperator into a 4x4 transformation matrix + + Note that in general you will not need to call this directly. See + ``get_mappeditem_transformation`` instead. + + :param item: The IfcCartesianTransformationOperator entity + :return: A 4x4 numpy transformation matrix + """ + origin = np.array(inst.LocalOrigin.Coordinates) + axis1 = np.array((1.0, 0.0, 0.0)) + axis2 = np.array((0.0, 1.0, 0.0)) + axis3 = np.array((0.0, 0.0, 1.0)) + + if inst.Axis1: + axis1[0:3] = inst.Axis1.DirectionRatios + if inst.Axis2: + axis2[0:3] = inst.Axis2.DirectionRatios + if inst.Axis3: + axis3[0:3] = inst.Axis3.DirectionRatios + + m4 = a2p(origin, axis3, axis1) + # Negate axis2 (introduce mirroring) when supplied axis2 + # is opposite of constructed axis2, but remains orthogonal + if m4.T[1][0:3].dot(axis2) < 0.0: + m4.T[1] *= -1.0 + + scale1 = scale2 = scale3 = 1.0 + + if inst.Scale: + scale1 = inst.Scale + + if inst.is_a("IfcCartesianTransformationOperator3DnonUniform"): + scale2 = inst.Scale2 if inst.Scale2 is not None else scale1 + scale3 = inst.Scale3 if inst.Scale3 is not None else scale1 + else: + scale2 = scale3 = scale1 + + m4.T[0] *= scale1 + m4.T[1] *= scale2 + m4.T[2] *= scale3 + + return m4 + + +def get_mappeditem_transformation(item: ifcopenshell.entity_instance) -> MatrixType: + """Parse an IfcMappedItem into a 4x4 transformation matrix + + Mapped items take a representation with an origin and transform them with a + cartesian transformation operation. This function returns the final + transformation matrix. + + :param item: The IfcMappedItem entity + :return: A 4x4 numpy transformation matrix + """ + m4 = get_axis2placement(item.MappingSource.MappingOrigin) + # TODO 2d + if item.MappingTarget.is_a("IfcCartesianTransformationOperator3D"): + return get_cartesiantransformationoperator3d(item.MappingTarget) @ m4 + + +def get_storey_elevation(storey: ifcopenshell.entity_instance) -> float: + """Get the Z elevation in project units of a buildling storey + + Building storeys store elevation in two possible locations: the Z value of + its placement, or as a fallback the ``Elevation`` attribute. + + :param storey: The IfcBuildingStorey entity + :return: The elevation in project units + """ + if storey.ObjectPlacement: + matrix = get_local_placement(storey.ObjectPlacement) + return matrix[2][3] + return getattr(storey, "Elevation", 0.0) or 0.0 + + +def rotation(angle: float, axis: Literal["X", "Y", "Z"], is_degrees=True) -> MatrixType: + """Create a 4x4 numpy matrix representing an euler rotation + + :param angle: The angle of rotation + :param axis: The axis to rotate around, either X, Y, or Z. + :param is_degrees: Whether or not the angle is specified in degrees or + radians. Defaults to true (i.e. degrees). + :return: A 4x4 numpy rotation matrix + """ + theta = np.radians(angle) if is_degrees else angle + cos, sin = np.cos(theta), np.sin(theta) + + # fmt: off + if axis == "X": + return np.array([ + [1, 0, 0, 0], + [0, cos, -sin, 0], + [0, sin, cos, 0], + [0, 0, 0, 1] + ]) + elif axis == "Y": + return np.array([ + [cos, 0, sin, 0], + [0, 1, 0, 0], + [-sin, 0, cos, 0], + [0, 0, 0, 1] + ]) + elif axis == "Z": + return np.array([ + [cos, -sin, 0, 0], + [sin, cos, 0, 0], + [0, 0, 1, 0], + [0, 0, 0, 1] + ]) + # fmt: on diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/profiler.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..2228a54a6a126bc0eb9ec5af69e5131c91a26998 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/profiler.py @@ -0,0 +1,35 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +from timeit import default_timer as timer + + +class Profiler: + """ + A python context manager timing utility, useful for measure functions performances + """ + + def __init__(self, task): + self.task = task + + def __enter__(self): + self.start = timer() + + def __exit__(self, *args): + print(f"{self.task} {timer() - self.start:.6f} s") diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/pset.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/pset.py new file mode 100644 index 0000000000000000000000000000000000000000..df906a2e57efc49eb64e999b2cb444339091c1db --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/pset.py @@ -0,0 +1,249 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import re +import pathlib +import ifcopenshell +import ifcopenshell.ifcopenshell_wrapper as W +import ifcopenshell.util.schema +import ifcopenshell.util.type +from ifcopenshell.entity_instance import entity_instance +from functools import lru_cache +from typing import Optional, Literal, NamedTuple, Union + +templates: dict[ifcopenshell.util.schema.IFC_SCHEMA, "PsetQto"] = {} + + +def get_template(schema_identiier: str) -> "PsetQto": + """ + :param schema_identiier: As in ``file.schema_identifier``, not ``file.schema``. + """ + global templates + schema = ifcopenshell.util.schema.get_fallback_schema(schema_identiier) + if schema not in templates: + templates[schema] = PsetQto(schema) + return templates[schema] + + +class PsetQto: + # fmt: off + templates_path: dict[ifcopenshell.util.schema.IFC_SCHEMA, str] = { + "IFC2X3": "Pset_IFC2X3.ifc", + "IFC4": "Pset_IFC4_ADD2.ifc", + "IFC4X3": "Pset_IFC4X3.ifc" + } + # fmt: on + templates: list[ifcopenshell.file] + + def __init__( + self, + schema: ifcopenshell.util.schema.IFC_SCHEMA, + templates: Optional[list[ifcopenshell.file]] = None, + ) -> None: + self.schema = ifcopenshell.schema_by_name(schema) + if not templates: + folder_path = pathlib.Path(__file__).parent.absolute() + path = str(folder_path.joinpath("schema", self.templates_path[schema])) + ifc_file: ifcopenshell.file = ifcopenshell.open(path) + templates = [ifc_file] + # See bug 3583. We backport this change from IFC4X3 because it just makes sense. + # Users aren't forced to use it. + if schema == "IFC4": + for element in templates[0].by_type("IfcPropertySetTemplate"): + if element.TemplateType == "QTO_OCCURRENCEDRIVEN": + element.TemplateType = "QTO_TYPEDRIVENOVERRIDE" + self.templates = templates + + @lru_cache + def get_applicable( + self, + ifc_class="", + predefined_type="", + pset_only=False, + qto_only=False, + schema: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4", + ) -> list[entity_instance]: + """Get applicable property set templates.""" + any_class = not ifc_class + entity = None + if not any_class: + entity = self.schema.declaration_by_name(ifc_class).as_entity() + assert entity + result = [] + for template in self.templates: + for prop_set in template.by_type("IfcPropertySetTemplate"): + if pset_only: + if prop_set.TemplateType and prop_set.TemplateType.startswith("QTO_"): + continue + if qto_only: + if prop_set.TemplateType and prop_set.TemplateType.startswith("PSET_"): + continue + if any_class or ( + entity + and self.is_applicable( + entity, prop_set.ApplicableEntity or "IfcRoot", predefined_type, prop_set.TemplateType, schema + ) + ): + result.append(prop_set) + return result + + @lru_cache + def get_applicable_names( + self, + ifc_class: str, + predefined_type: str = "", + pset_only: bool = False, + qto_only: bool = False, + schema: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4", + ) -> list[str]: + """Return names instead of objects for other use eg. enum""" + return [ + prop_set.Name for prop_set in self.get_applicable(ifc_class, predefined_type, pset_only, qto_only, schema) + ] + + def is_applicable( + self, + entity: W.entity, + applicables: str, + predefined_type: str = "", + template_type: str = "NOTDEFINED", + schema: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4", + ) -> bool: + """ + + applicables can have multiple possible patterns : + + .. code-block:: text + + IfcBoilerType (IfcClass) + IfcBoilerType/STEAM (IfcClass/PREDEFINEDTYPE) + IfcBoilerType[PerformanceHistory] (IfcClass[PerformanceHistory]) + IfcBoilerType/STEAM[PerformanceHistory] (IfcClass/PREDEFINEDTYPE[PerformanceHistory]) + + """ + for applicable in applicables.split(","): + match = re.match(r"(\w+)(\[\w+\])*/*(\w+)*(\[\w+\])*", applicable) + if not match: + continue + # Uncomment if usage found + # applicable_perf_history = match.group(2) or match.group(4) + matched_type = match.group(3) + if matched_type and not predefined_type: + continue + # Case insensitive to handle things like material categories + elif matched_type and predefined_type.lower() != match.group(3).lower(): + continue + + applicable_class = match.group(1) + if ifcopenshell.util.schema.is_a(entity, applicable_class): + return True + # There is an implementer agreement that if the template type is + # type based, the type need not be explicitly mentioned + # https://github.com/buildingSMART/IFC4.3.x-development/issues/22 + # This will be fixed in IFC4.3 + template_type = template_type or "" + if "TYPE" in template_type and ifcopenshell.util.schema.is_a(entity, "IfcTypeObject"): + types = ifcopenshell.util.type.get_applicable_types(applicable_class, schema) + if not types: + # Abstract classes will not have an "applicable type" but + # the implementer agreement still applies to them. + occurrence_class = None + try: + occurrence_class = self.schema.declaration_by_name(applicable_class + "Type") + except: + try: + occurrence_class = self.schema.declaration_by_name("IfcType" + applicable_class[3:]) + except: + pass + if occurrence_class: + types = [occurrence_class.name()] + for ifc_type in types: + if ifcopenshell.util.schema.is_a(entity, ifc_type): + return True + return False + + @lru_cache + def get_by_name(self, name: str) -> Optional[entity_instance]: + for template in self.templates: + for prop_set in template.by_type("IfcPropertySetTemplate"): + if prop_set.Name == name: + return prop_set + return None + + def is_templated(self, name: str) -> bool: + return bool(self.get_by_name(name)) + + +def get_pset_template_type(pset_template: entity_instance) -> Literal["PSET", "QTO", None]: + """Get the type of the pset template. + If type is mixed or not defined, return None.""" + + # Try to identify whether it's pset or qto from the template type. + template_type = pset_template.TemplateType + if template_type: + if template_type.startswith("PSET_"): + return "PSET" + elif template_type.startswith("QTO_"): + return "QTO" + # Can also be 'NOTDEFINED'. + + pset_types = set() + for prop in pset_template.HasPropertyTemplates: + prop_template_type = prop.TemplateType + if prop_template_type: + if prop_template_type.startswith("P_"): + pset_types.add("PSET") + else: # All other values are Q_. + pset_types.add("QTO") + + pset_type = next(iter(pset_types)) if len(pset_types) == 1 else None + return pset_type + + +class ApplicableEntity(NamedTuple): + value: str + ifc_class: str + predefined_type: Union[str, None] + performance_history: bool + + +def parse_applicable_entity(applicable_entity: str) -> list[ApplicableEntity]: + """Parse ApplicableEntity string query to tuples. + + :param applicable_entity: IfcPropertySetTemplate.ApplicableEntity query. + :return: List of ApplicableEntity tuples. + """ + items: list[ApplicableEntity] = [] + for item in applicable_entity.split(","): + value = item + item, predefined_type = parts if len(parts := item.split("/")) > 1 else (item, None) + ifc_class, performance_history = (parts[0], True) if len(parts := item.split("[")) > 1 else (item, False) + items.append(ApplicableEntity(value, ifc_class, predefined_type, performance_history)) + return items + + +def convert_applicable_entities_to_query(applicable_entities: list[ApplicableEntity]) -> str: + """Get query supported by :func:`ifcopenshell.util.selector.filter_elements`.""" + parts: list[str] = [] + for entity in applicable_entities: + # NOTE: selector currently doesn't support checking if element has performance history. + part = entity.ifc_class + if entity.predefined_type: + part += f', PredefinedType="{entity.predefined_type}"' + parts.append(part) + return " + ".join(parts) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/representation.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/representation.py new file mode 100644 index 0000000000000000000000000000000000000000..10743294b06cbad2c29efdc5abd3d481d40f01a4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/representation.py @@ -0,0 +1,522 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import numpy as np +import numpy.typing as npt +import ifcopenshell +import ifcopenshell.util.representation +import ifcopenshell.util.placement +import ifcopenshell.util.shape +from typing import Optional, Union, TypedDict, Literal +from collections.abc import Generator, Sequence + + +CONTEXT_TYPE = Literal["Model", "Plan", "NotDefined"] +REPRESENTATION_IDENTIFIER = Literal[ + "CoG", + "Box", + "Annotation", + "Axis", + "FootPrint", + "Profile", + "Surface", + "Reference", + "Body", + "Body-Fallback", + "Clearance", + "Lighting", +] +TARGET_VIEW = Literal[ + "ELEVATION_VIEW", + "GRAPH_VIEW", + "MODEL_VIEW", + "PLAN_VIEW", + "REFLECTED_PLAN_VIEW", + "SECTION_VIEW", + "SKETCH_VIEW", + "USERDEFINED", + "NOTDEFINED", +] + + +def get_context( + ifc_file: ifcopenshell.file, + context: CONTEXT_TYPE, + subcontext: Optional[REPRESENTATION_IDENTIFIER] = None, + target_view: Optional[TARGET_VIEW] = None, +) -> Union[ifcopenshell.entity_instance, None]: + """Get IfcGeometricRepresentationSubContext by the provided context type, identifier, and target view. + + :param context: ContextType. + :param subcontext: A ContextIdentifier string, or any if left blank. + :param target_view: A TargetView string, or any if left blank. + """ + + if subcontext or target_view: + elements = ifc_file.by_type("IfcGeometricRepresentationSubContext") + else: + elements = ifc_file.by_type("IfcGeometricRepresentationContext", include_subtypes=False) + for element in elements: + if context and element.ContextType != context: + continue + if subcontext and getattr(element, "ContextIdentifier") != subcontext: + continue + if target_view and getattr(element, "TargetView") != target_view: + continue + return element + + +def is_representation_of_context( + representation: ifcopenshell.entity_instance, + context: Union[ifcopenshell.entity_instance, CONTEXT_TYPE], + subcontext: Optional[REPRESENTATION_IDENTIFIER] = None, + target_view: Optional[TARGET_VIEW] = None, +) -> bool: + """Check if representation has specified context or context type, identifier, and target view. + + :param representation: IfcShapeRepresentation. + :param context: Either a specific IfcGeometricRepresentationContext or a ContextType. + :param subcontext: A ContextIdentifier string, or any if left blank. + :param target_view: A TargetView string, or any if left blank. + """ + + if isinstance(context, ifcopenshell.entity_instance): + return representation.ContextOfItems == context + + if target_view is not None: + return ( + representation.ContextOfItems.is_a("IfcGeometricRepresentationSubContext") + and representation.ContextOfItems.TargetView == target_view + and representation.ContextOfItems.ContextIdentifier == subcontext + and representation.ContextOfItems.ContextType == context + ) + elif subcontext is not None: + return ( + representation.ContextOfItems.is_a("IfcGeometricRepresentationSubContext") + and representation.ContextOfItems.ContextIdentifier == subcontext + and representation.ContextOfItems.ContextType == context + ) + + return representation.ContextOfItems.ContextType == context + + +def get_representations_iter( + element: ifcopenshell.entity_instance, +) -> Generator[ifcopenshell.entity_instance, None, None]: + """Get an iterator with element's IfcShapeRepresentations. + + :param element: An IfcProduct or IfcTypeProduct + """ + if element.is_a("IfcProduct") and (rep := element.Representation): + for r in rep.Representations: + yield r + elif element.is_a("IfcTypeProduct") and (maps := element.RepresentationMaps): + for r in maps: + yield r.MappedRepresentation + + +def get_representation( + element: ifcopenshell.entity_instance, + context: Union[ifcopenshell.entity_instance, CONTEXT_TYPE], + subcontext: Optional[REPRESENTATION_IDENTIFIER] = None, + target_view: Optional[TARGET_VIEW] = None, +) -> Union[ifcopenshell.entity_instance, None]: + """Gets a IfcShapeRepresentation filtered by the context type, identifier, and target view + + :param element: An IfcProduct or IfcTypeProduct + :param context: Either a specific IfcGeometricRepresentationContext or a ContextType + :param subcontext: A ContextIdentifier string, or any if left blank. + :param target_view: A TargetView string, or any if left blank. + :return: The first IfcShapeRepresentation matching the criteria. + """ + for r in get_representations_iter(element): + if is_representation_of_context(r, context, subcontext, target_view): + return r + + +def guess_type(items: Sequence[ifcopenshell.entity_instance]) -> Union[str, None]: + """Guesses the appropriate RepresentationType attribute based on a list of items + + :param items: A list of IfcRepresentationItem, typically in an IfcShapeRepresentation + :return: The appropriate RepresentationType value, or None if no valid value + """ + if all([True if i.is_a("IfcMappedItem") else False for i in items]): + return "MappedRepresentation" + elif all([True if i.is_a("IfcPoint") or i.is_a("IfcCartesianPointList") else False for i in items]): + return "Point" + elif all([True if i.is_a("IfcCartesianPointList3d") else False for i in items]): + return "PointCloud" + elif all([True if i.is_a("IfcCurve") and i.Dim == 2 else False for i in items]): + return "Curve2D" + elif all([True if i.is_a("IfcCurve") and i.Dim == 3 else False for i in items]): + return "Curve3D" + elif all([True if i.is_a("IfcCurve") else False for i in items]): + return "Curve" + elif all([True if i.is_a("IfcSegment") else False for i in items]): + return "Segment" + elif all([True if i.is_a("IfcSurface") and i.Dim == 2 else False for i in items]): + return "Surface2D" + elif all([True if i.is_a("IfcSurface") and i.Dim == 3 else False for i in items]): + return "Surface3D" + elif all([True if i.is_a("IfcSurface") else False for i in items]): + return "Surface" + elif all([True if i.is_a("IfcSectionedSurface") else False for i in items]): + return "SectionedSurface" + elif all([True if i.is_a("IfcAnnotationFillArea") else False for i in items]): + return "FillArea" + elif all([True if i.is_a("IfcTextLiteral") else False for i in items]): + return "Text" + elif all([True if i.is_a("IfcBSplineSurface") else False for i in items]): + return "AdvancedSurface" + elif all( + [ + ( + True + if i.is_a("IfcGeometricSet") or i.is_a("IfcPoint") or i.is_a("IfcCurve") or i.is_a("IfcSurface") + else False + ) + for i in items + ] + ): + return "GeometricSet" + elif all( + [ + ( + True + if i.is_a("IfcGeometricCurveSet") + or (i.is_a("IfcGeometricSet") and all([e.is_a("IfcSurface") for e in i.Elements])) + or i.is_a("IfcPoint") + or i.is_a("IfcCurve") + else False + ) + for i in items + ] + ): + return "GeometricCurveSet" + elif all( + [ + ( + True + if i.is_a("IfcPoint") + or i.is_a("IfcCurve") + or i.is_a("IfcGeometricCurveSet") + or i.is_a("IfcAnnotationFillArea") + or i.is_a("IfcTextLiteral") + else False + ) + for i in items + ] + ): + return "Annotation2D" + elif all([True if i.is_a("IfcTessellatedItem") else False for i in items]): + return "Tessellation" + elif all( + [ + ( + True + if i.is_a("IfcTessellatedItem") + or i.is_a("IfcShellBasedSurfaceModel") + or i.is_a("IfcFaceBasedSurfaceModel") + else False + ) + for i in items + ] + ): + return "SurfaceModel" + elif all( + [True if i.is_a() == "IfcExtrudedAreaSolid" or i.is_a() == "IfcRevolvedAreaSolid" else False for i in items] + ): + return "SweptSolid" + elif all([True if i.is_a("IfcSolidModel") else False for i in items]): + return "SolidModel" + elif all( + [ + ( + True + if i.is_a("IfcTessellatedItem") + or i.is_a("IfcShellBasedSurfaceModel") + or i.is_a("IfcFaceBasedSurfaceModel") + or i.is_a("IfcSolidModel") + else False + ) + for i in items + ] + ): + return "SurfaceOrSolidModel" + elif all( + [ + ( + True + if i.is_a("IfcSweptAreaSolid") or i.is_a("IfcSweptDiskSolid") or i.is_a("IfcSectionedSolidHorizontal") + else False + ) + for i in items + ] + ): + return "AdvancedSweptSolid" + elif all([True if i.is_a("IfcCsgSolid") or i.is_a("IfcBooleanClippingResult") else False for i in items]): + return "Clipping" + elif all( + [ + True if i.is_a("IfcBooleanResult") or i.is_a("IfcCsgPrimitive3d") or i.is_a("IfcCsgSolid") else False + for i in items + ] + ): + return "CSG" + elif all([True if i.is_a("IfcFacetedBrep") else False for i in items]): + return "Brep" + elif all([True if i.is_a("IfcManifoldSolidBrep") else False for i in items]): + return "AdvancedBrep" + elif all([True if i.is_a("IfcBoundingBox") else False for i in items]): + return "BoundingBox" + elif all([True if i.is_a("IfcSectionedSpine") else False for i in items]): + return "SectionedSpine" + elif all([True if i.is_a("IfcLightSource") else False for i in items]): + return "LightSource" + elif all([True if i.is_a("IfcVertex") else False for i in items]): + return "Vertex" + elif all([True if i.is_a("IfcEdge") else False for i in items]): + return "Edge" + elif all([True if i.is_a("IfcPath") else False for i in items]): + return "Path" + elif all([True if i.is_a("IfcFace") else False for i in items]): + return "Face" + elif all([True if i.is_a("IfcOpenShell") else False for i in items]): + return "Shell" + + +def resolve_representation(representation: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + """Resolve possibly mapped representation. + + :param representation: IfcRepresentation + :return: Representation resolved from mappings + """ + # Tekla 2023 has missing items and mapped representation, though it's invalid IFC. + if ( + len(representation.Items or []) == 1 + and representation.Items[0].is_a("IfcMappedItem") + and (mapped_rep := representation.Items[0].MappingSource.MappedRepresentation) + ): + return resolve_representation(mapped_rep) + return representation + + +class ResolvedItemDict(TypedDict): + matrix: npt.NDArray[np.float64] + item: ifcopenshell.entity_instance + + +def resolve_items( + representation: ifcopenshell.entity_instance, matrix: Optional[npt.NDArray[np.float64]] = None +) -> list[ResolvedItemDict]: + if matrix is None: + matrix = np.eye(4) + results: list[ResolvedItemDict] = [] + for item in representation.Items or []: # Be forgiving of invalid IFCs because Revit :( + if item.is_a("IfcMappedItem"): + rep_matrix = ifcopenshell.util.placement.get_mappeditem_transformation(item) + if not np.allclose(rep_matrix, np.eye(4)): + rep_matrix = rep_matrix @ matrix.copy() + results.extend(resolve_items(item.MappingSource.MappedRepresentation, rep_matrix)) + else: + results.append(ResolvedItemDict(matrix=matrix.copy(), item=item)) + return results + + +def resolve_base_items( + representation: ifcopenshell.entity_instance, +) -> Generator[ifcopenshell.entity_instance, None, None]: + """Resolve representation to it's base items resolving mapped items and boolean results to it's operands.""" + queue: list[ifcopenshell.entity_instance] = list(representation.Items) + while queue: + item = queue.pop() + if item.is_a("IfcMappedItem"): + yield from resolve_base_items(item.MappingSource.MappedRepresentation) + elif item.is_a("IfcBooleanResult"): + queue.append(item.FirstOperand) + queue.append(item.SecondOperand) + else: + yield item + + +def get_prioritised_contexts(ifc_file: ifcopenshell.file) -> list[ifcopenshell.entity_instance]: + """Gets a list of contexts ordered from high priority to low priority + + Models can contain multiple geometric contexts. When visualising models, + you may want to prioritise visualising certain contexts over others, + determined by the context type, identifier, target view, and target scale. + + The default prioritises 3D, then 2D. It then prioritises subcontexts, then + contexts. It then prioritises bodies, then others. It also prioritises + model views, then plan views, then others. + + :param ifc_file: The model containing contexts + :return: A list of IfcGeometricRepresentationContext (or SubContext) from + high priority to low priority. + """ + # Annotation ContextType is to accommodate broken Revit files + # See https://github.com/Autodesk/revit-ifc/issues/187 + type_priority = ["Model", "Plan", "Annotation"] + identifier_priority = [ + "Body", + "Body-FallBack", + "Facetation", + "FootPrint", + "Profile", + "Surface", + "Reference", + "Axis", + "Clearance", + "Box", + "Lighting", + "Annotation", + "CoG", + ] + target_view_priority = [ + "MODEL_VIEW", + "PLAN_VIEW", + "REFLECTED_PLAN_VIEW", + "ELEVATION_VIEW", + "SECTION_VIEW", + "GRAPH_VIEW", + "SKETCH_VIEW", + "USERDEFINED", + "NOTDEFINED", + ] + + def sort_context(context): + priority = [] + + if context.ContextType in type_priority: + priority.append(len(type_priority) - type_priority.index(context.ContextType)) + else: + priority.append(0) + + if context.ContextIdentifier in identifier_priority: + priority.append(len(identifier_priority) - identifier_priority.index(context.ContextIdentifier)) + else: + priority.append(0) + + if getattr(context, "TargetView", None) in target_view_priority: + priority.append(len(target_view_priority) - target_view_priority.index(context.TargetView)) + else: + priority.append(0) + + priority.append(getattr(context, "TargetScale", None) or 0) # Big then small + + return tuple(priority) + + return sorted(ifc_file.by_type("IfcGeometricRepresentationContext"), key=sort_context, reverse=True) + + +def get_part_of_product( + element: ifcopenshell.entity_instance, context: ifcopenshell.entity_instance +) -> Union[ifcopenshell.entity_instance, None]: + """Gets the product definition or representation map of an element + + This is typically used for setting shape aspects. Note that this will + return None for IFC2X3 element types. + + :param element: An IfcProduct or IfcTypeProduct + :param context: A IfcGeometricRepresentationContext + :return: IfcProductRepresentationSelect + """ + if element.is_a("IfcProduct"): + return element.Representation + elif element.is_a("IfcTypeProduct") and element.file.schema != "IFX2X3": + if maps := [r for r in element.RepresentationMaps if r.MappedRepresentation.ContextOfItems == context]: + return maps[0] + + +def get_item_shape_aspect( + representation: ifcopenshell.entity_instance, item: ifcopenshell.entity_instance +) -> Union[ifcopenshell.entity_instance, None]: + """Gets the shape aspect relating to an item + + :param representation: The IfcShapeRepresentation that the item is part of + :param item: The IfcRepresentationItem you want to get the shape aspect of + :return: IfcShapeAspect, or None if none exists + """ + for inverse in item.file.get_inverse(item): + if ( + inverse.is_a("IfcShapeRepresentation") + and inverse.ContextOfItems == representation.ContextOfItems + and (of_shape_aspect := inverse.OfShapeAspect) + ): + return of_shape_aspect[0] + + +def get_material_style( + material: ifcopenshell.entity_instance, context: ifcopenshell.entity_instance, ifc_class: str = "IfcSurfaceStyle" +) -> Union[ifcopenshell.entity_instance, None]: + """Get a presentation style associated with a material + + :param material: the IfcMaterial + :param context: IfcGeometricRepresentationContext that the style belongs to + :param ifc_class: The class name of the type of style you need, typically + IfcSurfaceStyle for 3D styling. + :return: IfcPresentationStyle + """ + if definition_representation := material.HasRepresentation: + for styled_rep in definition_representation[0].Representations: + if styled_rep.ContextOfItems == context: + for item in styled_rep.Items: + for style in item.Styles: + if style.is_a(ifc_class): + return style + + +def get_reference_line(wall: ifcopenshell.entity_instance, fallback_length: float = 1.0) -> list[npt.NDArray]: + """Fetch the reference axis that goes in the +X direction + + A base line will then be offset from this reference line based on the + material usage. From that base line, the layer thicknesses will offset + again, and be extruded to form the body representation. + + :param wall: ifcopenshell.entity_instance + :param fallback_length: If there is no reference axis, assume it starts at + the object placement (i.e. 0.0, 0.0) and extends for this fallback + length along the +X axis. + :return: A list of two 2D coordinates representing the start and end of the + axis. The axis always goes in the +X direction. + """ + if axis := ifcopenshell.util.representation.get_representation(wall, "Plan", "Axis", "GRAPH_VIEW"): + for item in ifcopenshell.util.representation.resolve_representation(axis).Items: + if item.is_a("IfcPolyline"): + points = [p[0] for p in item.Points] + elif item.is_a("IfcIndexedPolyCurve"): + points = item.Points.CoordList + else: + continue + if points[0][0] < points[1][0]: # An axis always goes in the +X direction + return [np.array(points[0]), np.array(points[1])] + return [np.array(points[1]), np.array(points[0])] + elif extrusions := ifcopenshell.util.shape.get_base_extrusions(wall): + for extrusion in extrusions: + profile = extrusion.SweptArea + curve = getattr(profile, "OuterCurve", None) + if not curve: + continue + elif curve.is_a("IfcPolyline"): + x = [p[0][0] for p in curve.Points] + elif curve.is_a("IfcIndexedPolyCurve"): + x = [p[0] for p in curve.Points.CoordList] + else: + continue + return [np.array((min(x), 0.0)), np.array((max(x), 0.0))] + return [np.array((0.0, 0.0)), np.array((fallback_length, 0.0))] diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/resource.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/resource.py new file mode 100644 index 0000000000000000000000000000000000000000..f518a091250f51f5e1ac038a58e59098f5f14f96 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/resource.py @@ -0,0 +1,171 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import ifcopenshell.util.cost +import ifcopenshell.util.element +import ifcopenshell.util.date +from typing import Union, Any + + +PRODUCTIVITY_PSET_DATA = Union[dict[str, Any], None] +# https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcConstructionResource.htm#Table-7.3.3.7.1.3.H +RESOURCES_TO_QUANTITIES: dict[str, tuple[str, ...]] = { + "IfcCrewResource": ("IfcQuantityTime",), + "IfcLaborResource": ("IfcQuantityTime",), + "IfcSubContractResource": ("IfcQuantityTime",), + "IfcConstructionEquipmentResource": ("IfcQuantityTime",), + "IfcConstructionMaterialResource": ( + "IfcQuantityVolume", + "IfcQuantityArea", + "IfcQuantityLength", + "IfcQuantityWeight", + ), + "IfcConstructionProductResource": ("IfcQuantityCount",), +} + + +def get_productivity(resource: ifcopenshell.entity_instance, should_inherit: bool = True) -> PRODUCTIVITY_PSET_DATA: + productivity = ifcopenshell.util.element.get_psets(resource).get("EPset_Productivity", None) + if should_inherit and not productivity: + # Note: This is not part of the Schema - but it makes sense to inherit from parent + productivity = get_parent_productivity(resource) + return productivity + + +def get_parent_productivity(resource: ifcopenshell.entity_instance) -> PRODUCTIVITY_PSET_DATA: + if not resource.Nests: + return + else: + parent_resource = resource.Nests[0].RelatingObject + productivity = ifcopenshell.util.element.get_psets(parent_resource).get("EPset_Productivity", None) + return productivity + + +def get_unit_consumed(productivity: PRODUCTIVITY_PSET_DATA) -> Union[Any, None]: + duration = productivity.get("BaseQuantityConsumed", None) + if not duration: + return + return ifcopenshell.util.date.ifc2datetime(duration) + + +def get_quantity_produced(productivity: PRODUCTIVITY_PSET_DATA) -> float: + if not productivity: + return 0.0 + return productivity.get("BaseQuantityProducedValue", 0.0) + + +def get_quantity_produced_name(productivity: PRODUCTIVITY_PSET_DATA): + if not productivity: + return "" + return productivity.get("BaseQuantityProducedName", "") + + +def get_total_quantity_produced(resource: ifcopenshell.entity_instance, quantity_name_in_process: str) -> float: + def get_product_quantity(product: ifcopenshell.entity_instance, quantity_name: str): + psets = ifcopenshell.util.element.get_psets(product) + for pset in psets.values(): + for name, value in pset.items(): + if name == quantity_name: + return float(value) + + total = 0.0 + products = get_parametric_resource_products(resource) + if quantity_name_in_process == "Count": + total = len(products) + else: + for product in products: + total += get_product_quantity(product, quantity_name_in_process) or 0 + return total + + +def get_parametric_resource_products(resource: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + products = [] + for rel in resource.HasAssignments or []: + if not rel.is_a("IfcRelAssignsToProcess"): + continue + for rel2 in rel.RelatingProcess.HasAssignments or []: + if not rel2.is_a("IfcRelAssignsToProduct"): + continue + products.append(rel2.RelatingProduct) + return products + + +def get_task_assignments(resource: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + for rel in resource.HasAssignments or []: + if not rel.is_a("IfcRelAssignsToProcess"): + continue + return rel.RelatingProcess + + +def get_resource_required_work(resource: ifcopenshell.entity_instance) -> Union[str, None]: + productivity = get_productivity(resource) + if productivity: + quantity_produced = get_quantity_produced(productivity) + time_consumed = get_unit_consumed(productivity) + quantity_name_in_process = get_quantity_produced_name(productivity) + total_quantity_to_produce = get_total_quantity_produced(resource, quantity_name_in_process) + if not time_consumed or not quantity_produced or not total_quantity_to_produce: + return + iso_string = "" + if "T" in productivity.get("BaseQuantityConsumed", ""): + seconds = (time_consumed.days * 24 * 60 * 60) + time_consumed.seconds + productivity_ratio = seconds / quantity_produced + required_work = total_quantity_to_produce * productivity_ratio + iso_string = f"PT{required_work / 60 / 60}H" + else: + days = time_consumed.days + (time_consumed.seconds / (24 * 60 * 60)) + productivity_ratio = days / quantity_produced + required_work = total_quantity_to_produce * productivity_ratio + iso_string = f"P{required_work}D" + return iso_string + + +def get_nested_resources(resource: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + return [object for rel in resource.IsNestedBy or [] for object in rel.RelatedObjects] + + +def get_cost(resource: ifcopenshell.entity_instance) -> tuple[Union[float, None], Union[str, None]]: + """Get cost data for IfcConstructionResource. + + :return: a tuple of cost and unit. + """ + cost, unit = None, None + if base_costs := resource.BaseCosts: + costs = [ifcopenshell.util.cost.calculate_applied_value(resource, cost_value) for cost_value in base_costs] + cost = sum(costs) + unit_basis = next((unit_basis for cost_value in base_costs if (unit_basis := cost_value.UnitBasis)), None) + if unit_basis and (unit_component := unit_basis.UnitComponent).is_a("IfcConversionBasedUnit"): + unit = unit_component.Name + return cost, unit + + +def get_quantity(resource: ifcopenshell.entity_instance) -> float: + if resource.Usage and resource.Usage.ScheduleWork: + duration = ifcopenshell.util.date.ifc2datetime(resource.Usage.ScheduleWork) + return duration.total_seconds() / 3600 + # TODO: is it safe to assume None quantity should be treated as 1.0? See #910 in ifc4x3dev. + quantity = resource.BaseQuantity + return 1.0 if quantity is None else quantity[3] + + +def get_parent_cost(resource: ifcopenshell.entity_instance) -> Union[tuple[Union[float, None], Union[str, None]], None]: + if not (nests := resource.Nests): + return + else: + cost = get_cost(nests[0].RelatingObject) + return cost diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/schema.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/schema.py new file mode 100644 index 0000000000000000000000000000000000000000..d3d7b65c6a64a18b6435be6500a45cf5d4099bbd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/schema.py @@ -0,0 +1,561 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import os +import json +import time +import ifcopenshell +import ifcopenshell.util.attribute +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper +from typing import Union, Any, Literal + +# This is highly experimental and incomplete, however, it may work for simple datasets. + +cwd = os.path.dirname(os.path.realpath(__file__)) +IFC_SCHEMA = Literal["IFC2X3", "IFC4", "IFC4X3"] + + +def get_fallback_schema(version: str) -> IFC_SCHEMA: + """Fallback to the schema version we do have docs and mapping for. + + Needed to support IFC versions like 4X3_RC1, 4X1 etc. + + :param version: Typically a string from ``ifcopenshell.file.schema_identifier``, e.g. IFC4X3_ADD2 + """ + if version.startswith("IFC4X3"): + version = "IFC4X3" + elif version.startswith("IFC4"): + version = "IFC4" + elif version.startswith("IFC2X3"): + version = "IFC2X3" + else: + assert False, f"Unexpected schema version: {version}." + return version + + +def get_declaration(element: ifcopenshell.entity_instance): + """Get the schema declaration of an actively used entity instance + + IFC models are made out of instances (e.g. with a STEP ID) of entities + (e.g. IfcWall). Those entities are defined through a **Schema + Declaration**. + + **Schema Declaration** objects can be used to query information about the + IFC schema itself, such as data types, enumeration values, and inheritance. + + :param element: Any instance, typically from a loaded or created IFC model + + Example: + + .. code:: python + + wall = model.createIfcWall() + declaration = ifcopenshell.util.schema.get_declaration(wall) + print(declaration.name()) # IfcWall + print(declaration.is_abstract()) # False + print(declaration.supertype().name()) # IfcBuildingElement + """ + return element.wrapped_data.declaration().as_entity() + + +def is_a(declaration: ifcopenshell.ifcopenshell_wrapper.declaration, ifc_class: str) -> bool: + """Checks if a schema declaration is a class + + :param declaration: The declaration from the schema. + :param ifc_class: A case insensitive IFC class name (e.g. IfcRoot) + :return: True is the declaration is of that class + + Example: + + .. code:: python + + wall = model.createIfcWall() + declaration = ifcopenshell.util.schema.get_declaration(wall) + ifcopenshell.util.schema.is_a(declaration, "IfcRoot") # True + """ + return declaration._is(ifc_class) + + +def get_supertypes( + declaration: ifcopenshell.ifcopenshell_wrapper.entity, +) -> list[ifcopenshell.ifcopenshell_wrapper.entity]: + """Gets a list of supertype declarations + + :param declaration: The declaration from the schema, as an entity. + :return: A list of supertypes in order from parent to grandparent. + + Example: + + .. code:: python + + wall = model.createIfcWall() + results = ifcopenshell.util.schema.get_supertypes(wall.wrapped_data.declaration().as_entity()) + # [, , ..., ] + """ + results = [] + while True: + if not (declaration := declaration.supertype()): + break + results.append(declaration) + return results + + +def get_subtypes( + declaration: ifcopenshell.ifcopenshell_wrapper.entity, +) -> list[ifcopenshell.ifcopenshell_wrapper.entity]: + """Get a flat list of subtype declarations, recursively. + + Abstract classes are skipped. + + Inconsistently, the declaration itself is also added to this list. This + should be fixed exclude the declaration itself. + + :param declaration: The declaration from the schema, as an entity. + :return: A list of subtypes in order from child to grandchild. + + .. code:: python + + schema = ifcopenshell.schema_by_name("IFC4") + declaration = schema.declaration_by_name("IfcFlowSegment") + print(ifcopenshell.util.schema.get_subtypes(declaration)) + [, , ..., ] + """ + + def get_classes(decl: ifcopenshell_wrapper.entity) -> list[ifcopenshell_wrapper.entity]: + results: list[ifcopenshell_wrapper.entity] = [] + if not decl.is_abstract(): + results.append(decl) + for subtype in decl.subtypes(): + results.extend(get_classes(subtype)) + return results + + return get_classes(declaration) + + +def reassign_class( + ifc_file: Union[ifcopenshell.file, None], element: ifcopenshell.entity_instance, new_class: str +) -> ifcopenshell.entity_instance: + """ + Attempts to change the class (entity name) of `element` to `new_class` by + removing element and recreating a similar instance of type `new_class` + with the same id. + + In certain cases it may affect the structure of inversely related instances: + - Multiple occurrences of reassigned instance within the same aggregate + (such as start and end-point of polyline) + - Occurrences of reassigned instance within an ordered aggregate + (such as IfcRelNests) + + It's unlikely that this affects real-world usage of this function. + + :raises ValueError: If ``new_class`` does not exist in the provided file schema. + """ + + if element.is_a() == new_class: + return element + + if not ifc_file: + ifc_file = element.file + + schema = ifcopenshell_wrapper.schema_by_name(ifc_file.schema_identifier) + try: + declaration = schema.declaration_by_name(new_class) + except RuntimeError: + raise ValueError( + f"Class of {element} could not be changed to {new_class} as the class does not exist in schema {ifc_file.schema_identifier}." + ) + + info = element.get_info() + + new_attributes = {} + for attribute in declaration.all_attributes(): + name = attribute.name() + old_attribute = info.get(name, None) + if old_attribute: + if ifcopenshell.util.attribute.get_primitive_type(attribute) == "enum": + if old_attribute in ifcopenshell.util.attribute.get_enum_items(attribute): + new_attributes[name] = old_attribute + else: + new_attributes[name] = old_attribute + + inverse_pairs = ifc_file.get_inverse(element, allow_duplicate=True, with_attribute_indices=True) + ifc_file.remove(element) + + try: + new_element = ifc_file.create_entity(new_class, id=info["id"], **new_attributes) + except: + print(f"Class of {element} could not be changed to {new_class}") + old_class = info.pop("type") + return ifc_file.create_entity(old_class, **info) + + for inverse_pair in inverse_pairs: + inverse, index = inverse_pair + if inverse[index] is None: + inverse[index] = new_element + elif isinstance(inverse[index], tuple): + item = list(inverse[index]) + item.append(new_element) + inverse[index] = item + + return new_element + + +class BatchReassignClass: + def __init__(self, file: ifcopenshell.file): + self.file = file + self.purge() + + def reassign(self, element: ifcopenshell.entity_instance, new_class: str) -> ifcopenshell.entity_instance: + try: + new_element = self.file.create_entity(new_class) + except: + print(f"Class of {element} could not be changed to {new_class}") + return element + new_attributes = [new_element.attribute_name(i) for i, attribute in enumerate(new_element)] + for i, attribute in enumerate(element): + try: + new_element[new_attributes.index(element.attribute_name(i))] = attribute + except: + continue + for inverse_pair in self.file.get_inverse(element, allow_duplicate=True, with_attribute_indices=True): + inverse, index = inverse_pair + self.replacements.setdefault(inverse, {}).setdefault(index, {})[element] = new_element + self.to_delete.add(element) + return new_element + + def unbatch(self): + for inverse, replacements in self.replacements.items(): + for index, element_map in replacements.items(): + value = inverse[index] + new = inverse.walk(lambda x: True, lambda v: element_map.get(v, v), value) + if value != new: + inverse[index] = new + + for element in self.to_delete: + self.file.remove(element) + self.purge() + + def purge(self) -> None: + # mapping {inverse: {attribute_index: {old_element: new_element} } } + self.replacements: dict[ + ifcopenshell.entity_instance, dict[int, dict[ifcopenshell.entity_instance, ifcopenshell.entity_instance]] + ] = {} + self.to_delete: set[ifcopenshell.entity_instance] = set() + + +class Migrator: + migrated_ids: dict[int, int] + attribute_overrides: dict[int, dict[int, str]] + + def __init__(self): + self.migrated_ids = {} + self.attribute_overrides = {} + self.class_4_to_2x3 = json.load(open(os.path.join(cwd, "class_4_to_2x3.json"), "r")) + self.class_2x3_to_4 = json.load(open(os.path.join(cwd, "class_2x3_to_4.json"), "r")) + + # IFC classes, and their IFC attributes mapping + self.attributes_mapping = { + ("IFC4", "IFC2X3"): json.load(open(os.path.join(cwd, "attribute_4_to_2x3.json"), "r")), + ("IFC4X3", "IFC4"): json.load(open(os.path.join(cwd, "attribute_4x3_to_4.json"), "r")), + } + + self.default_values = { + "ChangeAction": "NOCHANGE", + "CompositionType": "ELEMENT", + "CrossSectionArea": 1, + "DataValue": 0, + "DefinedValues": [0], + "DefiningValues": [0], + "DestabilizingLoad": False, + "Edition": "", + "EndParam": 1.0, + "EnumerationValues": [0], + "GeodeticDatum": "", + "Intent": "", + "IsHeading": False, + "ListValues": [0], + "LongitudinalBarCrossSectionArea": 1, + "LongitudinalBarNominalDiameter": 1, + "LongitudinalBarSpacing": 1, + "Name": "", + "NominalDiameter": 1, + "PredefinedType": "NOTDEFINED", + "RowCells": [0], + "SequenceType": "NOTDEFINED", + "Source": "", + "StartParam": 0.0, + "TransverseBarCrossSectionArea": 1, + "TransverseBarNominalDiameter": 1, + "TransverseBarSpacing": 1, + # Manual additions from experience + "InteriorOrExteriorSpace": "NOTDEFINED", + "AssemblyPlace": "NOTDEFINED", # See bug https://github.com/Autodesk/revit-ifc/issues/395 + } + self.default_entities = { + "CurrentValue": None, + "DepreciatedValue": None, + "Jurisdiction": None, + "OriginalValue": None, + "Owner": None, + "OwnerHistory": None, + "Position": None, + "PropertyReference": None, + "RepresentationContexts": None, + "ResponsiblePerson": None, + "ResponsiblePersons": None, + "Rows": None, + "TotalReplacementCost": None, + "UnitsInContext": None, + "User": None, + } + + def preprocess(self, old_file: ifcopenshell.file, new_file: ifcopenshell.file) -> None: + new_file.assign_header_from(old_file) + to_delete = set() + + if old_file.schema == "IFC2X3" and new_file.schema == "IFC4": + # IfcCalendarDate is deprecated in IFC4 + for element in old_file.by_type("IfcCalendarDate"): + for inverse, attribute_index in old_file.get_inverse( + element, allow_duplicate=True, with_attribute_indices=True + ): + self.attribute_overrides.setdefault(inverse.id(), {})[ + attribute_index + ] = f"{element[2]}-{element[1]}-{element[0]}" + to_delete.add(element) + + if old_file.schema == "IFC4" and new_file.schema == "IFC4X3": + # IfcPresentationStyleAssignment is deprecated + for assignment in old_file.by_type("IfcPresentationStyleAssignment"): + for styled_item in old_file.get_inverse(assignment): + if not styled_item.is_a("IfcStyledItem"): + continue + styled_item.Styles = [s for s in styled_item.Styles if s.is_a("IfcPresentationStyle")] + list( + assignment.Styles + ) + to_delete.add(assignment) + + for element in to_delete: + old_file.remove(element) + + def migrate( + self, element: ifcopenshell.entity_instance, new_file: ifcopenshell.file + ) -> ifcopenshell.entity_instance: + if element.id() == 0: + ifc_class = element.is_a() + if ifc_class == "IfcCountMeasure" and new_file.schema == "IFC4X3": + value = element.wrappedValue + if isinstance(value, float): + ifc_class = "IfcNumericMeasure" + return new_file.create_entity(ifc_class, element.wrappedValue) + try: + return new_file.by_id(self.migrated_ids[element.id()]) + except: + pass + # print("Migrating", element) + schema = ifcopenshell.ifcopenshell_wrapper.schema_by_name(new_file.schema_identifier) + new_element = self.migrate_class(element, new_file) + # print("Migrated class from {} to {}".format(element, new_element)) + new_element_schema = schema.declaration_by_name(new_element.is_a()) + if not hasattr(new_element_schema, "all_attributes"): + return element # The element has no attributes, so migration is done + new_element = self.migrate_attributes(element, new_file, new_element, new_element_schema) + self.migrated_ids[element.id()] = new_element.id() + return new_element + + def migrate_class( + self, element: ifcopenshell.entity_instance, new_file: ifcopenshell.file + ) -> ifcopenshell.entity_instance: + ifc_class = element.is_a() + if ifc_class == "IfcQuantityCount" and new_file.schema == "IFC4X3": + # 3 IfcPhysicalSimpleQuantity Value + value = element[3] + if isinstance(value, float): + ifc_class = "IfcQuantityNumber" + try: + new_element = new_file.create_entity(ifc_class) + except: + # The element does not exist in this schema + # Complex migration is not yet supported (e.g. polygonal face set to faceted brep) + if new_file.schema == "IFC2X3": + new_element = new_file.create_entity(self.class_4_to_2x3[ifc_class]) + elif new_file.schema == "IFC4": + new_element = new_file.create_entity(self.class_2x3_to_4[ifc_class]) + return new_element + + def migrate_attributes( + self, + element: ifcopenshell.entity_instance, + new_file: ifcopenshell.file, + new_element: ifcopenshell.entity_instance, + new_element_schema: ifcopenshell_wrapper.declaration, + ) -> ifcopenshell.entity_instance: + for attribute_index, value in self.attribute_overrides.get(element.id(), {}).items(): + new_element[attribute_index] = value + for i, attribute in enumerate(new_element_schema.all_attributes()): + if new_element_schema.derived()[i]: + continue + self.migrate_attribute(attribute, element, new_file, new_element, new_element_schema) + return new_element + + def find_equivalent_attribute( + self, + new_element: ifcopenshell.entity_instance, + attribute: ifcopenshell_wrapper.attribute, + element: ifcopenshell.entity_instance, + attributes_mapping: dict[str, dict[str, str]], + reverse_mapping: bool = False, + ) -> Union[Any, None]: + # print("Searching for an equivalent", element, new_element, attribute.name()) + ifc_class = new_element.is_a() + attr_name = attribute.name() + try: + if reverse_mapping: + equivalent_map = attributes_mapping[ifc_class] + equivalent = list(equivalent_map.keys())[list(equivalent_map.values()).index(attr_name)] + else: + equivalent = attributes_mapping[ifc_class][attr_name] + if hasattr(element, equivalent): + # print("Equivalent found", equivalent) + return getattr(element, equivalent) + else: + return + except Exception as e: + if ( + ifc_class == "IfcQuantityNumber" + and attr_name == "NumberValue" + and new_element.file.schema == "IFC4X3" + and element.is_a("IfcQuantityCount") + ): + # 3 IfcPhysicalSimpleQuantity Value + return element[3] + + print( + "Unable to find equivalent attribute of {} to migrate from {} to {}".format( + attr_name, element, new_element + ) + ) + raise e + + def migrate_attribute( + self, + attribute: ifcopenshell_wrapper.attribute, + element: ifcopenshell.entity_instance, + new_file: ifcopenshell.file, + new_element: ifcopenshell.entity_instance, + new_element_schema: ifcopenshell_wrapper.declaration, + ) -> None: + # NOTE: `attribute` is an attribute in new file schema + # print("Migrating attribute", element, new_element, attribute.name()) + old_file = element.wrapped_data.file + if hasattr(element, attribute.name()): + value = getattr(element, attribute.name()) + # print("Attribute names matched", value) + + elif new_file.schema == "IFC2X3" and old_file.schema == "IFC4": + # IFC4 to IFC2X3: We know the IFC2X3 attribute name, but not its IFC4 equivalent + try: + value = self.find_equivalent_attribute( + new_element, attribute, element, self.attributes_mapping[("IFC4", "IFC2X3")], reverse_mapping=True + ) + except: # We tried our best + return + + elif new_file.schema == "IFC4" and old_file.schema == "IFC2X3": + # IFC2X3 to IFC4: We know the IFC4 attribute name, but not its IFC2X3 equivalent + try: + value = self.find_equivalent_attribute( + new_element, attribute, element, self.attributes_mapping[("IFC4", "IFC2X3")] + ) + except: # We tried our best + return + + elif new_file.schema == "IFC4X3" and old_file.schema == "IFC4": + try: + value = self.find_equivalent_attribute( + new_element, attribute, element, self.attributes_mapping[("IFC4X3", "IFC4")] + ) + except: # We tried our best + return + + elif new_file.schema == "IFC4" and old_file.schema == "IFC4X3": + try: + value = self.find_equivalent_attribute( + new_element, attribute, element, self.attributes_mapping[("IFC4X3", "IFC4")], reverse_mapping=True + ) + except: # We tried our best + return + + try: + value + except UnboundLocalError: + print( + f"Couldn't match attribute {attribute.name()} by name to migrate from {element} " + f"to {new_element} and there is no special mapping to handle migration " + f"from {old_file.schema} -> {new_file.schema}" + ) + return + + # print("Continuing migration of {} to migrate from {} to {}".format(attribute.name(), element, new_element)) + if value is None and not attribute.optional(): + value = self.generate_default_value(attribute, new_file) + if value is None: + print("Failed to generate default value for {} on {}".format(attribute.name(), element)) + elif isinstance(value, ifcopenshell.entity_instance): + value = self.migrate(value, new_file) + elif isinstance(value, (list, tuple)): + if value and isinstance(value[0], ifcopenshell.entity_instance): + new_value = [] + for item in value: + new_value.append(self.migrate(item, new_file)) + value = new_value + if value is not None: + setattr(new_element, attribute.name(), value) + + def generate_default_value(self, attribute: ifcopenshell_wrapper.attribute, new_file: ifcopenshell.file) -> Any: + if attribute.name() in self.default_values: + return self.default_values[attribute.name()] + elif attribute.name() == "OwnerHistory": + self.default_entities[attribute.name()] = new_file.create_entity( + "IfcOwnerHistory", + **{ + "OwningUser": new_file.create_entity( + "IfcPersonAndOrganization", + **{ + "ThePerson": new_file.create_entity("IfcPerson"), + "TheOrganization": new_file.create_entity( + "IfcOrganization", **{"Name": "IfcOpenShell Migrator"} + ), + }, + ), + "OwningApplication": new_file.create_entity( + "IfcApplication", + **{ + "ApplicationDeveloper": new_file.create_entity( + "IfcOrganization", **{"Name": "IfcOpenShell Migrator"} + ), + "Version": "Works for me", + "ApplicationFullName": "IfcOpenShell Migrator", + "ApplicationIdentifier": "IfcOpenShell Migrator", + }, + ), + "ChangeAction": "NOCHANGE", + "CreationDate": int(time.time()), + }, + ) + return self.default_entities.get(attribute.name(), None) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/selector.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/selector.py new file mode 100644 index 0000000000000000000000000000000000000000..a2ce6fb4675267250ccdb7d8a60236c2dc5be26b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/selector.py @@ -0,0 +1,1166 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import re +import sys +import lark +import numpy as np +import ifcopenshell.api.pset +import ifcopenshell.api.geometry +import ifcopenshell.util +import ifcopenshell.util.attribute +import ifcopenshell.util.classification +import ifcopenshell.util.element +import ifcopenshell.util.fm +import ifcopenshell.util.geolocation +import ifcopenshell.util.placement +import ifcopenshell.util.pset +import ifcopenshell.util.schema +import ifcopenshell.util.shape +import ifcopenshell.util.system +import ifcopenshell.util.unit +from decimal import Decimal +from typing import Optional, Any, Union +from collections.abc import Iterable + +if sys.version_info >= (3, 10): + from types import EllipsisType +else: + EllipsisType = type(...) + + +filter_elements_grammar = lark.Lark( + """start: filter_group + filter_group: facet_list ("+" facet_list)* + facet_list: facet ("," facet)* + + facet: instance | entity | attribute | type | material | query | classification | location | property | group | parent + + instance: not? globalid + globalid: /[0-3][a-zA-Z0-9_$]{21}/ + entity: not? ifc_class + attribute: attribute_name comparison value + type: "type" comparison value + material: "material" comparison value + property: pset "." prop comparison value + classification: "classification" comparison value + location: "location" comparison value + group: "group" comparison value + parent: "parent" comparison value + query: "query:" keys comparison value + + pset: quoted_string | regex_string | unquoted_string + prop: quoted_string | regex_string | unquoted_string + keys: quoted_string | unquoted_string + + attribute_name: /[A-Z]\\w+/ + ifc_class: /Ifc\\w+/ + + value: special | quoted_string | regex_string | unquoted_string + unquoted_string: /[^,.=><*!\\s]+/ + regex_string: "/" /[^\\/]+/ "/" + quoted_string: ESCAPED_STRING + + special: null | true | false + + comparison: not? equals | morethanequalto | lessthanequalto | morethan | lessthan | not? contains + not: "!" + equals: "=" + morethanequalto: ">=" + lessthanequalto: "<=" + morethan: ">" + lessthan: "<" + contains: "*=" + null: "NULL" + true: "TRUE" + false: "FALSE" + + // Embed common.lark for packaging + DIGIT: "0".."9" + HEXDIGIT: "a".."f"|"A".."F"|DIGIT + INT: DIGIT+ + SIGNED_INT: ["+"|"-"] INT + DECIMAL: INT "." INT? | "." INT + _EXP: ("e"|"E") SIGNED_INT + FLOAT: INT _EXP | DECIMAL _EXP? + SIGNED_FLOAT: ["+"|"-"] FLOAT + NUMBER: FLOAT | INT + SIGNED_NUMBER: ["+"|"-"] NUMBER + _STRING_INNER: /.*?/ + _STRING_ESC_INNER: _STRING_INNER /(?= 3 and args[2]: + return "{:,}".format(args[0]).replace(".", "*").replace(",", args[2]).replace("*", args[1]) + elif len(args) >= 2 and args[1]: + return "{}".format(args[0]).replace(".", args[1]) + return "{:,}".format(args[0]) + + def format_length(self, args): + return args[0] + + def metric_length(self, args): + value, precision, decimal_places = args + return ifcopenshell.util.unit.format_length( + float(value), float(precision), int(decimal_places), unit_system="metric" + ) + + def imperial_length(self, args): + args = list(filter(lambda x: x is not None, args)) + if len(args) == 2: + input_unit, output_unit = "foot", "foot" + value, precision = args + suppress_zero_inches = True + elif len(args) == 3: + value, precision, suppress_zero_inches = args + input_unit, output_unit = "foot", "foot" + elif len(args) == 4: + value, precision, input_unit, output_unit = args + input_unit = "inch" if input_unit == "inch" else "foot" + output_unit = "inch" if output_unit == "inch" else "foot" + suppress_zero_inches = True + else: + value, precision, input_unit, output_unit, suppress_zero_inches = args + input_unit = "inch" if input_unit == "inch" else "foot" + output_unit = "inch" if output_unit == "inch" else "foot" + + return ifcopenshell.util.unit.format_length( + float(value), + int(precision), + suppress_zero_inches=(suppress_zero_inches if suppress_zero_inches is not None else False), + unit_system="imperial", + input_unit=input_unit, + output_unit=output_unit, + ) + + def int(self, args: list[str]) -> str: + return str(int(float(args[0]))) + + +class GetElementTransformer(lark.Transformer): + def start(self, args): + return args[0] + + def keys(self, args): + return args + + def key(self, args): + return args[0] + + def quoted_string(self, args): + return str(args[0]) + + def regex_string(self, args): + return re.compile(args[0]) + + def unquoted_string(self, args): + return str(args[0]) + + def ESCAPED_STRING(self, args): + return args[1:-1].replace("\\", "") + + +def format(query: str) -> str: + return FormatTransformer().transform(format_grammar.parse(query)) + + +def get_element_value(element: ifcopenshell.entity_instance, query: str) -> Any: + keys: list[str] = GetElementTransformer().transform(get_element_grammar.parse(query)) + return _get_element_value(element, keys) + + +def _get_element_value(element: ifcopenshell.entity_instance, keys: list[str]) -> Any: + value = element + for key in keys: + if value is None: + return + if key == "type": + value = ifcopenshell.util.element.get_type(value) + elif key in ("material", "mat"): + value = ifcopenshell.util.element.get_material(value, should_skip_usage=True) + elif key in ("materials", "mats"): + value = ifcopenshell.util.element.get_materials(value) + elif key == "profiles": + value = ifcopenshell.util.shape.get_profiles(value) + elif key == "styles": + value = ifcopenshell.util.element.get_styles(value) + elif key in ("item", "i"): + if value.is_a("IfcMaterialLayerSet"): + value = value.MaterialLayers + elif value.is_a("IfcMaterialProfileSet"): + value = value.MaterialProfiles + elif value.is_a("IfcMaterialConstituentSet"): + value = value.MaterialConstituents + elif key == "container": + value = ifcopenshell.util.element.get_container(value) + elif key == "space": + value = ifcopenshell.util.element.get_container(value, ifc_class="IfcSpace") + elif key == "storey": + value = ifcopenshell.util.element.get_container(value, ifc_class="IfcBuildingStorey") + elif key == "building": + value = ifcopenshell.util.element.get_container(value, ifc_class="IfcBuilding") + elif key == "site": + value = ifcopenshell.util.element.get_container(value, ifc_class="IfcSite") + elif key == "parent": + value = ifcopenshell.util.element.get_parent(value) + elif key in ("types", "occurrences"): + value = ifcopenshell.util.element.get_types(value) + elif key == "count": + if isinstance(value, set): + value = len(list(value)) + elif isinstance(value, (list, tuple)): + value = len(value) + else: + value = 1 + elif key == "class": + value = value.is_a() + elif key == "predefined_type": + value = ifcopenshell.util.element.get_predefined_type(value) + elif key == "id": + value = value.id() + elif key == "classification": + value = ifcopenshell.util.classification.get_references(value) + elif key == "group": + value = ifcopenshell.util.element.get_groups(value) + elif key == "system": + value = ifcopenshell.util.system.get_element_systems(value) + elif key == "zone": + value = ifcopenshell.util.system.get_element_zones(value) + elif key in ("x", "y", "z", "easting", "northing", "elevation") and hasattr(value, "ObjectPlacement"): + if getattr(value, "ObjectPlacement", None): + matrix = ifcopenshell.util.placement.get_local_placement(value.ObjectPlacement) + xyz = matrix[:, 3][:3] + if key in ("x", "y", "z"): + value = xyz["xyz".index(key)] + else: + enh = ifcopenshell.util.geolocation.auto_xyz2enh(element.wrapped_data.file, *xyz) + value = enh[("easting", "northing", "elevation").index(key)] + else: + value = None + elif isinstance(value, ifcopenshell.entity_instance): + if key == "Name" and value.is_a("IfcMaterialLayerSet"): + key = "LayerSetName" # This oddity in the IFC spec is annoying so we account for it. + + if isinstance(key, re.Pattern): + attribute = None # Should we support regex attributes? Probably not for now. + else: + attribute = getattr(value, key, None) + + if attribute is not None: + value = attribute + else: + # Try to extract pset + if isinstance(key, re.Pattern): + psets = ifcopenshell.util.element.get_psets(value) + matching_psets = [] + for pset_name, pset in psets.items(): + if key.match(pset_name): + del pset["id"] + matching_psets.append(pset) + result = matching_psets or None + if result and len(result) == 1: + result = result[0] + else: + result = ifcopenshell.util.element.get_pset(value, key) + if result: + del result["id"] + + value = result + elif isinstance(value, dict): # Such as from the result of a prior get_pset + if isinstance(key, re.Pattern): + results = [] + for prop_name, prop_value in value.items(): + if key.match(prop_name): + if isinstance(prop_value, (list, tuple)): + results.extend(prop_value) + else: + results.append(prop_value) + value = results or None + if value and len(value) == 1: + value = value[0] + else: + value = value.get(key, None) + elif isinstance(value, (list, tuple, set)): # If we use regex + if isinstance(key, str) and key.isnumeric(): + try: + value = value[int(key)] + except IndexError: + return + else: + results = [] + for v in value: + subvalue = _get_element_value(v, [key]) + if isinstance(subvalue, list): + results.extend(subvalue) + else: + results.append(subvalue) + value = results + return value + + +def filter_elements( + ifc_file: ifcopenshell.file, + query: str, + elements: Optional[set[ifcopenshell.entity_instance]] = None, + edit_in_place=False, +) -> set[ifcopenshell.entity_instance]: + """ + Filter elements based on the provided `query`. + + :param ifc_file: The IFC file object + :param query: Query to execute + :param elements: Base set of IFC elements for the query. If not provided, + all elements in the IFC are queried. If provided, the query will be + applied to this set of elements, so the result will be a subset of + elements. + :param edit_in_place: If `True`, mutate the provided `elements` in place. Defaults to `False` + :return: Set of filtered elements + + Example: + + .. code:: python + + # Select all the walls and slabs in the file. + elements = ifcopenshell.util.selector.filter_elements(ifc_file, "IfcWall, IfcSlab") + + # Add doors to the elements too. + elements = ifcopenshell.util.selector.filter_elements(ifc_file, "IfcDoor", elements) + + # Changed our mind, exclude the slabs. + elements = ifcopenshell.util.selector.filter_elements(ifc_file, "! IfcSlab", elements) + + # {#1=IfcWall(...), #2=IfcDoor(...)} + print(elements) + """ + if not query: + return elements or set() + if elements and not edit_in_place: + elements = elements.copy() + transformer = FacetTransformer(ifc_file, elements) + transformer.transform(filter_elements_grammar.parse(query)) + return transformer.get_results() + + +class SetElementValueException(Exception): ... + + +def set_element_value( + ifc_file: ifcopenshell.file, + element: Union[ + ifcopenshell.entity_instance, + dict[str, Any], + Iterable[ifcopenshell.entity_instance], + None, + ], + query: Union[str, list[str]], + value: Any, + *, + concat: str = ", ", +) -> None: + """Set element value based on the provided query. + + :param element: IFC element to change. + :param query: String query to identify the attribute to change. + :param value: Value to set. + :param concat: Concatenation symbol, used only to deserialize property + set enum values from string values. + """ + original_element = element + if isinstance(query, (list, tuple)): + keys = query + else: + keys = GetElementTransformer().transform(get_element_grammar.parse(query)) + + for i, key in enumerate(keys): + if element is None: + return + if key == "type": + element = ifcopenshell.util.element.get_type(element) + elif key in ("material", "mat"): + element = ifcopenshell.util.element.get_material(element, should_skip_usage=True) + elif key in ("materials", "mats"): + element = ifcopenshell.util.element.get_materials(element) + elif key == "styles": + element = ifcopenshell.util.element.get_styles(element) + elif key in ("item", "i"): + if element.is_a("IfcMaterialLayerSet"): + element = element.MaterialLayers + elif element.is_a("IfcMaterialProfileSet"): + element = element.MaterialProfiles + elif element.is_a("IfcMaterialConstituentSet"): + element = element.MaterialConstituents + elif key == "container": + element = ifcopenshell.util.element.get_container(element) + elif key == "space": + element = ifcopenshell.util.element.get_container(element, ifc_class="IfcSpace") + elif key == "storey": + element = ifcopenshell.util.element.get_container(element, ifc_class="IfcBuildingStorey") + elif key == "building": + element = ifcopenshell.util.element.get_container(element, ifc_class="IfcBuilding") + elif key == "site": + element = ifcopenshell.util.element.get_container(element, ifc_class="IfcSite") + elif key == "parent": + element = ifcopenshell.util.element.get_parent(element) + elif key == "class": + if element.is_a().lower() != value.lower(): + return ifcopenshell.util.schema.reassign_class(ifc_file, element, value) + return + elif key == "id": + return + elif key == "predefined_type": + current_value = ifcopenshell.util.element.get_predefined_type(element) + if current_value == value: + return + + def set_predefined_type( + element: ifcopenshell.entity_instance, value: Union[str, None], *, is_type: bool + ) -> None: + predefined_type = element.PredefinedType + declaration = element.wrapped_data.declaration() + entity = declaration.as_entity() + enum_attr = next(attr for attr in entity.attributes() if attr.name() == "PredefinedType") + enum_items = ifcopenshell.util.attribute.get_enum_items(enum_attr) + + # USERDEFINED shouldn't occur here, if it does then it means + # then it was artificially added and PredefinedType is actually unset. + if value in (None, "NOTDEFINED", "USERDEFINED"): + element.PredefinedType = "NOTDEFINED" + setattr(element, "ElementType" if is_type else "ObjectType", None) + elif value in enum_items: + if predefined_type == value: + return + element.PredefinedType = value + return + + # Value not in PredefinedType enum items. + if predefined_type != "USERDEFINED": + element.PredefinedType = "USERDEFINED" + setattr(element, "ElementType" if is_type else "ObjectType", value) + return + + if element_type := ifcopenshell.util.element.get_type(element): + set_predefined_type(element_type, value, is_type=True) + return + set_predefined_type(element, value, is_type=False) + return + elif key == "classification": + element = ifcopenshell.util.classification.get_references(element) + elif key in ("x", "y", "z", "easting", "northing", "elevation") and hasattr(element, "ObjectPlacement"): + # TODO: add support + if key in ("easting", "northing", "elevation"): + return + + placement = element.ObjectPlacement + if placement is None: + matrix = np.eye(4) + else: + matrix = ifcopenshell.util.placement.get_local_placement(placement) + + # check if value is within tolerance to avoid api calls + coord_i = "xyz".index(key) + prev_value = matrix[coord_i][3] + new_value = float(value) if value else 0.0 + if ifcopenshell.util.shape.is_x(new_value, prev_value): + return + + matrix[coord_i][3] = new_value + ifcopenshell.api.geometry.edit_object_placement(ifc_file, product=element, matrix=matrix, is_si=False) + return + elif isinstance(element, ifcopenshell.entity_instance): + if key == "Name" and element.is_a("IfcMaterialLayerSet"): + key = "LayerSetName" # This oddity in the IFC spec is annoying so we account for it. + + if isinstance(key, str) and ((current_value := getattr(element, key, ...)) is not ...): + # check if key is not last + if len(keys) != i + 1: + element = current_value + continue + + if current_value == value: + return + else: + # check if key is not last + try: + # Try our luck + return setattr(element, key, value) + except: + # Try to cast + data_type = ifcopenshell.util.attribute.get_primitive_type( + element.wrapped_data.declaration() + .as_entity() + .attribute_by_index(element.wrapped_data.get_argument_index(key)) + ) + if data_type == "string": + value = str(value) + elif data_type == "float": + value = float(value) + elif data_type == "integer": + value = int(value) + elif data_type == "boolean": + if value in ("True", "true", "TRUE", "Yes", "1"): + value = True + elif value in ("False", "false", "FALSE", "No", "0"): + value = False + else: + value = bool(value) + elif data_type == "entity": + value = ifc_file.by_guid(value) + if current_value == value: + return + return setattr(element, key, value) + else: + # Try to extract pset + if isinstance(key, re.Pattern): + psets = ifcopenshell.util.element.get_psets(element) + matching_psets = [] + for pset_name, pset in psets.items(): + if key.match(pset_name): + matching_psets.append(pset) + result = matching_psets or None + if result and len(result) == 1: + result = result[0] + else: + result = ifcopenshell.util.element.get_pset(element, key) + + if value and not result and len(keys) == i + 2: # The next key is the prop name + if "qto" in key.lower() or "quantity" in key.lower() or "quantities" in key.lower(): + pset = ifcopenshell.api.pset.add_qto(ifc_file, product=element, name=key) + else: + pset = ifcopenshell.api.pset.add_pset(ifc_file, product=element, name=key) + result = {"id": pset.id()} + + element = result + elif isinstance(element, dict): # Such as from the result of a prior get_pset + pset = ifc_file.by_id(element["id"]) + if isinstance(key, re.Pattern): + for prop, prop_value in element.items(): + if key.match(prop): + if pset.is_a("IfcPropertySet") and prop_value != value: + ifcopenshell.api.pset.edit_pset(ifc_file, pset=pset, properties={prop: value}) + elif pset.is_a("IfcElementQuantity") and prop_value != float(value): + ifcopenshell.api.pset.edit_qto(ifc_file, qto=pset, properties={prop: float(value)}) + elif pset.is_a("IfcPropertySet") and element.get(key, None) != value: + + def process_pset_prop_value( + pset: ifcopenshell.entity_instance, prop: str, value: Any + ) -> Union[Any, EllipsisType]: + """Try to process value for edit_pset. + + `edit_pset` is expecting a sequence of values + for enum properties, not just a string of some-symbol-separated values. + + Return `...` if property can be skipped as it has the same value. + """ + if not isinstance(value, str): + return value + + current_value = element.get(key, ...) + # Check if previous value is a list as a fast way to identify enum properties. + if not isinstance(current_value, (EllipsisType, list)): + return value + + if isinstance(current_value, list): + # Value won't change, safe to skip editing IFC. + enum_values = value.split(concat) + if len(enum_values) == len(current_value) and set(enum_values) == set(current_value): + return ... + + template = ifcopenshell.util.pset.get_template(ifc_file.schema_identifier) + pset_template = template.get_by_name(pset.Name) + if pset_template is None: + return value + for prop_template in pset_template.HasPropertyTemplates: + # 2 IfcSimplePropertyTemplate.Name + if prop_template[2] != prop: + continue + + # 4 IfcSimplePropertyTemplate.TemplateType + if prop_template[4] != "P_ENUMERATEDVALUE": + # Not a enum property. + return value + + # 7 IfcSimplePropertyTemplate.Enumerators + if (enumeration := prop_template[7]) is None: + # Enum property but without enumerators, + # make it a sequence to keep it assignable as a enum. + return (value,) + + # 1 IfcPropertyEnumeration.EnumerationValues + available_enum_values = {v.wrappedValue for v in enumeration[1]} + if value in available_enum_values: + # Valid enum item, just keep it a sequence. + return (value,) + + # Taking a wild guess that it's `concat` separated list. + enum_values = value.split(concat) + if not all(v in available_enum_values for v in enum_values): + raise Exception( + "Error setting pset enum property.\n" + f"Invalid enum values for property '{prop} in pset '{pset}': '{', '.join(enum_values)}'.\n" + f"Possible enum values for this property: {', '.join(available_enum_values)}." + ) + return enum_values + + # Couldn't find property template for this prop - delegate decision to edit_pset. + return value + + value = process_pset_prop_value(pset, key, value) + if value == ...: + return + ifcopenshell.api.pset.edit_pset(ifc_file, pset=pset, properties={key: value}) + elif pset.is_a("IfcElementQuantity"): + try: + value = float(value) + if element.get(key, None) != value: + ifcopenshell.api.pset.edit_qto(ifc_file, qto=pset, properties={key: value}) + except: + pass + return + elif isinstance(element, (list, tuple, set)): # If we use regex + if key.isnumeric(): + try: + element = element[int(key)] + except IndexError: + return + else: + for v in element: + set_element_value(ifc_file, v, keys[i:], value) + return + + raise SetElementValueException( + f"Failed to set value '{value}' for element '{original_element}' with query '{query}' (invalid or unsupported query)." + ) + + +class FacetTransformer(lark.Transformer): + results: list[set[ifcopenshell.entity_instance]] + base_elements: Optional[set[ifcopenshell.entity_instance]] + elements: set[ifcopenshell.entity_instance] + container_trees: dict[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]] + + def __init__(self, ifc_file: ifcopenshell.file, elements: Optional[set[ifcopenshell.entity_instance]] = None): + self.file = ifc_file + self.results = [] + if elements is None: + self.base_elements = None + self.elements = set() + else: + self.base_elements = elements.copy() + self.elements = set() + self.has_additive_facet_in_current_list = False + self.container_trees = {} + + def add_default_elements(self): + if self.has_additive_facet_in_current_list: + return + self.has_additive_facet_in_current_list = True + if self.base_elements: + self.elements.update(self.base_elements) + else: + self.elements.update(self.file.by_type("IfcProduct")) + self.elements.update(self.file.by_type("IfcTypeProduct")) + + def get_results(self) -> set[ifcopenshell.entity_instance]: + results: set[ifcopenshell.entity_instance] = set() + for r in self.results: + results |= r + return results + + def facet_list(self, args): + if self.elements: + self.results.append(self.elements) + self.elements = set() + self.has_additive_facet_in_current_list = False + + def instance(self, args): + self.has_additive_facet_in_current_list = True + if self.base_elements is None: + if args[0].data == "globalid": + try: + self.elements.add(self.file.by_guid(args[0].children[0].value)) + except: + pass + else: + try: + self.elements.remove(self.file.by_guid(args[1].children[0].value)) + except: + pass + else: + if args[0].data == "globalid": + self.elements |= { + e for e in self.base_elements if getattr(e, "GlobalId", None) == args[0].children[0].value + } + else: + self.elements -= { + e for e in self.base_elements if getattr(e, "GlobalId", None) == args[1].children[0].value + } + + def entity(self, args): + self.has_additive_facet_in_current_list = True + if self.base_elements is None: + if args[0].data == "ifc_class": + try: + self.elements |= set(self.file.by_type(args[0].children[0].value)) + except: + pass + else: + try: + self.elements -= set(self.file.by_type(args[1].children[0].value)) + except: + pass + else: + if args[0].data == "ifc_class": + self.elements |= {e for e in self.base_elements if e.is_a(args[0].children[0].value)} + else: + self.elements -= {e for e in self.base_elements if e.is_a(args[1].children[0].value)} + + def attribute(self, args): + name, comparison, value = args + name = name.children[0].value + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + if name == "PredefinedType": + element_value = ifcopenshell.util.element.get_predefined_type(element) + else: + element_value = getattr(element, name, None) + return self.compare(element_value, comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def type(self, args): + comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + element_type = ifcopenshell.util.element.get_type(element) + return self.compare(getattr(element_type, "Name", None), comparison, value) or self.compare( + getattr(element_type, "GlobalId", None), comparison, value + ) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def material(self, args): + comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + materials = ifcopenshell.util.element.get_materials(element) + result = False if materials else None + for material in materials: + if self.compare(material.Name, comparison, value): + result = True + if self.compare(getattr(material, "Category", None), comparison, value): + result = True + if result is not None: + return result if comparison == "=" else not result + return self.compare(None, comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def property(self, args): + pset, prop, comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + if isinstance(pset, str) and isinstance(prop, str): + element_value = ifcopenshell.util.element.get_pset(element, pset, prop) + return self.compare(element_value, comparison, value) + elif isinstance(pset, str) and isinstance(prop, re.Pattern): + element_props = ifcopenshell.util.element.get_pset(element, pset) or {} + for element_prop, element_value in element_props.items(): + if prop.match(element_prop): + return self.compare(element_value, comparison, value) + elif isinstance(pset, re.Pattern): + element_psets = ifcopenshell.util.element.get_psets(element) + for element_pset, element_props in element_psets.items(): + if not pset.match(element_pset): + continue + if isinstance(prop, str): + element_value = element_props.get(prop, None) + if element_value is not None: + return self.compare(element_value, comparison, value) + elif isinstance(prop, re.Pattern): + for element_prop, element_value in element_props.items(): + if prop.match(element_prop): + return self.compare(element_value, comparison, value) + return self.compare(None, comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def classification(self, args): + comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + references = ifcopenshell.util.classification.get_references(element) + result = False if references else None + for reference in references: + if self.compare(reference.Name, comparison, value): + result = True + if self.compare( + getattr(reference, "Identification", getattr(reference, "ItemReference", None)), comparison, value + ): + result = True + if result is not None: + return result if comparison == "=" else not result + return self.compare(None, comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def location(self, args): + comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + container = ifcopenshell.util.element.get_container(element) + if not container: + container = ifcopenshell.util.element.get_aggregate(element) + containers = self.get_container_tree(container) + result = False if containers else None + for container in containers: + if self.compare(container.Name, "=", value) or self.compare(container.GlobalId, "=", value): + result = True + if result is not None: + return result if comparison == "=" else not result + return self.compare(None, comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def group(self, args): + comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + result = False + for rel in getattr(element, "HasAssignments", []): + if rel.is_a("IfcRelAssignsToGroup") and rel.RelatingGroup: + if self.compare(rel.RelatingGroup.Name, "=", value): + result = True + elif self.compare(rel.RelatingGroup.GlobalId, "=", value): + result = True + return result if comparison == "=" else not result + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def parent(self, args): + comparison, value = args + + parents = set() + for rel in self.file.by_type("IfcRelAggregates"): + parent = rel.RelatingObject + if parent and ( + self.compare(parent.Name, comparison, value) or self.compare(parent.GlobalId, comparison, value) + ): + parents.add(parent) + + for rel in self.file.by_type("IfcRelContainedInSpatialStructure"): + parent = rel.RelatingStructure + if parent and ( + self.compare(parent.Name, comparison, value) or self.compare(parent.GlobalId, comparison, value) + ): + parents.add(parent) + + for rel in self.file.by_type("IfcRelNests"): + parent = rel.RelatingObject + if parent and ( + self.compare(parent.Name, comparison, value) or self.compare(parent.GlobalId, comparison, value) + ): + parents.add(parent) + + for rel in self.file.by_type("IfcRelVoidsElement"): + parent = rel.RelatingBuildingElement + if parent and ( + self.compare(parent.Name, comparison, value) or self.compare(parent.GlobalId, comparison, value) + ): + parents.add(parent) + + for rel in self.file.by_type("IfcRelFillsElement"): + parent = rel.RelatingOpeningElement + if parent and ( + self.compare(parent.Name, comparison, value) or self.compare(parent.GlobalId, comparison, value) + ): + parents.add(parent) + + # Get all children of the matched parents + children: set[ifcopenshell.entity_instance] = set() + for parent in parents: + children |= set(ifcopenshell.util.element.get_decomposition(parent)) + + # Combine parents and children into a single result set + result = parents | children + + self.add_default_elements() + if comparison == "=": + self.elements = self.elements & result + else: + self.elements -= result + + def query(self, args): + keys, comparison, value = args + + def filter_function(element: ifcopenshell.entity_instance) -> bool: + return self.compare(get_element_value(element, keys), comparison, value) + + self.add_default_elements() + self.elements = set(filter(filter_function, self.elements)) + + def get_container_tree(self, container: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + tree: Union[list[ifcopenshell.entity_instance], None] + tree = self.container_trees.get(container, None) + if tree: + return tree + + tree = [] + + while container: + if container.is_a("IfcProject"): + break + tree.append(container) + container = ifcopenshell.util.element.get_aggregate(container) + + tree_copy = tree.copy() + while tree_copy: + self.container_trees[tree_copy.pop(0)] = tree_copy.copy() + return tree + + def comparison(self, args): + if args[0].data == "not": + comparison = args[1].data + is_not = "!" + else: + comparison = args[0].data + is_not = "" + + return ( + is_not + + { + "equals": "=", + "morethanequalto": ">=", + "lessthanequalto": "<=", + "morethan": ">", + "lessthan": "<", + "contains": "*=", + }[comparison] + ) + + def keys(self, args): + return self.value(args) + + def pset(self, args): + return self.value(args) + + def prop(self, args): + return self.value(args) + + def value(self, args): + if args[0].data == "unquoted_string": + return args[0].children[0].value + elif args[0].data == "quoted_string": + return args[0].children[0].value[1:-1].replace('\\"', '"') + elif args[0].data == "regex_string": + return re.compile(args[0].children[0].value) + elif args[0].data == "special": + if args[0].children[0].data == "null": + return None + elif args[0].children[0].data == "true": + return True + elif args[0].children[0].data == "false": + return False + + def compare(self, element_value, comparison, value) -> bool: + if isinstance(element_value, (list, tuple)): + return any(self.compare(ev, comparison, value) for ev in element_value) + elif isinstance(value, str): + try: + if isinstance(element_value, int): + value = int(value) + elif isinstance(element_value, float): + value = float(value) + + if isinstance(element_value, (int, float)): + operator = comparison.lstrip("!") + if operator == ">=": + result = element_value >= value + elif operator == "<=": + result = element_value <= value + elif operator == ">": + result = element_value > value + elif operator == "<": + result = element_value < value + else: + result = element_value == value # Tolerance? + elif isinstance(element_value, str): + operator = comparison.lstrip("!") + if operator == "*=": + result = value in element_value + else: + result = element_value == value + else: + result = element_value == value + except: + # Potentially they are trying to compare a value which cannot + # be legally casted to the element_value, or cannot use the + # `in` or more / less than comparison operators. + result = False + elif isinstance(value, re.Pattern): + result = bool(value.match(element_value)) if element_value is not None else False + elif value in (None, True, False): + result = element_value is value + + if comparison.startswith("!"): + return not result + return result diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/sequence.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/sequence.py new file mode 100644 index 0000000000000000000000000000000000000000..51f34b7226a7b990eedbe00bc0da79159662fa9d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/sequence.py @@ -0,0 +1,465 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import datetime +import ifcopenshell.util.date +import ifcopenshell.util.element +from math import floor +from functools import cache +from typing import Union, Literal, Optional +from collections.abc import Generator + + +DURATION_TYPE = Literal["ELAPSEDTIME", "WORKTIME", "NOTDEFINED"] +RECURRENCE_TYPE = Literal[ + "BY_DAY_COUNT", + "BY_WEEKDAY_COUNT", + "DAILY", + "MONTHLY_BY_DAY_OF_MONTH", + "MONTHLY_BY_POSITION", + "WEEKLY", + "YEARLY_BY_DAY_OF_MONTH", + "YEARLY_BY_POSITION", +] + + +def derive_date( + task: ifcopenshell.entity_instance, + attribute_name: str, + date=None, + is_earliest: bool = False, + is_latest: bool = False, +): + """ + + :param task: IfcTask. + + """ + if task.TaskTime: + current_date = ( + ifcopenshell.util.date.ifc2datetime(getattr(task.TaskTime, attribute_name)) + if getattr(task.TaskTime, attribute_name) + else "" + ) + if current_date: + return current_date + for subtask in get_all_nested_tasks(task): + current_date = derive_date( + subtask, + attribute_name, + date=date, + is_earliest=is_earliest, + is_latest=is_latest, + ) + if is_earliest: + if current_date and (date is None or current_date < date): + date = current_date + if is_latest: + if current_date and (date is None or current_date > date): + date = current_date + return date + + +def derive_calendar(task: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + calendar = get_calendar(task) + if calendar: + return calendar + for rel in task.Nests or []: + return derive_calendar(rel.RelatingObject) + + +def get_calendar(task: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + calendar = [ + rel.RelatingControl + for rel in task.HasAssignments or [] + if rel.is_a("IfcRelAssignsToControl") and rel.RelatingControl.is_a("IfcWorkCalendar") + ] + if calendar: + return calendar[0] + + +def count_working_days(start, finish, calendar: ifcopenshell.entity_instance) -> int: + result = 0 + if start == finish: + return 0 + current_date = datetime.date(start.year, start.month, start.day) + finish_date = datetime.date(finish.year, finish.month, finish.day) + while current_date <= finish_date: + if calendar and calendar.WorkingTimes and is_working_day(current_date, calendar): + result += 1 + elif not calendar or not is_calendar_applicable(current_date, calendar): + result += 1 + current_date += datetime.timedelta(days=1) + return result + + +def get_start_or_finish_date( + start, + duration, + duration_type: DURATION_TYPE, + calendar: ifcopenshell.entity_instance, + date_type: Literal["START", "FINISH"] = "FINISH", +): + if not duration.days: + # Typically a milestone will have zero duration, so the start == finish + return start + # We minus 1 because the start day itself is counted as a day + months = int(getattr(duration, "months", 0)) + years = int(getattr(duration, "years", 0)) + total_duration = duration.days + months * 30 + years * 12 * 30 + duration = datetime.timedelta(days=total_duration - 1) + + if date_type == "START": + duration = -duration + result = offset_date(start, duration, duration_type, calendar) + if date_type == "START": + return datetime.datetime.combine(result, datetime.time(9)) + return datetime.datetime.combine(result, datetime.time(17)) + + +def offset_date(start, duration, duration_type: DURATION_TYPE, calendar: ifcopenshell.entity_instance): + current_date = start + months = getattr(duration, "months", 0) + years = getattr(duration, "years", 0) + + abs_duration = abs(duration.days + months * 30 + years * 12 * 30) + date_offset = datetime.timedelta(days=1 if duration.days > 0 else -1) + while abs_duration > 0: + if duration_type == "ELAPSEDTIME" or not is_calendar_applicable(current_date, calendar): + abs_duration -= 1 + elif is_working_day(current_date, calendar): + abs_duration -= 1 + current_date += date_offset + if duration.days > 0: + current_date = get_soonest_working_day(current_date, duration_type, calendar) + else: + current_date = get_recent_working_day(current_date, duration_type, calendar) + return current_date + + +def get_soonest_working_day(start, duration_type: DURATION_TYPE, calendar: ifcopenshell.entity_instance): + if duration_type == "ELAPSEDTIME" or not is_calendar_applicable(start, calendar): + return start + while not is_working_day(start, calendar): + if not is_calendar_applicable(start, calendar): + break + start += datetime.timedelta(days=1) + return start + + +def get_recent_working_day(start, duration_type: DURATION_TYPE, calendar: ifcopenshell.entity_instance): + if duration_type == "ELAPSEDTIME" or not is_calendar_applicable(start, calendar): + return start + while not is_working_day(start, calendar): + if not is_calendar_applicable(start, calendar): + break + start -= datetime.timedelta(days=1) + return start + + +@cache +def is_working_day(day, calendar: ifcopenshell.entity_instance) -> bool: + is_working_day = False + for work_time in calendar.WorkingTimes or []: + if is_work_time_applicable_to_day(work_time, day): + is_working_day = True + break + if not is_working_day: + return is_working_day + for work_time in calendar.ExceptionTimes or []: + if is_work_time_applicable_to_day(work_time, day): + is_working_day = False + break + return is_working_day + + +@cache +def is_calendar_applicable(day, calendar: ifcopenshell.entity_instance) -> bool: + if not calendar or not calendar.WorkingTimes: + return False + is_applicable = False + for work_time in calendar.WorkingTimes or []: + if is_day_in_work_time(day, work_time): + is_applicable = True + break + return is_applicable + + +def is_day_in_work_time(day, work_time: ifcopenshell.entity_instance) -> bool: + is_day_in_work_time = True + if isinstance(day, datetime.datetime): + day = datetime.date(day.year, day.month, day.day) + # 4 IfcWorktime Start + if start := work_time[4]: + start = ifcopenshell.util.date.ifc2datetime(start) + if day > start: + is_day_in_work_time = True + else: + is_day_in_work_time = False + # 5 IfcWorktime Finish + if finish := work_time[5]: + finish = ifcopenshell.util.date.ifc2datetime(finish) + if day < finish: + is_day_in_work_time = True + else: + is_day_in_work_time = False + return is_day_in_work_time + + +def is_work_time_applicable_to_day(work_time: ifcopenshell.entity_instance, day) -> bool: + if not is_day_in_work_time(day, work_time): + return False + if not work_time.RecurrencePattern: + return True + + if isinstance(day, datetime.datetime): + day = datetime.date(day.year, day.month, day.day) + recurrence = work_time.RecurrencePattern + recurrence_type: RECURRENCE_TYPE = recurrence.RecurrenceType + if recurrence_type == "DAILY": + if not recurrence.Interval and not recurrence.Occurrences: + return True + # 4 IfcWorktime Start + if not work_time[4]: + return False + return False # TODO + elif recurrence_type == "WEEKLY": + if not recurrence.Interval and not recurrence.Occurrences: + return (day.weekday() + 1) in recurrence.WeekdayComponent + # 4 IfcWorktime Start + if not work_time[4]: + return False + return False # TODO + elif recurrence_type == "MONTHLY_BY_DAY_OF_MONTH": + if not recurrence.Interval and not recurrence.Occurrences: + return day.day in recurrence.DayComponent + return False # TODO + elif recurrence_type == "MONTHLY_BY_POSITION": + if not recurrence.Interval and not recurrence.Occurrences: + return (day.weekday() + 1) in recurrence.WeekdayComponent and floor(day.day / 7) + 1 == recurrence[ + "Position" + ] + return False # TODO + elif recurrence_type == "YEARLY_BY_DAY_OF_MONTH": + if not recurrence.Interval and not recurrence.Occurrences: + return day.month in recurrence.MonthComponent and day.day in recurrence.DayComponent + return False # TODO + elif recurrence_type == "YEARLY_BY_POSITION": + if not recurrence.Interval and not recurrence.Occurrences: + return ( + day.month in recurrence.MonthComponent + and (day.weekday() + 1) in recurrence.WeekdayComponent + and floor(day.day / 7) + 1 == recurrence.Position + ) + return False # TODO + + +def get_task_work_schedule(task: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + parent_task = get_parent_task(task) + if parent_task: + return get_task_work_schedule(parent_task) or get_task_work_schedule(task) + else: + for rel in task.HasAssignments: + if rel.is_a("IfcRelAssignsToControl") and rel.RelatingControl.is_a("IfcWorkSchedule"): + return rel.RelatingControl + return None + + +def get_nested_tasks(task: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + return [obj for obj in ifcopenshell.util.element.get_components(task) if obj.is_a("IfcTask")] + + +def get_parent_task(task: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + nests = task.Nests + if nests and (obj := nests[0].RelatingObject).is_a("IfcTask"): + return obj + + +def get_all_nested_tasks(task: ifcopenshell.entity_instance) -> Generator[ifcopenshell.entity_instance]: + for nested_task in get_nested_tasks(task): + yield nested_task + yield from get_all_nested_tasks(nested_task) + + +def get_work_schedule_tasks(work_schedule: ifcopenshell.entity_instance) -> Generator[ifcopenshell.entity_instance]: + """Get all work schedule tasks, including the nested ones.""" + for root_task in get_root_tasks(work_schedule): + yield root_task + yield from get_all_nested_tasks(root_task) + + +def get_root_tasks(work_schedule: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + return [obj for rel in work_schedule.Controls for obj in rel.RelatedObjects if obj.is_a("IfcTask")] + + +def guess_date_range(work_schedule: ifcopenshell.entity_instance): + earliest = None + latest = None + root_tasks = get_root_tasks(work_schedule) + tasks_with_assignements = [] + for task in root_tasks: + if has_task_outputs(task) or has_task_inputs(task): + tasks_with_assignements.append(task) + for sub_task in get_all_nested_tasks(task): + if has_task_outputs(sub_task) or has_task_inputs(sub_task): + tasks_with_assignements.append(sub_task) + + for task in tasks_with_assignements: + derived_start = derive_date(task, "ScheduleStart", is_earliest=True) + derived_finish = derive_date(task, "ScheduleFinish", is_latest=True) + if derived_start and (not earliest or derived_start < earliest): + earliest = derived_start + if derived_finish and (not latest or derived_finish > latest): + latest = derived_finish + return earliest, latest + + +def get_task_outputs( + task: ifcopenshell.entity_instance, is_recursive: bool = False +) -> set[ifcopenshell.entity_instance]: + if is_recursive: + return {o for subtask in [task] + list(get_all_nested_tasks(task)) for o in get_task_outputs(subtask)} + return {rel.RelatingProduct for rel in task.HasAssignments if rel.is_a("IfcRelAssignsToProduct")} + + +def get_task_inputs( + task: ifcopenshell.entity_instance, is_recursive: bool = False +) -> set[ifcopenshell.entity_instance]: + if is_recursive: + return {o for subtask in [task] + list(get_all_nested_tasks(task)) for o in get_task_inputs(subtask)} + return {o for rel in task.OperatesOn for o in rel.RelatedObjects if o.is_a("IfcProduct")} + + +def get_task_resources( + task: ifcopenshell.entity_instance, is_recursive: bool = False +) -> set[ifcopenshell.entity_instance]: + if is_recursive: + return {r for subtask in [task] + list(get_all_nested_tasks(task)) for r in get_task_resources(subtask)} + return {o for rel in task.OperatesOn for o in rel.RelatedObjects if o.is_a("IfcResource")} + + +def has_task_outputs(task: ifcopenshell.entity_instance) -> bool: + return len(get_task_outputs(task)) > 0 + + +def has_task_inputs(task: ifcopenshell.entity_instance) -> bool: + return len(get_task_inputs(task)) > 0 + + +def get_tasks_for_product( + product: ifcopenshell.entity_instance, schedule: Optional[ifcopenshell.entity_instance] = None +) -> tuple[list[ifcopenshell.entity_instance], list[ifcopenshell.entity_instance]]: + """ + Get all tasks assigned to or referenced by the given product. + + :param product: An object that is assigned tasks or references tasks. + :param schedule: An optional string representing the schedule name to filter tasks by. + + :return: A tuple of two lists: + - The first list contains all tasks assigned to the product. + - The second list contains all tasks referenced by the product that are part of the given schedule. + """ + inputs = [ + assignement.RelatingProcess + for assignement in product.HasAssignments + if assignement.is_a("IfcRelAssignsToProcess") and assignement.RelatingProcess.is_a("IfcTask") + ] + outputs = [ + obj + for ref in product.ReferencedBy + if ref.is_a("IfcRelAssignsToProduct") + for obj in ref.RelatedObjects + if obj.is_a("IfcTask") + ] + + if schedule: + inputs = [task for task in inputs if get_task_work_schedule(task).id() == schedule.id()] + outputs = [task for task in outputs if get_task_work_schedule(task).id() == schedule.id()] + + return inputs, outputs + + +def get_sequence_assignment(task: ifcopenshell.entity_instance, sequence="successor"): + if sequence == "successor": + relationship_attr = "IsPredecessorTo" + elif sequence == "predecessor": + relationship_attr = "IsSuccessorFrom" + else: + return [] + + relationship = getattr(task, relationship_attr, None) + if relationship: + return relationship + + for rel in task.Nests or []: + result = get_sequence_assignment(rel.RelatingObject, sequence) + if result: + return result + + return [] + + +def get_related_products( + relating_product: Optional[ifcopenshell.entity_instance] = None, + related_object: Optional[ifcopenshell.entity_instance] = None, +) -> set[ifcopenshell.entity_instance]: + """Gets the related products being output by a task + + :param relating_product: One of the products already output by the task. + :param related_object: The IfcTask that you want to get all the related + products for. + :return: A set of IfcProducts output by the IfcTask. + + Example: + + .. code:: python + + # Let's imagine we are creating a construction schedule. All tasks + # need to be part of a work schedule. + schedule = ifcopenshell.api.sequence.add_work_schedule(model, name="Construction Schedule A") + + # Let's create a construction task. Note that the predefined type is + # important to distinguish types of tasks. + task = ifcopenshell.api.sequence.add_task(model, + work_schedule=schedule, name="Build wall", identification="A", predefined_type="CONSTRUCTION") + + # Let's say we have a wall somewhere. + wall = ifcopenshell.api.root.create_entity(model, ifc_class="IfcWall") + + # Let's construct that wall! + ifcopenshell.api.sequence.assign_product(relating_product=wall, related_object=task) + + # This will give us a set with that wall in it. + products = ifcopenshell.util.sequence.get_related_products(related_object=task) + """ + + assert relating_product or related_object, "Either relating_product or related_object must be provided." + + products = set() + if not related_object and relating_product: + for reference in relating_product.ReferencedBy: + if reference.is_a("IfcRelAssignsToProduct"): + related_object = reference.RelatedObjects[0] + + if related_object: + assignments = related_object.HasAssignments + for assignment in assignments: + if assignment.is_a("IfcRelAssignsToProduct"): + products.add(assignment.RelatingProduct.id()) + + return products diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape.py new file mode 100644 index 0000000000000000000000000000000000000000..75c15b693530cb6bb88f17dbc4fbc9ce6cc141ae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape.py @@ -0,0 +1,744 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2023 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import shapely +import shapely.ops +import numpy as np +import numpy.typing as npt +import ifcopenshell.ifcopenshell_wrapper as W +import ifcopenshell.util.element +import ifcopenshell.util.placement +import ifcopenshell.util.representation +from ifcopenshell.util.shape_builder import VectorType +from math import radians, cos +from ifcopenshell.geom import ShapeElementType +from typing import Optional, Literal, Union + +tol = 1e-6 +AXIS_LITERAL = Literal["X", "Y", "Z"] +VECTOR_3D = tuple[float, float, float] + +MatrixType = npt.NDArray[np.float64] +"""`npt.NDArray[np.float64]`""" + +# NOTE: See IfcGeomRepresentation.h for W.Triangulation buffer types. + +# NOTE: For functions that return a single scalar ensure to use .item() to +# return the Python float instead of numpy float +# as it's less intrusive (doesn't promote numpy arrays on interactions), +# doesn't fail saving to IFC +# and precise enough anyway (internally Python floats are doubles). + + +def is_x(value: float, x: float, tolerance: Optional[float] = None) -> bool: + """Checks whether a value is equivalent to X given a tolerance + + :param value: Input value + :param x: The value to compare to + :param tolerance: The tolerance to use. Defaults to 1e-6. + :return: True or false + """ + if tolerance is None: + tolerance = tol + return abs(x - value) < tolerance + + +def get_volume(geometry: W.Triangulation) -> float: + """Calculates the total internal volume of a geometry + + Volumes of non-manifold geometry will be unpredictable. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The volume in m3 + """ + + # https://stackoverflow.com/questions/1406029/how-to-calculate-the-volume-of-a-3d-mesh-object-the-surface-of-which-is-made-up + def signed_triangle_volume(p1, p2, p3): + v321 = p3[0] * p2[1] * p1[2] + v231 = p2[0] * p3[1] * p1[2] + v312 = p3[0] * p1[1] * p2[2] + v132 = p1[0] * p3[1] * p2[2] + v213 = p2[0] * p1[1] * p3[2] + v123 = p1[0] * p2[1] * p3[2] + return (1.0 / 6.0) * (-v321 + v231 + v312 - v132 - v213 + v123) + + # Can't optimize it using buffers - performance seems to get only worse. + verts = geometry.verts + faces = geometry.faces + grouped_verts = [[verts[i], verts[i + 1], verts[i + 2]] for i in range(0, len(verts), 3)] + volumes = [ + signed_triangle_volume(grouped_verts[faces[i]], grouped_verts[faces[i + 1]], grouped_verts[faces[i + 2]]) + for i in range(0, len(faces), 3) + ] + return abs(sum(volumes)) + + +def get_x(geometry: W.Triangulation) -> float: + """Calculates the X length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The X dimension + """ + verts_flat = get_vertices(geometry).ravel() + return (np.max(verts_flat[0::3]) - np.min(verts_flat[0::3])).item() + + +def get_y(geometry: W.Triangulation) -> float: + """Calculates the Y length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Y dimension + """ + verts_flat = get_vertices(geometry).ravel() + return (np.max(verts_flat[1::3]) - np.min(verts_flat[1::3])).item() + + +def get_z(geometry: W.Triangulation) -> float: + """Calculates the Z length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z dimension + """ + verts_flat = get_vertices(geometry).ravel() + return (np.max(verts_flat[2::3]) - np.min(verts_flat[2::3])).item() + + +def get_max_xy(geometry: W.Triangulation) -> float: + """Gets the maximum X or Y length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The maximum possible value out of the X and Y dimension + """ + return max(get_x(geometry), get_y(geometry)) + + +def get_max_xyz(geometry: W.Triangulation) -> float: + """Gets the maximum X, Y, or Z length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The maximum possible value out of the X, Y, and Z dimension + """ + return max(get_x(geometry), get_y(geometry), get_z(geometry)) + + +def get_min_xyz(geometry: W.Triangulation) -> float: + """Gets the minimum X, Y, or Z length of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The minimum possible value out of the X, Y, and Z dimension + """ + return min(get_x(geometry), get_y(geometry), get_z(geometry)) + + +def get_shape_matrix(shape: ShapeElementType) -> MatrixType: + """Formats the transformation matrix of a shape as a 4x4 numpy array + + :param shape: Shape output calculated by IfcOpenShell + :return: A 4x4 numpy array representing the transformation matrix + """ + return np.frombuffer(shape.transformation_buffer, "d").reshape((4, 4), order="F") + + +def get_bbox_centroid(geometry: W.Triangulation) -> tuple[float, float, float]: + """Calculates the bounding box centroid of the geometry + + The centroid is in local coordinates relative to the object's placement. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: A tuple representing the XYZ centroid + """ + vertices_array = get_vertices(geometry) + return (np.min(vertices_array, axis=0) + np.max(vertices_array, axis=0)) / 2 + + +def get_vert_centroid(geometry: W.Triangulation) -> tuple[float, float, float]: + """Calculates the average vertex centroid of the geometry + + The centroid is in local coordinates relative to the object's placement. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: A tuple representing the XYZ centroid + """ + return np.mean(get_vertices(geometry), axis=0) + + +def get_element_bbox_centroid( + element: ifcopenshell.entity_instance, geometry: W.Triangulation +) -> npt.NDArray[np.float64]: + """Calculates the element's bounding box centroid + + The centroid is in global coordinates. Note that if you have the shape, it + is more efficient to use :func:`get_shape_bbox_centroid`. + + :param element: The element occurrence + :param geometry: Geometry output calculated by IfcOpenShell + :return: A tuple representing the XYZ centroid + """ + centroid = get_bbox_centroid(geometry) + if not element.ObjectPlacement or not element.ObjectPlacement.is_a("IfcLocalPlacement"): + return np.array(centroid) + mat = ifcopenshell.util.placement.get_local_placement(element.ObjectPlacement) + return (mat @ np.array([*centroid, 1.0]))[0:3] + + +def get_shape_bbox_centroid(shape: ShapeElementType, geometry: W.Triangulation) -> npt.NDArray[np.float64]: + """Calculates the shape's bounding box centroid + + The centroid is in global coordinates. Note that if you do not have the + shape, you can use :func:`get_element_bbox_centroid`. + + :param shape: Shape output calculated by IfcOpenShell + :param geometry: Geometry output calculated by IfcOpenShell + :return: A tuple representing the XYZ centroid + """ + centroid = get_bbox_centroid(geometry) + return (get_shape_matrix(shape) @ np.array([*centroid, 1.0]))[0:3] + + +def get_vertices(geometry: W.Triangulation, is_2d: bool = False) -> npt.NDArray[np.float64]: + """Get all the vertices as a numpy array + + Vertices are in local coordinates. + + :param geometry: Geometry output calculated by IfcOpenShell + :param is_2d: Set to True to to get XY coordinates only. + :return: A numpy array listing all the vertices and their coordinates. + Array shape: (n, 3), where n - number of vertices. + """ + if is_2d: + return np.frombuffer(geometry.verts_buffer, "d").reshape(-1, 3)[:, :2] + return np.frombuffer(geometry.verts_buffer, "d").reshape(-1, 3) + + +def get_edges(geometry: W.Triangulation) -> npt.NDArray[np.int32]: + """Get all the edges as a numpy array + + Results are a nested numpy array e.g. [[e1v1, e1v2], [e2v1, e2v2], ...] + + Note that although geometry always holds triangulated faces, edges will + represent the original tessellation or BRep's faces, which may be quads or + ngons. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: A numpy array listing all the edges. + Array shape: (n, 2), where n - number of edges. + """ + return np.frombuffer(geometry.edges_buffer, dtype="i").reshape(-1, 2) + + +def get_faces(geometry: W.Triangulation) -> npt.NDArray[np.int32]: + """Get all the faces as a numpy array + + Faces are always triangulated. If the shape is a BRep and you want to get + the original untriangulated output, refer to :func:`get_edges`. + + Results are a nested numpy array e.g. [[f1v1, f1v2, f1v3], [f2v1, f2v2, f2v3], ...] + + :param geometry: Geometry output calculated by IfcOpenShell + :return: A numpy array listing all the faces. + Array shape: (n, 3), where n - number of faces. + """ + return np.frombuffer(geometry.faces_buffer, dtype="i").reshape(-1, 3) + + +def get_material_colors(geometry: W.Triangulation) -> npt.NDArray[np.float64]: + """Get material colors as a numpy array. + + :return: A numpy array listing RGBA color for each shape's material. + Array shape: (1, 4). + """ + # colors_buffer comes from geometry.materials and doesn't account + # for colors that can be set by some other way (e.g. IfcIndexedColourMap). + return np.frombuffer(geometry.colors_buffer, dtype="d").reshape(-1, 4) + + +def get_normals(geometry: W.Triangulation) -> npt.NDArray[np.float64]: + """Get vertex normals as a numpy array. + + See geometry settings documentation for settings that affect normals. + + :return: A numpy array listing normal for each shape vertex. + Array shape: (1, 3). + """ + return np.frombuffer(geometry.normals_buffer, dtype="d").reshape(-1, 3) + + +def get_shape_material_styles(geometry: W.Triangulation) -> tuple[W.style, ...]: + """Get list of material styles.""" + return geometry.materials + + +def get_faces_material_style_ids(geometry: W.Triangulation) -> npt.NDArray[np.int32]: + """Get material styles ids for the geometry faces. + + Return a list of corresponding indices of styles from get_shape_material_styles for each face. + If face has no style assigned, index -1 is used. + """ + return np.frombuffer(geometry.material_ids_buffer, dtype="i") + + +def get_faces_representation_item_ids(geometry: W.Triangulation) -> npt.NDArray[np.int32]: + """Get representation item ids for the geometry faces.""" + return np.frombuffer(geometry.item_ids_buffer, dtype="i") + + +def get_edges_representation_item_ids(geometry: W.Triangulation) -> npt.NDArray[np.int32]: + """Get representation item ids for the geometry edges. + + Can be useful for geometry without faces and in general is more universal + since it's possible that geometry will have elements with and without faces. + """ + return np.frombuffer(geometry.edges_item_ids_buffer, dtype="i") + + +def get_shape_vertices(shape: ShapeElementType, geometry: W.Triangulation) -> npt.NDArray[np.float64]: + """Get the shape's vertices as a numpy array + + Vertices are in global coordinates. If you do not have the shape, you can + use :func:`get_element_vertices`. + + Results are a nested numpy array e.g. [[v1x, v1y, v1z], [v2x, v2y, v2z], ...] + + :param shape: Shape output calculated by IfcOpenShell + :param geometry: Geometry output calculated by IfcOpenShell + :return: A numpy array listing all the vertices. Each vertex is a numpy array with XYZ coordinates. + Array shape: (n, 3), where n - number of vertices. + """ + verts = get_vertices(geometry) + mat = get_shape_matrix(shape) + return np.delete((mat @ np.hstack((verts, np.ones((len(verts), 1)))).T).T, -1, axis=1) + + +def get_element_vertices(element: ifcopenshell.entity_instance, geometry: W.Triangulation) -> npt.NDArray[np.float64]: + """Get the element's vertices as a numpy array + + Vertices are in global coordinates. Note that if you have the shape, it is + more efficient to use :func:`get_shape_vertices`. + + Results are a nested numpy array e.g. [[v1x, v1y, v1z], [v2x, v2y, v2z], ...] + + :param element: The element occurrence + :param geometry: Geometry output calculated by IfcOpenShell + :return: A numpy array listing all the vertices. Each vertex is a numpy array with XYZ coordinates. + """ + verts = get_vertices(geometry) + if not element.ObjectPlacement or not element.ObjectPlacement.is_a("IfcLocalPlacement"): + return verts + mat = ifcopenshell.util.placement.get_local_placement(element.ObjectPlacement) + return np.delete((mat @ np.hstack((verts, np.ones((len(verts), 1)))).T).T, -1, axis=1) + + +def get_bottom_elevation(geometry: W.Triangulation) -> float: + """Gets the lowest local Z ordinate of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + verts_flat = get_vertices(geometry).ravel() + return np.min(verts_flat[2::3]).item() + + +def get_top_elevation(geometry: W.Triangulation) -> float: + """Gets the highest local Z ordinate of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + verts_flat = get_vertices(geometry).ravel() + return np.max(verts_flat[2::3]).item() + + +def get_shape_bottom_elevation(shape: ShapeElementType, geometry: W.Triangulation) -> float: + """Gets the lowest global Z ordinate of the shape + + If you do not have the shape, you can use :func:`get_element_bottom_elevation` + instead. + + :param shape: Shape output calculated by IfcOpenShell + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + return min([v[2] for v in get_shape_vertices(shape, geometry)]) + + +def get_shape_top_elevation(shape: ShapeElementType, geometry: W.Triangulation) -> float: + """Gets the highest global Z ordinate of the shape + + If you do not have the shape, you can use :func:`get_element_top_elevation` + instead. + + :param shape: Shape output calculated by IfcOpenShell + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + return max([v[2] for v in get_shape_vertices(shape, geometry)]) + + +def get_element_bottom_elevation(element: ifcopenshell.entity_instance, geometry: W.Triangulation) -> float: + """Gets the lowest global Z ordinate of the element + + Note that if you have the shape, it is more efficient to use + :func:`get_shape_bottom_elevation`. + + :param element: The element occurrence + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + return min([v[2] for v in get_element_vertices(element, geometry)]) + + +def get_element_top_elevation(element: ifcopenshell.entity_instance, geometry: W.Triangulation) -> float: + """Gets the highest global Z ordinate of the element + + Note that if you have the shape, it is more efficient to use + :func:`get_shape_top_elevation`. + + :param element: The element occurrence + :param geometry: Geometry output calculated by IfcOpenShell + :return: The Z value + """ + return max([v[2] for v in get_element_vertices(element, geometry)]) + + +def get_bbox(vertices: npt.NDArray[np.float64]) -> tuple[npt.NDArray[np.float64], npt.NDArray[np.float64]]: + """Gets the bounding box of vertices + + :param vertices: An iterable of vertices + :return: The bounding box value represented as a tuple of two numpy arrays. + The first holds the bottom left corner and the second holds the top + right. E.g. (np.array([minx, miny, minz]), np.array([maxx, maxy, + maxz])) + """ + return (np.min(vertices, axis=0), np.max(vertices, axis=0)) + + +def get_area_vf(vertices: npt.NDArray[np.float64], faces: npt.NDArray[np.int32]) -> float: + """Calculates the surface area given a list of vertices and triangulated faces + + :param vertices: A list of 3D vertices, such as returned from get_vertices. + :param faces: A list of faces, such as returned from get_faces. + :return: The surface area. + """ + # Calculate the triangle normal vectors + v1 = vertices[faces[:, 1]] - vertices[faces[:, 0]] + v2 = vertices[faces[:, 2]] - vertices[faces[:, 0]] + triangle_normals = np.cross(v1, v2) + + # Normalize the normal vectors to get their length (i.e., triangle area) + triangle_areas = np.linalg.norm(triangle_normals, axis=1) / 2 + + # Sum up the areas to get the total area of the mesh + mesh_area = np.sum(triangle_areas) + + return mesh_area.item() + + +def get_area(geometry: W.Triangulation) -> float: + """Calculates the surface area of the geometry + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The surface area. + """ + vertices = get_vertices(geometry) + faces = get_faces(geometry) + return get_area_vf(vertices, faces) + + +def get_side_area( + geometry: W.Triangulation, + axis: AXIS_LITERAL = "Y", + direction: Optional[VectorType] = None, + angle: float = 90.0, +) -> float: + """Calculates the total surface area of surfaces that are visible from the specified axis + + This is typically useful for calculating elevational areas. For example, + you might want to calculate the side area of a wall (i.e. only one side, + not both). + + Surfaces do not need to be exactly perpendicular in the direction of the + specified axis. A surface is counted so long as it is visible from that + axis. + + Note that this calculates the actual area, not the projected 2D area. If + you want the projected area, use :func:`get_footprint_area`. + + :param geometry: Geometry output calculated by IfcOpenShell + :param axis: Either X, Y, or Z. Defaults to Y, which is used for standard + walls. + :param angle: Accept angle difference between face and axis, in degrees. + E.g. default angle 90 will find all faces with angle < 90 degrees. + :return: The surface area. + """ + if direction is None: + direction = {"X": (1.0, 0.0, 0.0), "Y": (0.0, 1.0, 0.0), "Z": (0.0, 0.0, 1.0)}[axis] + + vertices = get_vertices(geometry) + faces = get_faces(geometry) + + # Calculate the triangle normal vectors + v1 = vertices[faces[:, 1]] - vertices[faces[:, 0]] + v2 = vertices[faces[:, 2]] - vertices[faces[:, 0]] + triangle_normals = np.cross(v1, v2) + + # Normalize the normal vectors + triangle_normals = triangle_normals / np.linalg.norm(triangle_normals, axis=1)[:, np.newaxis] + direction = np.array(direction) / np.linalg.norm(direction) + + # Find the faces with a normal vector pointing in the desired +Y normal direction + # normal_tol < 0 is pointing away, = 0 is perpendicular, and > 0 is pointing towards. + normal_tol = 0.01 # For angle 90 it's close to perpendicular, but with a fuzz for numerical tolerance + acceptable_dot = cos(radians(angle)) + normal_tol + dot_products = np.dot(triangle_normals, direction) + filtered_face_indices = np.where(dot_products > acceptable_dot)[0] + filtered_faces = faces[filtered_face_indices] + return get_area_vf(vertices, filtered_faces) + + +def get_max_side_area(geometry: W.Triangulation) -> float: + """Returns the maximum X, Y, or Z side area + + See :func:`get_side_area` for how side area is calculated. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The maximum surface area from either the X, Y, or Z axis. + """ + return max(get_side_area(geometry, axis="X"), get_side_area(geometry, axis="Y"), get_side_area(geometry, axis="Z")) + + +def get_top_area(geometry: W.Triangulation) -> float: + return get_side_area(geometry, axis="Z", angle=45) + + +def get_footprint_area( + geometry: W.Triangulation, + axis: AXIS_LITERAL = "Z", + direction: Optional[VECTOR_3D] = None, +) -> float: + """Calculates the total footprint (i.e. projected) surface area visible from along an axis + + This is typically useful for calculating footprint areas. For example, you + might want to calculate the top-down footprint area of a slab, ignoring + slopes in the slab. + + Surfaces do not need to be exactly perpendicular in the direction of the + specified axis. A surface is counted so long as it is visible from that + axis. + + Note that this calculates the 2D projected area, not the actual surface + area. If you want the actual area, use :func:`get_side_area`. + + :param geometry: Geometry output calculated by IfcOpenShell + :param axis: Either X, Y, or Z. Defaults to Z. + :param direction: An XYZ iterable (e.g. (0., 0., 1.)). If a direction + vector is specified, this overrides the axis argument. + :return: The surface area. + """ + if direction is None: + direction = {"X": (1.0, 0.0, 0.0), "Y": (0.0, 1.0, 0.0), "Z": (0.0, 0.0, 1.0)}[axis] + + vertices = get_vertices(geometry) + faces = get_faces(geometry) + + # Calculate the triangle normal vectors + v1 = vertices[faces[:, 1]] - vertices[faces[:, 0]] + v2 = vertices[faces[:, 2]] - vertices[faces[:, 0]] + triangle_normals = np.cross(v1, v2) + + # Normalize the normal vectors + triangle_normals = triangle_normals / np.linalg.norm(triangle_normals, axis=1)[:, np.newaxis] + direction = np.array(direction) / np.linalg.norm(direction) + + # Find the faces with a normal vector pointing in the desired direction using dot product + # normal_tol < 0 is pointing away, = 0 is perpendicular, and > 0 is pointing towards. + normal_tol = 0.01 # Close to perpendicular, but with a fuzz for numerical tolerance + dot_products = np.dot(triangle_normals, direction) + filtered_face_indices = np.where(dot_products > normal_tol)[0] + filtered_faces = faces[filtered_face_indices] + + # Flatten vertices along the direction + vertices = vertices.copy() # Buffers are read-only. + for idx in range(len(vertices)): + vertices[idx] = vertices[idx] - np.dot(vertices[idx], direction) * direction + + # Now flatten 3D vertices into 2D polygons which can be unioned to find a footprint. + + # Create an orthonormal basis using the direction + d = np.array(direction) / np.linalg.norm(direction) + + # Find a vector not parallel to d + a = np.array(d) + if not np.isclose(a[2], 1.0, atol=0.01): # If d is not along the Z-axis + a[2] += 0.01 # Small perturbation to make it not parallel + else: + a = np.array([1, 0, 0]) + + # First basis vector + b = np.cross(d, a) + b /= np.linalg.norm(b) + + # Second basis vector + c = np.cross(d, b) + + # Project the flattened vertices onto the basis to get 2D coordinates + vertices_2d = np.array([[np.dot(v, b), np.dot(v, c)] for v in vertices]) + + polygons = [shapely.Polygon(vertices_2d[face]) for face in filtered_faces] + unioned_polygon = shapely.ops.unary_union(polygons) + + return unioned_polygon.area + + +def get_outer_surface_area(geometry: W.Triangulation) -> float: + """Calculates the outer surface area (i.e. all sides except for top and bottom) + + This is typically useful for calculating painted areas of beams which + exclude the end faces (at the minimum and maximum local Z). + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The surface area. + """ + vertices = get_vertices(geometry) + faces = get_faces(geometry) + + # Calculate the triangle normal vectors + v1 = vertices[faces[:, 1]] - vertices[faces[:, 0]] + v2 = vertices[faces[:, 2]] - vertices[faces[:, 0]] + triangle_normals = np.cross(v1, v2) + + # Normalize the normal vectors + triangle_normals = triangle_normals / np.linalg.norm(triangle_normals, axis=1)[:, np.newaxis] + + # Find the faces with a normal vector that isn't +Z or -Z + filtered_face_indices = np.where(abs(triangle_normals[:, 2]) < tol)[0] + filtered_faces = faces[filtered_face_indices] + return get_area_vf(vertices, filtered_faces) + + +def get_footprint_perimeter(geometry: W.Triangulation) -> float: + """Calculates the footprint perimeter of the geometry + + All faces with a negative Z normal are considered and the distance of all + perimeter edges are totaled. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The perimeter length + """ + vertices = get_vertices(geometry) + faces = get_faces(geometry) + + # Calculate the triangle normal vectors + v1 = vertices[faces[:, 1]] - vertices[faces[:, 0]] + v2 = vertices[faces[:, 2]] - vertices[faces[:, 0]] + triangle_normals = np.cross(v1, v2) + + # Normalize the normal vectors + triangle_normals = triangle_normals / np.linalg.norm(triangle_normals, axis=1)[:, np.newaxis] + + # Find the faces with a normal vector pointing in the negative Z direction + negative_z_face_indices = np.where(triangle_normals[:, 2] < -tol)[0] + negative_z_faces = faces[negative_z_face_indices] + + # Initialize the set of counted edges and the perimeter + all_edges = set() + shared_edges = set() + perimeter = 0 + + # Loop through each face + for face in negative_z_faces: + # Loop through each edge of the face + for i in range(3): + # Get the indices of the two vertices that define the edge + edge = (face[i], face[(i + 1) % 3]) + # Keep track of shared edges. Perimeter edges are unshared. + if (edge[1], edge[0]) in all_edges or (edge[0], edge[1]) in all_edges: + shared_edges.add((edge[0], edge[1])) + shared_edges.add((edge[1], edge[0])) + else: + all_edges.add(edge) + + return np.sum([np.linalg.norm(vertices[e[0]] - vertices[e[1]]) for e in (all_edges - shared_edges)]).item() + + +def get_profiles(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + """Gets all 2D profiles used in the definition of a parametric shape + + Profiles may be retrieved either from material profile sets or from swept + solid extrusions. This is useful for later doing 2D take-off from profiles. + + :param element: The element occurrence + :return: A list of profiles + """ + material = ifcopenshell.util.element.get_material(element, should_skip_usage=True) + if material and material.is_a("IfcMaterialProfileSet"): + return [mp.Profile for mp in material.MaterialProfiles] + return [e.SweptArea for e in get_extrusions(element)] + + +def get_extrusions(element: ifcopenshell.entity_instance) -> Union[list[ifcopenshell.entity_instance], None]: + """Gets all extruded area solids used to define an element's model body geometry + + :param element: The element occurrence + :return: A list of extrusion representation items or `None` if element has no representation. + """ + representation = ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW") + if not representation: + return + representation = ifcopenshell.util.representation.resolve_representation(representation) + extrusions = [] + for item in representation.Items: + while True: + if item.is_a("IfcExtrudedAreaSolid"): + extrusions.append(item) + break + elif item.is_a("IfcBooleanResult"): + item = item.FirstOperand + else: + break + return extrusions + + +def get_base_extrusions(element: ifcopenshell.entity_instance) -> Union[list[ifcopenshell.entity_instance], None]: + """Gets all base extrusions used to define an element's model body geometry + + A base extrusion is assumed to be an extrusion prior to all boolean + results. + + :param element: The element occurrence + :return: A list of extrusion representation items or `None` if element has no representation. + """ + if not (rep := ifcopenshell.util.representation.get_representation(element, "Model", "Body", "MODEL_VIEW")): + return + extrusions = [] + for item in ifcopenshell.util.representation.resolve_representation(rep).Items: + while item.is_a("IfcBooleanResult"): + item = item.FirstOperand + if item.is_a("IfcExtrudedAreaSolid"): + extrusions.append(item) + return extrusions + + +def get_total_edge_length(geometry: W.Triangulation) -> float: + """Calculates the total length of edges in a given geometry. + + :param geometry: Geometry output calculated by IfcOpenShell + :return: The total length of all edges in the geometry. + """ + vertices = get_vertices(geometry) + vertices = vertices[get_edges(geometry)] + return np.linalg.norm(vertices[:, 1] - vertices[:, 0], axis=1).sum().item() diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape_builder.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape_builder.py new file mode 100644 index 0000000000000000000000000000000000000000..0811b8798cdcc20e62f38aeed48453ee929483c5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/shape_builder.py @@ -0,0 +1,2046 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022, 2023 @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from __future__ import annotations +import numpy as np +import numpy.typing as npt +import collections +import collections.abc +import ifcopenshell +import ifcopenshell.api +import ifcopenshell.util.element +import ifcopenshell.util.placement +import ifcopenshell.util.representation +import ifcopenshell.util.unit +from math import cos, sin, pi, tan, radians, degrees, atan, sqrt +from typing import Union, Optional, Literal, Any, TYPE_CHECKING +from collections.abc import Sequence +from itertools import chain + +PRECISION = 1.0e-5 + + +if TYPE_CHECKING: + # NOTE: mathutils is never used at runtime in ifcopenshell, + # only for type checking to ensure methods are compatible with + # Blender vectors. + from mathutils import Vector + + # Support both numpy arrays and python sequences as inputs. + VectorType = Union[Sequence[float], Vector, np.ndarray] +else: + # Ensure it's exportable, so other modules can reuse it for typing. + VectorType = Any + +SequenceOfVectors = Union[Sequence[VectorType], np.ndarray] + + +def V(*args: Union[float, int, VectorType, SequenceOfVectors]) -> npt.NDArray[np.float64]: + """Convert floats / vector / sequence of vectors to numpy array. + + Note that `float` argument type also allows passing ints, + which will be converted to floats (a double type) as IfcOpenShell is strict + about setting int/float attributes. + """ + if isinstance(args[0], (float, int)): + return np.array(args, dtype="d") + + assert len(args) == 1, "Only single argument is supported if providing a vector or a sequence of them." + return np.array(args[0], dtype="d") + + +def ifc_safe_vector_type(v: Union[VectorType, SequenceOfVectors]) -> Any: + """Convert vector / sequence of vectors to a list of floats + that's safe to save IFC attribute. + + Basically converting all numbers in sequences to Python floats. + """ + return np.array(v, dtype="d").tolist() + + +def is_x(value: float, x: float, si_conversion: Optional[float] = None) -> bool: + if si_conversion is not None: + value = value * si_conversion + return (x + PRECISION) > value > (x - PRECISION) + + +def round_to_precision(x: float, si_conversion: float) -> float: + return round(x * si_conversion, 5) / si_conversion + + +def np_round_to_precision(v: np.ndarray, si_conversion: float) -> np.ndarray: + return np.round(v * si_conversion, 5) / si_conversion + + +def np_normalized(v: VectorType) -> np.ndarray: + return np.divide(v, np.linalg.norm(v)) + + +def np_matrix_normalized(matrix: np.ndarray) -> np.ndarray: + # Ensure translation is not affected. + scale_factors = np.linalg.norm(matrix[:3, :3], axis=0) + rotation_matrix = matrix.copy() + rotation_matrix[:3, :3] /= scale_factors + return rotation_matrix + + +def np_lerp(a: VectorType, b: VectorType, t: float) -> np.ndarray: + return a + np.subtract(b, a) * t + + +def np_to_3d(v: VectorType, z: float = 0.0) -> np.ndarray: + """Convert 2D/4D vector to 3D.""" + l = len(v) + if l == 2: + return np.append(v, z) + elif l == 4: + return v[:3] + assert False, f"Unexpected vector length: {l} ({v})." + + +def np_to_4d(v: VectorType, z: float = 0.0, w: float = 1.0) -> np.ndarray: + """Convert 2D/3D vector to 4D (e.g. for multiplying with 4x4 matrix).""" + l = len(v) + if l == 2: + return np.append(v, (z, w)) + elif l == 3: + return np.append(v, w) + assert False, f"Unexpected vector length: {l} ({v})." + + +def np_to_4x4(matrix_3x3: np.ndarray) -> np.ndarray: + """Convert 3x3 matrix to 4x4.""" + matrix_4x4 = np.pad(matrix_3x3, ((0, 1), (0, 1))) + matrix_4x4[3, 3] = 1 + return matrix_4x4 + + +def np_apply_matrix(vectors: SequenceOfVectors, matrix: npt.NDArray) -> npt.NDArray: + """ + :param vectors: Nx3 array of vectors. + :param matrix: 4x4 transformation matrix. + """ + m3x3 = matrix[:3, :3] + translation = matrix[:3, 3] + return vectors @ m3x3.T + translation + + +def np_angle(a: VectorType, b: VectorType) -> float: + """Get angle between vectors in radians. + Designed to work similar to `Vector.angle`. + """ + return np.arccos(np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))) + + +def np_angle_signed(a: VectorType, b: VectorType) -> float: + """Get signed angle between 2D vectors in radians (clockwise is positive). + Designed to work similar to `Vector.angle_signed`. + """ + assert len(a) == 2 and len(b) == 2, "Only 2D vectors are supported." + det = a[1] * b[0] - a[0] * b[1] + dot = np.dot(a, b) + return np.arctan2(det, dot) + + +def np_translation_matrix(vector: VectorType) -> npt.NDArray[np.float64]: + """Get translation matrix. + + Designed to be similar to mathutils Matrix.Rotation but to use numpy. + + :param vector: 3D translation vector. + :return: An 4x4 identity matrix with a translation + """ + eye = np.eye(4, dtype=np.float64) + M_TRANSLATION = (slice(0, 3), 3) + eye[M_TRANSLATION] = vector + return eye + + +def np_rotation_matrix( + angle: float, size: int, axis: Optional[Union[Literal["X", "Y", "Z"], VectorType]] = None +) -> np.ndarray: + """Get rotation matrix. Designed to be similar to mathutils Matrix.Rotation but to use numpy. + + :param float: Rotation angle, in radians. + :param size: Matrix size ([2;4]). + :param axis: Rotation axis. + For 2x2 matrices Z assumed by default and argument can be omitted, + for 3x3/4x4 matrices could be either axis literal + or a rotation axis presented as a vector. + :return: Rotation matrix. + """ + if not (2 <= size <= 4): + raise ValueError(f"Size must be [2;4], got {size}.") + + cos_theta: float = np.cos(angle) + sin_theta: float = np.sin(angle) + if size == 2: + return np.array([[cos_theta, -sin_theta], [sin_theta, cos_theta]]) + + assert axis, "For non-2D matrices 'axis' argument is not optional." + if isinstance(axis, str): + if axis == "X": + matrix = np.array([[1, 0, 0], [0, cos_theta, -sin_theta], [0, sin_theta, cos_theta]]) + elif axis == "Y": + matrix = np.array([[cos_theta, 0, sin_theta], [0, 1, 0], [-sin_theta, 0, cos_theta]]) + elif axis == "Z": + matrix = np.array([[cos_theta, -sin_theta, 0], [sin_theta, cos_theta, 0], [0, 0, 1]]) + else: + # Assume axis is a vector. + axis = axis / np.linalg.norm(axis) + # Rodrigues' rotation formula. + K = np.array([[0, -axis[2], axis[1]], [axis[2], 0, -axis[0]], [-axis[1], axis[0], 0]]) + matrix = cos_theta * np.eye(3) + (1 - cos_theta) * np.outer(axis, axis) + sin_theta * K + if size == 4: + return np_to_4x4(matrix) + return matrix + + +def np_matrix_to_euler(matrix: np.ndarray) -> tuple[float, float, float]: + """Convert a rotation matrix to Euler angles. + + Designed to work similar to `mathutils.Matrix.to_euler`. + Currently only XYZ rotation is supported. + """ + if matrix.shape not in ((3, 3), (4, 4)): + raise ValueError(f"Matrix must be 3x3 or 4x4, got {matrix.shape}.") + + matrix = np_matrix_normalized(matrix) + y = -np.arcsin(matrix[2, 0]) + cos_y = np.cos(y) + x = np.arctan2(matrix[2, 1] / cos_y, matrix[2, 2] / cos_y) + z = np.arctan2(matrix[1, 0] / cos_y, matrix[0, 0] / cos_y) + return (x, y, z) + + +def np_normal(vectors: SequenceOfVectors) -> np.ndarray: + """Normal of 3D Polygon. + + Designed to work similar to `mathutils.geometry.normal`. + """ + assert len(vectors) == 3, "3 vectors required" + # TODO: can be optimized? + verts_np = np.array(vectors[:3]) + v0, v1, v2 = verts_np[:3] + edge1 = v1 - v0 + edge2 = v2 - v0 + normal = np.cross(edge1, edge2) + norm = np.linalg.norm(normal) + return normal / norm + + +def np_intersect_line_line( + v1: VectorType, v2: VectorType, v3: VectorType, v4: VectorType +) -> tuple[np.ndarray, np.ndarray]: + """Get 2 closest points on each line. + First line - (v1, v2). Second line - (v3, v4). + + Designed to work similar to `mathutils.geometry.intersect_line_line`. + """ + # TODO: could be optimized? + d1 = np.subtract(v2, v1) + d2 = np.subtract(v4, v3) + + # Cross product of the directions + cross_d1_d2 = np.cross(d1, d2) + cross_d1_d2_norm: float = np.linalg.norm(cross_d1_d2) + + # Check if the lines are parallel. + if is_x(cross_d1_d2_norm, 0): + raise ValueError("Lines are parallel and do not intersect uniquely.") + + r = np.subtract(v3, v1) + t = np.dot(np.cross(r, d2), cross_d1_d2) / (cross_d1_d2_norm**2) + u = np.dot(np.cross(r, d1), cross_d1_d2) / (cross_d1_d2_norm**2) + + # Closest points on each line + point_on_line1 = v1 + t * d1 + point_on_line2 = v3 + u * d2 + return point_on_line1, point_on_line2 + + +def intersect_x_axis_2d(p1: VectorType, p2: VectorType, y=0) -> Optional[float]: + """Intersect a line defined by 2 points to a horizontal line defined by y + + Useful for axis-aligned intersection checks. + + :param p1: First 2D point of the line, order doesn't matter + :param p2: Second 2D point of the line, order doesn't matter + :param y: Intersect at this y value (i.e. defaults to y=0) + """ + x1, y1 = p1 + x2, y2 = p2 + if is_x(y1, y2): # Parallel + return + t = (y - y1) / (y2 - y1) + return x1 + t * (x2 - x1) + + +# Note: using ShapeBuilder try not to reuse IFC elements in the process +# otherwise you might run into situation where builder.mirror or other operation +# is applied twice during one run to the same element +# which might produce undesirable results + + +class ShapeBuilder: + def __init__(self, ifc_file: ifcopenshell.file): + self.file = ifc_file + + def polyline( + self, + points: SequenceOfVectors, + closed: bool = False, + position_offset: Optional[VectorType] = None, + arc_points: Sequence[int] = (), + ) -> ifcopenshell.entity_instance: + """ + Generate an IfcIndexedPolyCurve based on the provided points. + + :param points: List of 2d or 3d points + :param closed: Whether polyline should be closed. Default is `False` + :param position_offset: offset to be applied to all points + :param arc_points: Indices of the middle points for arcs. For creating an arc segment, + provide 3 points: `arc_start`, `arc_middle` and `arc_end` to `points` and add the `arc_middle` + point's index to `arc_points` + :return: IfcIndexedPolyCurve + + Example: + + .. code:: python + + # rectangle + points = Vector((0, 0)), Vector((1, 0)), Vector((1, 1)), Vector((0, 1)) + position = Vector((2, 0)) + # #2=IfcIndexedPolyCurve(#1,(IfcLineIndex((1,2,3,4,1))),$) + polyline = builder.polyline(points, closed=True, position_offset=position) + + # arc between points (1,0) and (0,1). Second point in the arc should be it's middle + points = Vector((1, 0)), Vector((0.707, 0.707)), Vector((0, 1)), Vector((0,2)) + arc_points = (1,) # point with index 1 is a middle of the arc + # 4=IfcIndexedPolyCurve(#3,(IfcArcIndex((1,2,3)),IfcLineIndex((3,4,1))),$) + curved_polyline = builder.polyline(points, closed=False, position_offset=position, arc_points=arc_points) + """ + + if arc_points and self.file.schema == "IFC2X3": + raise Exception("Arcs are not supported for IFC2X3.") + + points: np.ndarray + points = np.array(points) + if position_offset is not None: + points = points + position_offset + + if self.file.schema == "IFC2X3": + ifc_points = [self.file.create_entity("IfcCartesianPoint", p) for p in points.tolist()] + if closed: + ifc_points.append(ifc_points[0]) + ifc_curve = self.file.createIfcPolyline(Points=ifc_points) + return ifc_curve + + dimensions = len(points[0]) + if dimensions == 2: + ifc_points = self.file.create_entity("IfcCartesianPointList2D", points.tolist()) + elif dimensions == 3: + ifc_points = self.file.create_entity("IfcCartesianPointList3D", points.tolist()) + else: + raise Exception(f"Point has unexpected number of dimensions - {dimensions}.") + + if not closed and not arc_points: + ifc_curve = self.file.createIfcIndexedPolyCurve(Points=ifc_points) + return ifc_curve + + # if curve is closed or we have arc points + # then we do need to create segments + segments = [] + cur_i = 0 + closed_by_arc = False + while cur_i < len(points) - 1: + cur_i_ifc = cur_i + 1 + if cur_i + 1 in arc_points: + if cur_i_ifc + 1 < len(points): + segments.append((cur_i_ifc, cur_i_ifc + 1, cur_i_ifc + 2)) + else: + segments.append((cur_i_ifc, cur_i_ifc + 1, 1)) + closed_by_arc = True + cur_i += 2 + else: + segments.append((cur_i_ifc, cur_i_ifc + 1)) + cur_i += 1 + + if closed and not closed_by_arc: + segments.append((len(points), 1)) + + ifc_segments = [] + # because IfcLineIndex support 2+ points + # we merge neighbor line segments into one + current_line_segment = [] + last_segment = len(segments) - 1 + for seg_i, segment in enumerate(segments): + if len(segment) == 2: + # check if `current_line_segment` is empty to avoid duplicated indices like `IfcLineIndex((1,2,2,3,3,4,4,1))` + current_line_segment += segment if not current_line_segment else segment[1:] + + if current_line_segment and (len(segment) == 3 or seg_i == last_segment): + ifc_segments.append(self.file.createIfcLineIndex(current_line_segment)) + current_line_segment = [] + + if len(segment) == 3: + ifc_segments.append(self.file.createIfcArcIndex(segment)) + + # NOTE: IfcIndexPolyCurve support only consecutive segments + ifc_curve = self.file.createIfcIndexedPolyCurve(Points=ifc_points, Segments=ifc_segments) + return ifc_curve + + @staticmethod + def get_rectangle_coords(size: VectorType = (1.0, 1.0), position: Optional[VectorType] = None) -> np.ndarray: + """ + Get rectangle coords arranged as below: + + :: + + 3 2 + 0 1 + + :param size: rectangle size, could be either 2d or 3d, defaults to `(1,1)` + :param position: rectangle position, default to `None`. + if `position` not specified zero-vector will be used + :return: list of rectangle coords + """ + size_np = np.array(size) + + if position is None: + dimensions = len(size_np) + points = np.full((4, dimensions), 0.0) + else: + points = np.tile(position, (4, 1)) + + # Support both 2d and 3d sizes defined in different dimensions. + non_empty_coords = np.nonzero(size_np)[0] + points[1, non_empty_coords[0]] += size_np[non_empty_coords[0]] + points[2] += size_np + points[3, non_empty_coords[1]] += size_np[non_empty_coords[1]] + return points + + def rectangle( + self, size: VectorType = (1.0, 1.0), position: Optional[VectorType] = None + ) -> ifcopenshell.entity_instance: + """ + Generate a rectangle polyline. + + :param size: rectangle size, could be either 2d or 3d, defaults to `(1,1)` + :param position: rectangle position, default to `None`. + if `position` not specified zero-vector will be used + :return: IfcIndexedPolyCurve + """ + return self.polyline(self.get_rectangle_coords(size, position), closed=True) + + def circle(self, center: VectorType = (0.0, 0.0), radius: float = 1.0) -> ifcopenshell.entity_instance: + """ + :param center: circle 2D position + :param radius: radius of the circle + :return: IfcCircle + """ + ifc_center = self.create_axis2_placement_2d(center) + ifc_curve = self.file.create_entity("IfcCircle", ifc_center, radius) + return ifc_curve + + def plane( + self, location: VectorType = (0.0, 0.0, 0.0), normal: VectorType = (0.0, 0.0, 1.0) + ) -> ifcopenshell.entity_instance: + """ + Create IfcPlane. + + :param location: plane position. + :param normal: plane normal direction. + :return: IfcPlane + """ + + if np.allclose(np.round(normal, 2), (0.0, 0.0, 1.0)): + arbitrary_vector = (0.0, 1.0, 0.0) + else: + arbitrary_vector = (0.0, 0.0, 1.0) + x_axis = np_normalized(np.cross(normal, arbitrary_vector)) + axis_placement = self.create_axis2_placement_3d(location, normal, x_axis) + return self.file.createIfcPlane(axis_placement) + + # TODO: explain points order for the curve_between_two_points + # because the order is important and defines the center of the curve + # currently it seems like the first point shifted by x-axis defines the center + def curve_between_two_points(self, points: tuple[VectorType, VectorType]) -> ifcopenshell.entity_instance: + """Simple circle based curve between two points + Good for creating curves and fillets, won't work for continuous ellipse shapes. + + :param points: tuple of 2 points. + :return: IfcIndexePolyCurve + """ + diff = np.subtract(points[1], points[0]) + max_diff_i = np.argmax(np.abs(diff)) + diff_sign = np.zeros_like(diff) + diff_sign[max_diff_i] = np.sign(diff[max_diff_i]) + + # diff should be applied only to one axis + # if it's applied to two (like in a case of circle) it will create + # a straight line instead of a curve + diff = (0.01, 0.01) * diff_sign + middle_point = points[0] + diff + + points: list[VectorType] + points = [points[0], middle_point, points[1]] + points = [ifc_safe_vector_type(p) for p in points] + seg = self.file.createIfcArcIndex((1, 2, 3)) + ifc_points = self.file.createIfcCartesianPointList2D(points) + curve = self.file.createIfcIndexedPolyCurve(Points=ifc_points, Segments=[seg]) + return curve + + def get_trim_points_from_mask( + self, + x_axis_radius: float, + y_axis_radius: float, + trim_points_mask: Sequence[int], + position_offset: Optional[VectorType] = None, + ) -> np.ndarray: + """Handy way to get edge points of the ellipse like shape of a given radiuses. + + Mask points are numerated from 0 to 3 ccw starting from (x_axis_radius/2; 0). + + Example: mask (0, 1, 2, 3) will return points (x, 0), (0, y), (-x, 0), (0, -y) + """ + points = np.array( + ( + (x_axis_radius, 0), + (0, y_axis_radius), + (-x_axis_radius, 0), + (0, -y_axis_radius), + ) + ) + # list type is important for selecting items by the indices. + trim_points = points[list(trim_points_mask)] + if position_offset is None: + return trim_points + return trim_points + position_offset + + def create_ellipse_curve( + self, + x_axis_radius: float, + y_axis_radius: float, + position: VectorType = (0.0, 0.0), + trim_points: SequenceOfVectors = (), + ref_x_direction: VectorType = (1.0, 0.0), + trim_points_mask: Sequence[int] = (), + ) -> ifcopenshell.entity_instance: + """ + Ellipse trimming points should be specified in counter clockwise order. + + For example, if you need to get the part of the ellipse ABOVE y-axis, you need to use mask (0,2). Below y-axis - (2,0) + + For more information about trim_points_mask check builder.get_trim_points_from_mask + + Notion: trimmed ellipse also contains polyline between trim points, meaning IfcTrimmedCurve could be used + for further extrusion. + """ + ifc_position = self.create_axis2_placement_2d(position, ref_x_direction) + ifc_ellipse = self.file.createIfcEllipse( + Position=ifc_position, SemiAxis1=x_axis_radius, SemiAxis2=y_axis_radius + ) + + if not trim_points: + if not trim_points_mask: + return ifc_ellipse + trim_points = self.get_trim_points_from_mask( + x_axis_radius, y_axis_radius, trim_points_mask, position_offset=position + ) + + trim1 = [self.file.create_entity("IfcCartesianPoint", ifc_safe_vector_type(trim_points[0]))] + trim2 = [self.file.create_entity("IfcCartesianPoint", ifc_safe_vector_type(trim_points[1]))] + + trim_ellipse = self.file.createIfcTrimmedCurve( + BasisCurve=ifc_ellipse, Trim1=trim1, Trim2=trim2, SenseAgreement=True, MasterRepresentation="CARTESIAN" + ) + return trim_ellipse + + def profile( + self, + outer_curve: ifcopenshell.entity_instance, + name: Optional[str] = None, + inner_curves: Sequence[ifcopenshell.entity_instance] = (), + profile_type: str = "AREA", + ) -> ifcopenshell.entity_instance: + """Create a profile. + + :param outer_curve: Profile IfcCurve. + :param inner_curves: a sequence of IfcCurves. + + :return: IfcArbitraryClosedProfileDef or IfcArbitraryProfileDefWithVoids. + """ + # inner_curves could be used as a tool for boolean operation + # but if any point of inner curve will go outside the outer curve + # it will just add shape on top instead of "boolean" it + # because of that you can't create bool edges of outer_curve this way + + if outer_curve.Dim != 2: + raise Exception( + f"Outer curve for IfcArbitraryClosedProfileDef/IfcIfcArbitraryProfileDefWithVoid should be 2D to be valid, currently it has {outer_curve.Dim} dimensions.\n" + "Ref: https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcArbitraryClosedProfileDef.htm#8.15.3.1.4-Formal-propositions" + ) + + kwargs = { + "ProfileName": name, + "ProfileType": profile_type, + "OuterCurve": outer_curve, + } + + if inner_curves: + if not isinstance(inner_curves, collections.abc.Iterable): + inner_curves = [inner_curves] + if any(curve.Dim != 2 for curve in inner_curves): + raise Exception( + "WARNING. InnerCurve for IfcIfcArbitraryProfileDefWithVoid sould be 2D to be valid, " + "currently on one of the inner curves is using different amount of dimensions.\n" + "Ref: https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcArbitraryClosedProfileDef.htm#8.15.3.1.4-Formal-propositions" + ) + + profile = self.file.create_entity("IfcArbitraryProfileDefWithVoids", InnerCurves=inner_curves, **kwargs) + else: + profile = self.file.create_entity("IfcArbitraryClosedProfileDef", **kwargs) + return profile + + def translate( + self, + curve_or_item: Union[ifcopenshell.entity_instance, Sequence[ifcopenshell.entity_instance]], + translation: VectorType, + create_copy: bool = False, + ) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]]: + """ + Translate curve/representaiton item/representation. + + :param curve_or_item: A single item to translate or a sequence of them. + :param translation: Translation vector. + :param create_copy: Whether to translate the provided item or it's copy. + :return: Translated curve/item/representation or a sequence of them. + """ + + multiple_objects = isinstance(curve_or_item, collections.abc.Iterable) + if not multiple_objects: + curve_or_item = [curve_or_item] + + processed_objects: list[ifcopenshell.entity_instance] = [] + for c in curve_or_item: + if create_copy: + c = ifcopenshell.util.element.copy_deep(self.file, c) + + if c.is_a() in ("IfcIndexedPolyCurve", "IfcPolyline"): + coords = self.get_polyline_coords(c) + coords += translation + self.set_polyline_coords(c, coords) + + elif c.is_a("IfcCircle") or c.is_a("IfcExtrudedAreaSolid") or c.is_a("IfcEllipse"): + base_position = np.array(c.Position.Location.Coordinates) + c.Position.Location.Coordinates = ifc_safe_vector_type(base_position + translation) + + elif c.is_a("IfcTessellatedFaceSet"): + c.Coordinates.CoordList = ifc_safe_vector_type(np.array(c.Coordinates.CoordList) + translation) + + elif c.is_a("IfcShapeRepresentation"): + for item in c.Items: + self.translate(item, translation) + + elif c.is_a("IfcTrimmedCurve"): + base_position = np.array(c.Trim1[0].Coordinates) + c.Trim1[0].Coordinates = ifc_safe_vector_type(base_position + translation) + + base_position = np.array(c.Trim2[0].Coordinates) + c.Trim2[0].Coordinates = ifc_safe_vector_type(base_position + translation) + + self.translate(c.BasisCurve, translation) + + else: + raise Exception(f"{c} is not supported for translate() method.") + + processed_objects.append(c) + + return processed_objects if multiple_objects else processed_objects[0] + + def rotate_2d_point( + self, + point_2d: VectorType, + angle: float = 90.0, + pivot_point: VectorType = (0.0, 0.0), + counter_clockwise: bool = False, + ) -> np.ndarray: + angle_rad = radians(angle) * (1 if counter_clockwise else -1) + relative_point = np.array(point_2d) - pivot_point + relative_point = np_rotation_matrix(angle_rad, 2) @ relative_point + final_point = relative_point + pivot_point + return final_point + + def rotate( + self, + curve_or_item: Union[ifcopenshell.entity_instance, Sequence[ifcopenshell.entity_instance]], + angle: float = 90.0, + pivot_point: VectorType = (0.0, 0.0), + counter_clockwise: bool = False, + create_copy: bool = False, + ) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]]: + """Rotate curve/representaiton item/representation. + + :param curve_or_item: A single item to rotate or a sequence of them. + :param angle: Rotation angle, in degrees. + :param pivot_point: Rotation pivot point. + :param counter_clockwise: Whether rotation is counter-clockwise. + :param create_copy: Whether to rotate the provided item or it's copy. + :return: Rotated curve/representaiton item/representation or a sequence of them. + """ + + multiple_objects = isinstance(curve_or_item, collections.abc.Iterable) + if not multiple_objects: + curve_or_item = [curve_or_item] + + processed_objects: list[ifcopenshell.entity_instance] = [] + for c in curve_or_item: + if create_copy: + c = ifcopenshell.util.element.copy_deep(self.file, c) + + if c.is_a() in ("IfcIndexedPolyCurve", "IfcPolyline"): + original_coords = self.get_polyline_coords(c) + coords = [self.rotate_2d_point(co, angle, pivot_point, counter_clockwise) for co in original_coords] + self.set_polyline_coords(c, coords) + + elif c.is_a("IfcCircle"): + base_position = c.Position.Location.Coordinates + new_position = self.rotate_2d_point(base_position, angle, pivot_point, counter_clockwise) + c.Position.Location.Coordinates = ifc_safe_vector_type(new_position) + + elif c.is_a("IfcExtrudedAreaSolid"): + # TODO: add support for Z-axis too + base_position = c.Position.Location.Coordinates + new_position = self.rotate_2d_point(base_position[:2], angle, pivot_point, counter_clockwise) + new_position = np_to_3d(new_position) + new_position[2] = base_position[2] + c.Position.Location.Coordinates = ifc_safe_vector_type(new_position) + + # TODO: add inner axis too and test it + self.rotate(c.SweptArea.OuterCurve, angle, pivot_point, counter_clockwise) + + else: + raise Exception(f"{c} is not supported for rotate() method.") + + processed_objects.append(c) + + return processed_objects if multiple_objects else processed_objects[0] + + def mirror_2d_point( + self, + point_2d: VectorType, + mirror_axes: VectorType = (1.0, 1.0), + mirror_point: VectorType = (0.0, 0.0), + ) -> np.ndarray: + """mirror_axes - along which axes mirror will be applied""" + mirror_axes: np.ndarray = np.where(np.array(mirror_axes) > 0, -1, 1) + mirror_point: np.ndarray = np.array(mirror_point) + relative_point = point_2d - mirror_point + relative_point = relative_point * mirror_axes + point_2d_res = relative_point + mirror_point + return point_2d_res + + def create_axis2_placement_3d( + self, + position: VectorType = (0.0, 0.0, 0.0), + z_axis: VectorType = (0.0, 0.0, 1.0), + x_axis: VectorType = (1.0, 0.0, 0.0), + ) -> ifcopenshell.entity_instance: + """ + Create IfcAxis2Placement3D. + + :param position: placement position (Axis). + :param z_axis: local Z axis direction. + :param x_axis: local X axis direction (RefDirection). + :return: IfcAxis2Placement3D + """ + return self.file.create_entity( + "IfcAxis2Placement3D", + self.file.create_entity("IfcCartesianPoint", ifc_safe_vector_type(position)), + Axis=self.file.create_entity("IfcDirection", ifc_safe_vector_type(z_axis)), + RefDirection=self.file.create_entity("IfcDirection", ifc_safe_vector_type(x_axis)), + ) + + def create_axis2_placement_3d_from_matrix( + self, + matrix: Union[npt.NDArray[np.float64], None] = None, + ) -> ifcopenshell.entity_instance: + """ + Create IfcAxis2Placement3D from numpy matrix. + + :param matrix: 4x4 transformation matrix, defaults to `np.eye(4)` + :return: IfcAxis2Placement3D + """ + if matrix is None: + matrix = np.eye(4, dtype=float) + return self.create_axis2_placement_3d(position=matrix[:3, 3], z_axis=matrix[:3, 2], x_axis=matrix[:3, 0]) + + def create_axis2_placement_2d( + self, position: VectorType = (0.0, 0.0), x_direction: Optional[VectorType] = None + ) -> ifcopenshell.entity_instance: + """Create IfcAxis2Placement2D.""" + ref_direction = ( + self.file.create_entity("IfcDirection", ifc_safe_vector_type(x_direction)) if x_direction else None + ) + return self.file.create_entity( + "IfcAxis2Placement2D", + Location=self.file.create_entity("IfcCartesianPoint", ifc_safe_vector_type(position)), + RefDirection=ref_direction, + ) + + def vertex(self, position: VectorType = (0.0, 0.0, 0.0)) -> ifcopenshell.entity_instance: + """Create a topological vertex + + Commonly used in structural point elements. + + :param position: The 3D coordinate of the vertex + :return: IfcVertexPoint + """ + return self.file.create_entity( + "IfcVertexPoint", self.file.create_entity("IfcCartesianPoint", ifc_safe_vector_type(position)) + ) + + def edge( + self, start: VectorType = (0.0, 0.0, 0.0), end: VectorType = (1.0, 0.0, 0.0) + ) -> ifcopenshell.entity_instance: + """Create a topological edge + + :param start: The start coordinates of the vertex. + :param end: The end coordinates of the vertex. + :return: IfcEdge + """ + return self.file.create_entity("IfcEdge", self.vertex(start), self.vertex(end)) + + def face(self, points: SequenceOfVectors) -> ifcopenshell.entity_instance: + """Create a single topological face + + There are many types of faces, but for now we only support planar + polyloop defined faces with an outer boundary. + + :param points: ordered list of 3d coordinates representing the outer boundary + :return: IfcFace + """ + verts = [self.file.createIfcCartesianPoint(p) for p in ifc_safe_vector_type(points)] + return self.file.createIfcFace([self.file.createIfcFaceOuterBound(self.file.createIfcPolyLoop(verts), True)]) + + def mirror( + self, + curve_or_item: Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]], + mirror_axes: Union[VectorType, SequenceOfVectors] = (1.0, 1.0), + mirror_point: VectorType = (0.0, 0.0), + create_copy: bool = False, + placement_matrix: Optional[np.ndarray] = None, + ) -> Union[ifcopenshell.entity_instance, list[ifcopenshell.entity_instance]]: + """Mirror curve/representaiton item/representation. + + :param curve_or_item: A single item to mirror or a sequence of them. + :param mirror_axes: A vector of values, should have value > 0 for axes where mirror should be applied. + Example: mirroring `A(1,0)` by axis `(1,0)` will result in `A'(-1,0)` + + Also could be a list of mirrors to apply to `curve_or_item` + multiple mirror_axes will result in multiple resulting curves + Example: curve_or_item = [a, b], mirror_axes=[v1, v2], result = [av1, av2, bv1, bv2] + :param mirror_point: Point relative to which mirror should be applied. + :param create_copy: Whether to mirror the provided item or it's copy. + :param placement_matrix: Optional placement matrix to use for polylines. + :return: Mirrored curve/item/representation or a sequence of them. + """ + + # TODO: need to add placement_matrix for other types besides polycurve? + + np_XY = slice(2) + np_X, np_Y, np_Z = 0, 1, 2 + + multiple_objects = isinstance(curve_or_item, collections.abc.Iterable) + curve_or_item = [curve_or_item] if not multiple_objects else curve_or_item + multiple_transformations = not isinstance(mirror_axes[0], (float, int)) + mirror_axes_data = [mirror_axes] if not multiple_transformations else mirror_axes + + processed_objects: list[ifcopenshell.entity_instance] = [] + for curve_or_item_el in curve_or_item: + for mirror_axes in mirror_axes_data: + c = ( + ifcopenshell.util.element.copy_deep(self.file, curve_or_item_el) + if create_copy + else curve_or_item_el + ) + + if c.is_a() in ("IfcIndexedPolyCurve", "IfcPolyline"): + original_coords = self.get_polyline_coords(c) + inverted_placement_matrix = ( + np.linalg.inv(placement_matrix) if placement_matrix is not None else None + ) + coords = [] + for co in original_coords: + co_base = co.copy() + if placement_matrix is not None: + # TODO: add support for Z-axis too + co_base = placement_matrix @ np_to_3d(co_base) + co = self.mirror_2d_point(co_base[np_XY], mirror_axes, mirror_point) + co = np_to_3d(co, z=co_base[2]) + co = (inverted_placement_matrix @ co)[np_XY] + else: + co = self.mirror_2d_point(co_base, mirror_axes, mirror_point) + + coords.append(co) + + self.set_polyline_coords(c, coords) + + elif c.is_a("IfcCircle") or c.is_a("IfcEllipse"): + base_position = c.Position.Location.Coordinates + new_position = self.mirror_2d_point(base_position, mirror_axes, mirror_point) + c.Position.Location.Coordinates = ifc_safe_vector_type(new_position) + + elif c.is_a("IfcExtrudedAreaSolid"): + placement_matrix_ = ifcopenshell.util.placement.get_axis2placement(c.Position)[:3, :3] + base_position = c.Position.Location.Coordinates + # TODO: add support for Z-axis too + new_position = self.mirror_2d_point(base_position[np_XY], mirror_axes, mirror_point) + new_position = np_to_3d(new_position, base_position[np_Z]) + c.Position.Location.Coordinates = ifc_safe_vector_type(new_position) + + # TODO: add support for Z-axis too + self.translate(c.SweptArea.OuterCurve, base_position[np_XY]) + self.mirror(c.SweptArea.OuterCurve, mirror_axes, mirror_point, placement_matrix=placement_matrix_) + self.translate(c.SweptArea.OuterCurve, -new_position[np_XY]) + + if hasattr(c.SweptArea, "InnerCurves"): + for inner_curve in c.SweptArea.InnerCurves: + self.translate(inner_curve, base_position[np_XY]) + self.mirror(inner_curve, mirror_axes, mirror_point, placement_matrix=placement_matrix_) + self.translate(inner_curve, -new_position[np_XY]) + + # extrusion converted to world space + base_extruded_direction = c.ExtrudedDirection.DirectionRatios + extruded_direction = placement_matrix_ @ base_extruded_direction + + # TODO: add support for Z-axis too + # mirror point is ignored for extrusion direction + new_direction = self.mirror_2d_point( + extruded_direction[np_XY], mirror_axes, mirror_point=(0.0, 0.0) + ) + new_direction = np_to_3d(new_direction, extruded_direction[np_Z]) + + # extrusion direction converted back to placement space + new_direction = np.linalg.inv(placement_matrix_) @ (new_direction) + c.ExtrudedDirection.DirectionRatios = ifc_safe_vector_type(new_direction) + + elif c.is_a("IfcTrimmedCurve"): + trim_coords = [c.Trim1[0].Coordinates, c.Trim2[0].Coordinates] + trim_coords = [ + self.mirror_2d_point(base_position, mirror_axes, mirror_point) for base_position in trim_coords + ] + + # if mirror only by 1 axis we need to preserve the counter-clockwise order + # for the trim points + if 0 in mirror_axes: + trim_coords = [trim_coords[1], trim_coords[0]] + + trim_coords = ifc_safe_vector_type(np.array(trim_coords)) + c.Trim1[0].Coordinates, c.Trim2[0].Coordinates = trim_coords + + self.mirror(c.BasisCurve, mirror_axes, mirror_point) + else: + raise Exception(f"{c} is not supported for mirror() method.") + + processed_objects.append(c) + + return processed_objects if (multiple_objects or multiple_transformations) else processed_objects[0] + + def sphere(self, radius: float = 1.0, center: VectorType = (0.0, 0.0, 0.0)) -> ifcopenshell.entity_instance: + """ + :param radius: radius of the sphere, defaults to 1.0 + :param center: sphere position, defaults to `(0.0, 0.0, 0.0)` + + :return: IfcSphere + """ + + ifc_position = self.create_axis2_placement_3d(position=center) + return self.file.createIfcSphere(Radius=radius, Position=ifc_position) + + def block( + self, + position: VectorType = (0.0, 0.0, 0.0), + x_length: float = 1.0, + y_length: float = 1.0, + z_length: float = 1.0, + ) -> ifcopenshell.entity_instance: + """ + :param position: the bottom left (min X/Y of the cube). + :param x_length: the X length, in the +X direction + :param y_length: the Y length, in the +Y direction + :param z_length: the Z length, in the +Z direction + + :return: IfcBlock + """ + return self.file.createIfcBlock(self.create_axis2_placement_3d(position), x_length, y_length, z_length) + + def half_space_solid( + self, plane: ifcopenshell.entity_instance, agreement_flag: bool = False + ) -> ifcopenshell.entity_instance: + """ + :param plane: The IfcPlane representing the half space. + :param agreement_flag: False if +Z represents the void + :return: IfcHalfSpaceSolid + """ + return self.file.createIfcHalfSpaceSolid(plane, AgreementFlag=agreement_flag) + + def extrude( + self, + profile_or_curve: ifcopenshell.entity_instance, + magnitude: float = 1.0, + position: VectorType = (0.0, 0.0, 0.0), + extrusion_vector: VectorType = (0.0, 0.0, 1.0), + position_z_axis: VectorType = (0.0, 0.0, 1.0), + position_x_axis: VectorType = (1.0, 0.0, 0.0), + position_y_axis: Optional[VectorType] = None, + ) -> ifcopenshell.entity_instance: + """Extrude profile or curve to get IfcExtrudedAreaSolid. + + REMEMBER when handling custom axes - IFC is using RIGHT handed coordinate system. + + Position and position axes are in world space, extrusion vector in placement space defined by + position_x_axis/position_y_axis/position_z_axis + + NOTE: changing position also changes the resulting geometry origin. + + :param profile_or_curve: Profile or a curve to extrude (curve will automatically converted to a profile). + :param extrusion_vector: as defined in coordinate system position_x_axis+position_z_axis + :param position: as defined in default IFC coordinate system, not in position_x_axis+position_z_axis + :param position_y_axis: optional, could be used to calculate Z-axis based on Y-axis + :return: IfcExtrudedAreaSolid + """ + + if not magnitude: + raise Exception( + "Extrusion magnitude must be greater than 0 to be valid.\n" + "Ref: https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcPositiveLengthMeasure.htm#8.11.2.71.3-Formal-representation" + ) + + if not profile_or_curve.is_a("IfcProfileDef"): + profile_or_curve = self.profile(profile_or_curve) + + if position_y_axis: + position_z_axis = np.cross(position_x_axis, position_y_axis) + + ifc_position = self.create_axis2_placement_3d(position, position_z_axis, position_x_axis) + ifc_direction = self.file.create_entity("IfcDirection", ifc_safe_vector_type(extrusion_vector)) + extruded_area = self.file.createIfcExtrudedAreaSolid( + SweptArea=profile_or_curve, Position=ifc_position, ExtrudedDirection=ifc_direction, Depth=magnitude + ) + return extruded_area + + def create_swept_disk_solid( + self, path_curve: ifcopenshell.entity_instance, radius: float + ) -> ifcopenshell.entity_instance: + """Create IfcSweptDiskSolid from `path_curve` (must be 3D) and `radius`""" + if path_curve.Dim != 3: + raise Exception( + f"Path curve for IfcSweptDiskSolid should be 3D to be valid, currently it has {path_curve.Dim} dimensions.\n" + "Ref: https://ifc43-docs.standards.buildingsmart.org/IFC/RELEASE/IFC4x3/HTML/lexical/IfcSweptDiskSolid.htm#8.8.3.42.4-Formal-propositions" + ) + + disk_solid = self.file.createIfcSweptDiskSolid(Directrix=path_curve, Radius=radius) + return disk_solid + + def get_representation( + self, + context: ifcopenshell.entity_instance, + items: Union[ifcopenshell.entity_instance, Sequence[ifcopenshell.entity_instance]], + representation_type: Optional[str] = None, + ) -> ifcopenshell.entity_instance: + """Create IFC representation for the specified context and items. + + :param context: IfcGeometricRepresentationSubContext + :param items: could be a list or single curve/IfcExtrudedAreaSolid + :param representation_type: Explicitly specified RepresentationType, defaults to `None`. + If not provided it will be guessed from the items types + :return: IfcShapeRepresentation + """ + if not isinstance(items, collections.abc.Iterable): + items = [items] + + if not representation_type: + representation_type = ifcopenshell.util.representation.guess_type(items) + + return self.file.create_entity( + ( + "IfcTopologyRepresentation" + if representation_type in ("Vertex", "Edge", "Path", "Face", "Shell") + else "IfcShapeRepresentation" + ), + ContextOfItems=context, + RepresentationIdentifier=context.ContextIdentifier, + RepresentationType=representation_type, + Items=items, + ) + + def deep_copy(self, element: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + return ifcopenshell.util.element.copy_deep(self.file, element) + + # UTILITIES + def extrude_kwargs(self, axis: Literal["Y", "X", "Z"]) -> dict[str, tuple[float, float, float]]: + """Shortcut to get kwargs for `ShapeBuilder.extrude` to extrude by some axis. + + It assumes you have 2D profile in: + XZ plane for Y axis extrusion, \n + YZ plane for X axis extrusion, \n + XY plane for Z axis extrusion, \n + + Extruding by X/Y using other kwargs might break ValidExtrusionDirection.""" + + if axis == "Y": + return { + "position_x_axis": (1, 0, 0), + "position_z_axis": (0, -1, 0), + "extrusion_vector": (0, 0, -1), + } + elif axis == "X": + return { + "position_x_axis": (0, 1, 0), + "position_z_axis": (1, 0, 0), + "extrusion_vector": (0, 0, 1), + } + elif axis == "Z": + return { + "position_x_axis": (1, 0, 0), + "position_z_axis": (0, 0, 1), + "extrusion_vector": (0, 0, 1), + } + + def rotate_extrusion_kwargs_by_z( + self, kwargs: dict[str, Any], angle: float, counter_clockwise: bool = False + ) -> dict[str, VectorType]: + """shortcut to rotate extrusion kwargs by z axis + + `kwargs` expected to have `position_x_axis` and `position_z_axis` keys + + `angle` is a rotation value in radians + + by default rotation is clockwise, to make it counter clockwise use `counter_clockwise` flag + """ + rot = np_rotation_matrix(-angle, 3, "Z") + kwargs = kwargs.copy() # prevent mutation of original kwargs + kwargs["position_x_axis"] = rot @ kwargs["position_x_axis"] + kwargs["position_z_axis"] = rot @ kwargs["position_z_axis"] + return kwargs + + def get_polyline_coords(self, polyline: ifcopenshell.entity_instance) -> np.ndarray: + """polyline should be either `IfcIndexedPolyCurve` or `IfcPolyline`""" + coords = None + if polyline.is_a("IfcIndexedPolyCurve"): + coords = np.array(polyline.Points.CoordList) + elif polyline.is_a("IfcPolyline"): + coords = np.array(tuple(p.Coordinates for p in polyline.Points)) + else: + raise Exception(f"Unsupported polyline type: {polyline.is_a()}") + return coords + + def set_polyline_coords(self, polyline: ifcopenshell.entity_instance, coords: SequenceOfVectors) -> None: + """polyline should be either `IfcIndexedPolyCurve` or `IfcPolyline`""" + if polyline.is_a("IfcIndexedPolyCurve"): + polyline.Points.CoordList = ifc_safe_vector_type(coords) + elif polyline.is_a("IfcPolyline"): + ifc_points: list[ifcopenshell.entity_instance] = polyline.Points + assert len(ifc_points) == len(coords) + for point, co in zip(ifc_points, ifc_safe_vector_type(coords)): + point.Coordinates = co + else: + raise Exception(f"Unsupported polyline type: {polyline.is_a()}") + + def get_simple_2dcurve_data( + self, + coords: SequenceOfVectors, + fillets: Sequence[int] = (), + fillet_radius: Union[float, Sequence[float]] = (), + closed: bool = True, + create_ifc_curve: bool = False, + ) -> tuple[list[VectorType], list[list[int]], Union[ifcopenshell.entity_instance, None]]: + """ + Creates simple 2D curve from set of 2d coords and list of points with fillets. + Simple curve means that all fillets are based on 90 degree angle. + + :param coords: list of 2d coords. Example: ((x0,y0), (x1,y1), (x2, y2)) + :param fillets: list of points from `coords` to base fillet on. Example: (1,) + :param fillet_radius: list of fillet radius for each of corresponding point form `fillets`. + Example: (5.,) Note: `fillet_radius` could be just 1 float value if it's the same for all fillets. + :param closed: boolean whether curve should be closed (whether last point connected to first one). Default: True + :param create_ifc_curve: create IfcIndexedPolyCurve or just return the data. Default: False + + :return: (points, segments, ifc_curve) for the created simple curve + if both points in e are equally far from pt, then v1 is returned. + """ + + def remove_redundant_points( + points: list[VectorType], segments: list[list[int]] + ) -> tuple[list[VectorType], list[list[int]]]: + # prevent mutating + points = [tuple(p) for p in points] + segments = segments.copy() + + # find duplicate points, reindex them in segments + # and mark them to delete later + points_to_remove: list[int] = [] + prev_point = 0 + for i, p in enumerate(points[1:], 1): + if p != points[prev_point]: + prev_point = i + continue + + valid_segments: list[list[int]] = [] + for s in segments: + s = [ps if ps != i else prev_point for ps in s] + valid_segments.append(s) + segments = valid_segments + points_to_remove.append(i) + + # remove duplicate segments + valid_segments = [segment for segment in segments if len(set(segment)) != 1] + points = [point for i, point in enumerate(points) if i not in points_to_remove] + # correct the order in segments + unique_points = sorted(set(chain(*valid_segments))) + unique_points_translation = {prev: i for i, prev in enumerate(unique_points)} + valid_segments = [[unique_points_translation[p] for p in s] for s in valid_segments] + + return points, valid_segments + + # option to use same fillet radius for all fillets + if isinstance(fillet_radius, (float, int)): + fillet_radius = [fillet_radius] * len(fillets) + + fillets: dict[int, float] = dict(zip(fillets, fillet_radius)) + segments: list[list[int]] = [] + points: list[VectorType] = [] + + for co_i, co in enumerate(coords, 0): + current_point = len(points) + if co_i in fillets: + r = fillets[co_i] + rsb = r * cos(pi / 4) # radius shift big + rss = r - rsb # radius shift small + + next_co = coords[(co_i + 1) % len(coords)] + previous_co = coords[co_i - 1] + + # identify fillet type (1 of 4 possible types) + x_direction = 1 if coords[co_i][0] < previous_co[0] or coords[co_i][0] < next_co[0] else -1 + y_direction = 1 if coords[co_i][1] < previous_co[1] or coords[co_i][1] < next_co[1] else -1 + + xshift_point = (co[0] + r * x_direction, co[1]) + middle_point = (co[0] + rss * x_direction, co[1] + rss * y_direction) + yshift_point = (co[0], co[1] + r * y_direction) + + # identify fillet direction + if co[1] == previous_co[1]: + points.extend((xshift_point, middle_point, yshift_point)) + else: + points.extend((yshift_point, middle_point, xshift_point)) + + segments.append([current_point - 1, current_point]) + segments.append([current_point, current_point + 1, current_point + 2]) + else: + points.append(co) + if co_i != 0: + segments.append([current_point - 1, current_point]) + + if closed: + segments.append([len(points) - 1, 0]) + + # replace negative index + if segments[0][0] == -1: + segments[0][0] = len(points) - 1 + + # sometime fillet points could match previous or next points in line + # I remove them at the end to avoid making fillet algorithm even less readable + points, segments = remove_redundant_points(points, segments) + ifc_curve = None + if create_ifc_curve: + ifc_points = self.file.createIfcCartesianPointList2D(ifc_safe_vector_type(points)) + ifc_segments = [] + for segment in segments: + segment = [i + 1 for i in segment] + if len(segment) == 2: + ifc_segments.append(self.file.createIfcLineIndex(segment)) + elif len(segment) == 3: + ifc_segments.append(self.file.createIfcArcIndex(segment)) + + ifc_curve = self.file.createIfcIndexedPolyCurve(Points=ifc_points, Segments=ifc_segments) + return (points, segments, ifc_curve) + + def create_z_profile_lips_curve( + self, + FirstFlangeWidth: float, + SecondFlangeWidth: float, + Depth: float, + Girth: float, + WallThickness: float, + FilletRadius: float, + ) -> ifcopenshell.entity_instance: + x1 = FirstFlangeWidth + x2 = SecondFlangeWidth + y = Depth / 2 + g = Girth + t = WallThickness + r = FilletRadius + + # fmt: off + coords = ( + (-t/2, y), + (x2, y), + (x2, y-g), + (x2-t, y-g), + (x2-t, y-t), + (t/2, y-t), + (t/2, -y), + (-x1, -y), + (-x1, -y+g), + (-x1+t, -y+g), + (-x1+t, -y+t), + (-t/2, -y+t) + ) + + # option for no additional thickness in outer radius: + # points, segments, ifc_curve = create_curve_from_coords( + # coords, fillets = (0, 1, 4, 5, 6, 7, 10, 11), fillet_radius=r, closed=True, ifc_file=ifc_file + # ) + + points, segments, ifc_curve = self.get_simple_2dcurve_data( + coords, + fillets = (0, 1, 4, 5, 6, 7, 10, 11), + fillet_radius=(r+t, r+t, r, r, r+t, r+t, r, r), + closed=True, create_ifc_curve=True) + # fmt: on + assert ifc_curve + + return ifc_curve + + def create_transition_arc_ifc( + self, width: float, height: float, create_ifc_curve: bool = False + ) -> tuple[SequenceOfVectors, list[list[int]], Union[ifcopenshell.entity_instance, None]]: + """Create an arc in the rectangle with specified width and height. + + If it's not possible to make a complete arc, create an arc with longest radius possible + and straight segment in the middle. + """ + fillet_size = (width / 2) / height + if fillet_size <= 1: + fillet_radius = height * fillet_size + curve_coords = [ + (0.0, 0.0), + (0.0, height), + (width * 0.5, height), + (width, height), + (width, 0.0), + ] + fillets = (1, 3) + else: + fillet_radius = height + curve_coords = [ + (0.0, 0.0), + (0.0, height), + (fillet_radius, height), + (width - fillet_radius, height), + (width, height), + (width, 0.0), + ] + fillets = (1, 4) + points, segments, transition_arc = self.get_simple_2dcurve_data( + curve_coords, fillets, fillet_radius, closed=False, create_ifc_curve=create_ifc_curve + ) + return points, segments, transition_arc + + def mesh(self, points: SequenceOfVectors, faces: Sequence[Sequence[int]]) -> ifcopenshell.entity_instance: + if self.file.schema == "IFC2X3": + return self.faceted_brep(points, faces) + return self.polygonal_face_set(points, faces) + + def faceted_brep(self, points: SequenceOfVectors, faces: Sequence[Sequence[int]]) -> ifcopenshell.entity_instance: + """Generate an IfcFacetedBrep with a closed shell + + Note that :func:`polygonal_face_set` is recommended in IFC4. + + :param points: list of 3d coordinates + :param faces: list of faces consisted of point indices (points indices starting from 0) + :return: IfcFacetedBrep + """ + verts = [self.file.createIfcCartesianPoint(p) for p in ifc_safe_vector_type(points)] + faces: list[ifcopenshell.entity_instance] = [ + self.file.createIfcFace( + [self.file.createIfcFaceOuterBound(self.file.createIfcPolyLoop([verts[v] for v in f]), True)] + ) + for f in faces + ] + return self.file.createIfcFacetedBrep(self.file.createIfcClosedShell(faces)) + + def triangulated_face_set( + self, points: SequenceOfVectors, faces: Sequence[Sequence[int]] + ) -> ifcopenshell.entity_instance: + """ + Generate an IfcTriangulatedFaceSet + + Note that this is not available in IFC2X3. + + :param points: list of 3d coordinates + :param faces: list of triangles consisted of point indices (points indices starting from 0) + :return: IfcTriangulatedFaceSet + """ + ifc_points = self.file.createIfcCartesianPointList3D(ifc_safe_vector_type(points)) + ifc_faces = [[i + 1 for i in face][:3] for face in faces] + return self.file.createIfcTriangulatedFaceSet(Coordinates=ifc_points, CoordIndex=ifc_faces) + + def polygonal_face_set( + self, points: SequenceOfVectors, faces: Sequence[Union[Sequence[int], Sequence[Sequence[int]]]] + ) -> ifcopenshell.entity_instance: + """ + Generate an IfcPolygonalFaceSet + + Note that this is not available in IFC2X3. + + :param points: list of 3d coordinates + :param faces: list of faces consisted of point indices (points indices starting from 0) + in case of multiple sequences per face, the subsequent ones are inner voids + :return: IfcPolygonalFaceSet + """ + + def is_sequence_of_ints(x): + return isinstance(x, Sequence) and not isinstance(x, (str, bytes)) and all(isinstance(el, int) for el in x) + + def is_sequence_of_sequence_of_ints(x): + return ( + isinstance(x, Sequence) and not isinstance(x, (str, bytes)) and all(is_sequence_of_ints(el) for el in x) + ) + + def incr(face): + return [i + 1 for i in face] + + if not all(is_sequence_of_ints(f) or is_sequence_of_sequence_of_ints(f) for f in faces): + raise ValueError("Expected a sequence of int or sequence of sequence of int for each face") + + ifc_points = self.file.createIfcCartesianPointList3D(ifc_safe_vector_type(points)) + ifc_faces = [ + ( + self.file.createIfcIndexedPolygonalFace(incr(face)) + if is_sequence_of_ints(face) + else self.file.createIfcIndexedPolygonalFaceWithVoids(incr(face[0]), list(map(incr, face[1:]))) + ) + for face in faces + ] + return self.file.createIfcPolygonalFaceSet(Coordinates=ifc_points, Faces=ifc_faces) + + def extrude_face_set( + self, + points: SequenceOfVectors, + magnitude: float, + extrusion_vector: VectorType = (0, 0, 1), + offset: Optional[VectorType] = None, + start_cap: bool = True, + end_cap: bool = True, + ) -> ifcopenshell.entity_instance: + """ + Method to extrude by creating face sets rather than creating IfcExtrudedAreaSolid. + + Useful if your representation is already using face sets and you need to avoid using SweptSolid + to assure CorrectItemsForType. + + :param points: list of points, assuming they form consecutive closed polyline. + :param magnitude: extrusion magnitude + :param extrusion_vector: extrusion direction, by default it's extruding by Z+ axis + :param offset: offset from the points + :param start_cap: if True, create start cap, by default it's True + :param end_cap: if True, create end cap, by default it's True + :return: IfcPolygonalFaceSet + """ + + # prevent mutating arguments, deepcopy doesn't work + start_points = np.array(points) + if offset is not None and offset.any(): + start_points += offset + extrusion_offset = np.multiply(extrusion_vector, magnitude) + end_points = start_points + extrusion_offset + + all_points = np.vstack((start_points, end_points)) + faces = [] + n_verts = len(start_points) + last_vert_i = n_verts - 1 + for i in range(last_vert_i): + face = (i, i + 1, n_verts + i + 1, n_verts + i) + faces.append(face) + faces.append((last_vert_i, 0, n_verts + 0, n_verts + last_vert_i)) # close the loop + + if end_cap: + faces.append(tuple(range(n_verts, n_verts * 2))) + if start_cap: + faces.append(tuple(reversed(range(n_verts)))) + + face_set = self.polygonal_face_set(all_points, faces) + return face_set + + # TODO: move MEP to separate shape builder sub module + def mep_transition_shape( + self, + start_segment: ifcopenshell.entity_instance, + end_segment: ifcopenshell.entity_instance, + start_length: float, + end_length: float, + angle: float = 30.0, + profile_offset: VectorType = (0.0, 0.0), + ) -> Union[tuple[ifcopenshell.entity_instance, dict[str, Any]], tuple[None, None]]: + """Generate a MEP transition shape for the provided segments. + + :param start_segment: Starting segment. + :param end_segment: Ending segment. + :param start_length: Start transition length. + :param end_length: End transition length. + :param angle: Transition angle, in degrees. + Good default values from angle = 30/60 deg + 30 degree angle will result in 75 degrees on the transition (= 90 - α/2) - https://i.imgur.com/tcoYDWu.png + :param profile_offset: 2D vector for profile offset. + :return: A tuple of Model/Body/MODEL_VIEW IfcRepresentation and dictionary of transition shape data. + Or (None, None) if there was an error in the process. + """ + + # TODO: get rid of reliance on profiles + def get_profile(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + material = ifcopenshell.util.element.get_material(element, should_skip_usage=True) + if material and material.is_a("IfcMaterialProfileSet") and len(material.MaterialProfiles) == 1: + return material.MaterialProfiles[0].Profile + + def get_circle_points(radius: float, segments: int = 16) -> np.ndarray: + """starting from (R,0), going counter-clockwise""" + angles = np.linspace(0, 2 * np.pi, segments, endpoint=False) + verts = np.column_stack((np.cos(angles), np.sin(angles), np.zeros(segments))) * radius + return verts + + def get_rectangle_points(dim: np.ndarray) -> np.ndarray: + """Starting from (+X/2, +Y/2) going counter-clockwise""" + dim = dim / 2 + offsets = np.array([[1, 1, 0], [-1, 1, 0], [-1, -1, 0], [1, -1, 0]]) + return dim * offsets + + # TODO: support more profiles + def get_dim(profile: ifcopenshell.entity_instance, depth: float) -> Union[np.ndarray, None]: + if profile.is_a("IfcRectangleProfileDef"): + return np.array([profile.XDim / 2, profile.YDim / 2, depth]) + elif profile.is_a("IfcCircleProfileDef"): + return np.array([profile.Radius, profile.Radius, depth]) + return None + + start_profile = get_profile(start_segment) + end_profile = get_profile(end_segment) + if start_profile is None or end_profile is None: + return None, None + + start_half_dim = get_dim(start_profile, start_length) + end_half_dim = get_dim(end_profile, end_length) + + # if profile types are not supported + if start_half_dim is None or end_half_dim is None: + return None, None + + transition_items = [] + start_offset = np.array([0, 0, start_length]) + end_extrusion_offset = start_offset.copy() + + transition_length = self.mep_transition_length(start_half_dim, end_half_dim, angle, profile_offset) + if transition_length is None: + return None, None + + faces: list[Sequence[int]] = [] + end_extrusion_offset[2] += transition_length + end_extrusion_offset[:2] += profile_offset + + if start_profile.is_a("IfcRectangleProfileDef") and end_profile.is_a("IfcRectangleProfileDef"): + # no transitions for exactly the same profiles + if transition_length == 0: + return None, None + + faces += [(3, 4, 7, 0), (11, 8, 15, 12), (3, 11, 12, 4), (7, 15, 8, 0)] + + # NOTE: clockwise order for correct face orientation + faces += [ + # start extrusion + (0, 1, 2, 3), + (8, 11, 10, 9), + (0, 8, 9, 1), + (1, 9, 10, 2), + (2, 10, 11, 3), + # end extrusion + (4, 5, 6, 7), + (12, 15, 14, 13), + (4, 12, 13, 5), + (5, 13, 14, 6), + (6, 14, 15, 7), + ] + points = [ + start_half_dim * (-1, -1, 1), + start_half_dim * (-1, -1, 0), + start_half_dim * (1, -1, 0), + start_half_dim * (1, -1, 1), + end_half_dim * (1, -1, 0) + end_extrusion_offset, + end_half_dim * (1, -1, 1) + end_extrusion_offset, + end_half_dim * (-1, -1, 1) + end_extrusion_offset, + end_half_dim * (-1, -1, 0) + end_extrusion_offset, + start_half_dim * (-1, 1, 1), + start_half_dim * (-1, 1, 0), + start_half_dim * (1, 1, 0), + start_half_dim * (1, 1, 1), + end_half_dim * (1, 1, 0) + end_extrusion_offset, + end_half_dim * (1, 1, 1) + end_extrusion_offset, + end_half_dim * (-1, 1, 1) + end_extrusion_offset, + end_half_dim * (-1, 1, 0) + end_extrusion_offset, + ] + elif start_profile.is_a("IfcCircleProfileDef") and end_profile.is_a("IfcCircleProfileDef"): + # no transitions for exactly the same profiles + if transition_length == 0: + return None, None + + n_segments = 16 + first_profile_points = get_circle_points(start_profile.Radius, n_segments) + second_profile_points = get_circle_points(end_profile.Radius, n_segments) + + faces = [] + for i in range(n_segments): + # For wrapping around the circle + next_i = (i + 1) % n_segments + face = [i, next_i, next_i + n_segments, i + n_segments] + faces.append(face) + + transition_items.append(self.extrude_face_set(first_profile_points, start_length, end_cap=False)) + transition_items.append( + self.extrude_face_set(second_profile_points, end_length, offset=end_extrusion_offset, start_cap=False) + ) + + first_profile_points += start_offset + second_profile_points += end_extrusion_offset + points = np.vstack((first_profile_points, second_profile_points)) + + else: # one is circular, another one is rectangular + # support transition from rectangle to circle of the same dimensions + if transition_length == 0: + transition_length = (start_length + end_length) / 2 + end_extrusion_offset[2] += transition_length + + starting_with_circle = start_profile.is_a("IfcCircleProfileDef") + if starting_with_circle: + circle_profile, rect_profile = start_profile, end_profile + else: + circle_profile, rect_profile = end_profile, start_profile + + circle_points = get_circle_points(circle_profile.Radius) + rect_points = get_rectangle_points(np.array([rect_profile.XDim, rect_profile.YDim, 0])) + + if starting_with_circle: + start_points, end_points = circle_points, rect_points + else: + start_points, end_points = rect_points, circle_points + + transition_items.append(self.extrude_face_set(start_points, start_length, end_cap=False)) + transition_items.append( + self.extrude_face_set(end_points, end_length, offset=end_extrusion_offset, start_cap=False) + ) + + # offset verts + if starting_with_circle: + circle_points += start_offset + rect_points += end_extrusion_offset + else: + rect_points += start_offset + circle_points += end_extrusion_offset + + # circle verts are 0-15, rect verts are 16-19 + points = np.concatenate((circle_points, rect_points)) + transition_faces = [ + (0, 19, 16), # base + (0, 16, 1), + (1, 16, 2), + (2, 16, 3), + (3, 16, 4), + (4, 16, 17), # base + (4, 17, 5), + (5, 17, 6), + (6, 17, 7), + (7, 17, 8), + (8, 17, 18), # base + (8, 18, 9), + (9, 18, 10), + (10, 18, 11), + (11, 18, 12), + (12, 18, 19), # base + (12, 19, 13), + (13, 19, 14), + (14, 19, 15), + (15, 19, 0), + ] + # revert them in case it's starting with circle profile to keep the face orientation + if starting_with_circle: + transition_faces = [f[::-1] for f in transition_faces] + faces += transition_faces + + face_set = self.polygonal_face_set(points, faces) + transition_items.append(face_set) + + body = ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW") + assert body + representation = self.get_representation(body, transition_items, "Tesselation") + + transition_data = { + "start_length": start_length, + "end_length": end_length, + "angle": angle, + "profile_offset": profile_offset, + "transition_length": transition_length, + "full_transition_length": start_length + transition_length + end_length, + } + + return representation, transition_data + + # TODO: move to separate shape_builder method + # so we could check transition length without creating representation + def mep_transition_length( + self, + start_half_dim: np.ndarray, + end_half_dim: np.ndarray, + angle: float, + profile_offset: VectorType = (0.0, 0.0), + verbose: bool = True, + ): + """get the final transition length for two profiles dimensions, angle and XY offset between them, + + the difference from `calculate_transition` - `get_transition_length` is making sure + that length will fit both sides of the transition + """ + print = lambda *args, **kwargs: __builtins__["print"](*args, **kwargs) if verbose else None + np_X, np_Y = 0, 1 + np_XY = slice(2) + + # vectors tend to have bunch of float point garbage + # that can result in errors when we're calculating value for square root below + offset = np_round_to_precision(np.array(profile_offset), 1) + diff = start_half_dim[np_XY] - end_half_dim[np_XY] + diff = np.abs(diff) + + print(f"offset = {profile_offset} / {offset}") + print(f"diff = {diff}") + + calculation_arguments = { + "start_half_dim": start_half_dim, + "end_half_dim": end_half_dim, + "diff": diff, + "offset": offset, + "verbose": verbose, + } + + def check_transition(end_profile: bool = False) -> Union[float, None]: + length = self.mep_transition_calculate(**calculation_arguments, angle=angle, end_profile=end_profile) + if length is None: + return + + other_side_angle = self.mep_transition_calculate( + **calculation_arguments, length=length, end_profile=not end_profile + ) + if other_side_angle is None: + return None + + # NOTE: for now we just hardcode the good value for that case + same_dimension = is_x(diff[np_Y] if not end_profile else diff[np_X], 0) + if same_dimension and is_x(offset[np_Y] if not end_profile else offset[np_X], 0): + requested_angle = 90.0 + else: + requested_angle = angle + + print(f"other_side_angle = {other_side_angle}, requested_angle = {requested_angle}") + # need to make sure that the worst angle (maximum angle) + # for this transition angle is `requested_angle` + if other_side_angle < requested_angle or is_x(other_side_angle, requested_angle): + print(f"final length = {length}, angle = {requested_angle}, other side angle = {other_side_angle}") + return length + + return check_transition() or check_transition(True) + + def mep_transition_calculate( + self, + start_half_dim: np.ndarray, + end_half_dim: np.ndarray, + offset: np.ndarray, + diff: Optional[np.ndarray] = None, + end_profile: bool = False, + length: Optional[float] = None, + angle: Optional[float] = None, + verbose: bool = True, + ) -> Union[float, None]: + """will return transition length based on the profile dimension differences and offset. + + If `length` is provided will return transition angle""" + + print = lambda *args, **kwargs: __builtins__["print"](*args, **kwargs) if verbose else None + + if diff is None: + diff = start_half_dim[:2] - end_half_dim[:2] + diff = np.abs(diff) + + np_X, np_Y = 0, 1 + np_YX = [1, 0] + + if end_profile: + diff, offset = diff[np_YX], offset[np_YX] + + same_dimension = is_x(diff[0], 0) + a = diff[np_X] + offset[np_X] + b = diff[np_X] - offset[np_X] + if length is None: + if not same_dimension: + assert angle is not None + t = tan(radians(angle)) + h0 = a**2 + 4 * a * b * t**2 + 2 * a * b + b**2 + # TODO: we might need to specify the exact failing cases in the future + if h0 < 0: + print( + f"B. Coulndn't calculate transition length for angle = {angle}, offset = {offset}, diff = {diff}" + ) + return None + + h = (a + b + sqrt(h0)) / (2 * t) + length_squared = h**2 - offset[np_Y] ** 2 + if length_squared <= 0: + print(f"B. angle = {angle} requires h = {h} which is not possible with y offset = {offset[np_Y]}") + return None + length = sqrt(length_squared) + + if verbose: + A = (end_half_dim if end_profile else start_half_dim) * (1, 0, 0) + end_profile_offset = np_to_3d(offset, length) + D = (start_half_dim if end_profile else end_half_dim) * (1, 0, 0) + B, C = -A, -D + C += end_profile_offset + D += end_profile_offset + tested_angle = degrees(np_angle(A - D, B - C)) + print(f"A. length = {length}, requested angle = {angle}, tested angle = {tested_angle}") + else: + if is_x(offset[np_X], 0): + angle = 90 # NOTE: for now we just hardcode the good value for that case + h = start_half_dim[np_X] / tan(radians(angle / 2)) + length_squared = h**2 - offset[np_Y] ** 2 + if length_squared <= 0: + print( + f"B. angle = {angle} requires h = {h} which is not possible with y offset = {offset[np_Y]}" + ) + return None + length = sqrt(length_squared) + + if verbose: + O = np.zeros(3) + A = (-start_half_dim[np_X], 0, length) + np_to_3d(offset) + B = A * (-1, 1, 1) + tested_angle = degrees(np_angle(A - O, B - O)) + print(f"B. length = {length}, requested angle = {angle}, tested angle = {tested_angle}") + else: + assert angle is not None + h = offset[np_X] / tan(radians(angle)) + length_squared = h**2 - offset[np_Y] ** 2 + if length_squared <= 0: + print( + f"C. angle = {angle} requires h = {h} which is not possible with y offset = {offset[np_Y]}" + ) + return None + length = sqrt(length_squared) + + if verbose: + A = np.array((-start_half_dim[np_X], 0, 0)) + H = A + (0, 0, length) + H[np_Y] += offset[np_Y] + D = H.copy() + D[np_X] += offset[np_X] + tested_angle = degrees(np_angle(H - A, D - A)) + print(f"C. length = {length}, requested angle = {angle}, tested angle = {tested_angle}") + + return length + + elif angle is None: + if not same_dimension: + if length == 0: + return 0 + + h = sqrt(length**2 + offset[np_Y] ** 2) + t = -h * (a + b) / (a * b - h**2) + angle = degrees(atan(t)) + + else: + h = sqrt(length**2 + offset[np_Y] ** 2) + if is_x(offset[np_X], 0): + angle = degrees(2 * atan(start_half_dim[np_X] / h)) + else: + angle = degrees(atan(offset[np_X] / h)) + return angle + + def mep_bend_shape( + self, + segment: ifcopenshell.entity_instance, + start_length: float, + end_length: float, + angle: float, + radius: float, + bend_vector: VectorType, + flip_z_axis: bool, + ) -> tuple[ifcopenshell.entity_instance, dict[str, Any]]: + """ + Generate a MEP bend shape for the provided segments. + + :param segment: IfcFlowSegment for a bend. + Note that for a bend start and end segments types should match. + :param angle: bend angle, in radians + :param radius: bend radius + :param bend_vector: offset between start and end segments in local space of start segment + used mainly to determine the second bend axis and it's direction (positive or negative), + the actual magnitude of the vector is not important (though near zero values will be ignored). + :param flip_z_axis: since we cannot determine z axis direction from the profile offset, + there is an option to flip it if bend is going by start segment Z- axis. + :return: tuple of Model/Body/MODEL_VIEW IfcRepresentation and dictionary of transition shape data + """ + + def get_profile(element: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + material = ifcopenshell.util.element.get_material(element, should_skip_usage=True) + if material and material.is_a("IfcMaterialProfileSet") and len(material.MaterialProfiles) == 1: + return material.MaterialProfiles[0].Profile + + def get_dim(profile: ifcopenshell.entity_instance, depth: float) -> Union[np.ndarray, None]: + if profile.is_a("IfcRectangleProfileDef"): + return np.array([profile.XDim / 2, profile.YDim / 2, depth]) + elif profile.is_a("IfcCircleProfileDef"): + return np.array([profile.Radius, profile.Radius, depth]) + return None + + np_Z = 2 + + si_conversion = ifcopenshell.util.unit.calculate_unit_scale(self.file) + profile = get_profile(segment) + assert profile + is_circular_profile = profile.is_a("IfcCircleProfileDef") + profile_dim = get_dim(profile, start_length) + assert profile_dim is not None + + rounded_bend_vector = np_round_to_precision(bend_vector, si_conversion) + lateral_axis = next(i for i in range(2) if not is_x(rounded_bend_vector[i], 0)) + non_lateral_axis = 1 if lateral_axis == 0 else 0 + lateral_sign = np.sign(bend_vector[lateral_axis]) + z_sign = -1 if flip_z_axis else 1 + + rep_items: list[ifcopenshell.entity_instance] = [] + + # bend circle center + O = np.zeros(3) + O[lateral_axis] = (radius + profile_dim[lateral_axis]) * lateral_sign + theta = angle + + def get_circle_points(angles: np.ndarray, radius: float) -> np.ndarray: + """ + :param angles: Angles, in radians. + """ + angles = angles - pi / 2 + points = np.zeros((len(angles), 3)) + # fmt: off + points[:, np_Z] = z_sign * np.cos(angles) * radius + points[:, lateral_axis] = lateral_sign * np.sin(angles) * radius + # fmt: on + return points + + def get_circle_tangent(angle: float) -> np.ndarray: + """ + :param angle: Angle, in radians. + :return: Tangent vector. + """ + tangent = np.zeros(3) + tangent[np_Z] = cos(angle) * z_sign + tangent[lateral_axis] = sin(angle) * lateral_sign + return tangent + + def get_bend_representation_item() -> ifcopenshell.entity_instance: + r = radius + theta_segments = np.array([0.0, theta / 2, theta]) + points: np.ndarray + if is_circular_profile: + r += profile_dim[lateral_axis] + points = get_circle_points(theta_segments, r) + arc_points = (1,) + else: + outer_r = r + 2 * profile_dim[lateral_axis] + outer_points = get_circle_points(theta_segments[::-1], outer_r) + if is_x(r, 0): + points = get_circle_points(np.full(1, theta), r) + points = np.vstack((points, outer_points)) + arc_points = (2,) + else: + inner_points = get_circle_points(theta_segments, r) + points = np.vstack((inner_points, outer_points)) + arc_points = (1, 4) + + points += O + offset = np.zeros(3) + offset[np_Z] = z_sign * start_length + + if is_circular_profile: + bend_path = self.polyline(points, closed=False, arc_points=arc_points, position_offset=offset) + bend = self.create_swept_disk_solid(bend_path, profile_dim[lateral_axis]) + else: + offset[non_lateral_axis] = -profile_dim[non_lateral_axis] + extrusion_kwargs = self.extrude_kwargs("XY"[non_lateral_axis]) + polyline_points = points[:, [lateral_axis, np_Z]] + profile_curve = self.polyline(polyline_points, arc_points=arc_points, closed=True) + bend = self.extrude( + self.profile(profile_curve), profile_dim[non_lateral_axis] * 2, position=offset, **extrusion_kwargs + ) + return bend + + rep_items.append(get_bend_representation_item()) + if start_length: + rep_items.append(self.extrude(profile, start_length, extrusion_vector=(0, 0, z_sign))) + if end_length: + end_position = O + get_circle_points(np.full(1, theta), radius + profile_dim[lateral_axis])[0] + end_position[np_Z] += start_length * z_sign + + # define extrusion space for the segment after the bend + z_axis = get_circle_tangent(theta) + extrude_kwargs = { + "position_z_axis": z_axis, + "extrusion_vector": (0, 0, 1), + } + # since we are sure that tangent involves only two axis + # it's safe to assume that non lateral axis is untouched + if lateral_axis == 0: + x_axis = np.cross(z_axis, (0, 1, 0)) + else: + x_axis = (1, 0, 0) + extrude_kwargs["position_x_axis"] = x_axis + + rep_items.append(self.extrude(profile, end_length, end_position, **extrude_kwargs)) + + body = ifcopenshell.util.representation.get_context(self.file, "Model", "Body", "MODEL_VIEW") + assert body + rep = self.get_representation(body, rep_items) + + bend_data = { + "start_length": start_length, + "end_length": end_length, + "radius": radius, + "angle": degrees(theta), + "lateral_axis": lateral_axis, + "lateral_sign": lateral_sign, + "z_axis_sign": -1 if flip_z_axis else 1, + "main_profile_dimension": profile_dim[lateral_axis], + } + return rep, bend_data diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/system.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/system.py new file mode 100644 index 0000000000000000000000000000000000000000..832daefc0d6dba8ed8e4b6a0bd527cf8a43b67fb --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/system.py @@ -0,0 +1,154 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2022 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + + +import ifcopenshell.util.system +from typing import Optional, Union, Literal + +group_types: dict[str, tuple[str, ...]] = { + "IfcZone": ("IfcZone", "IfcSpace", "IfcSpatialZone"), + "IfcBuiltSystem": ( + "IfcBuiltElement", + "IfcFurnishingElement", + "IfcElementAssembly", + "IfcTransportElement", + ), + "IfcBuildingSystem": ( + "IfcBuildingElement", + "IfcFurnishingElement", + "IfcElementAssembly", + "IfcTransportElement", + ), + "IfcDistributionSystem": ("IfcDistributionElement",), + "IfcStructuralAnalysisModel": ("IfcStructuralMember", "IfcStructuralConnection"), + "IfcSystem": ("IfcProduct",), + "IfcGroup": ("IfcObjectDefinition",), +} +# Subclasses. +group_types["IfcDistributionCircuit"] = group_types["IfcDistributionSystem"] +# Replaced by IfcDistributionCircuit in IFC4, though it wasn't limited to IfcDistributionElements: +# "Usage of IfcElectricalCircuit is as for the supertype IfcSystem". +group_types["IfcElectricalCircuit"] = group_types["IfcSystem"] + + +FLOW_DIRECTION = Literal["SINK", "SOURCE", "SOURCEANDSINK", "NOTEDEFINED"] + + +def is_assignable(product: ifcopenshell.entity_instance, system: ifcopenshell.entity_instance) -> bool: + for assignable in group_types.get(system.is_a(), ()): + if product.is_a(assignable): + return True + return False + + +def get_system_elements(system: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + results = [] + for rel in system.IsGroupedBy: + results.extend(rel.RelatedObjects) + return results + + +def get_element_systems(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + results = [] + for rel in element.HasAssignments: + if not rel.is_a("IfcRelAssignsToGroup"): + continue + group = rel.RelatingGroup + if not group.is_a("IfcSystem") or group.is_a() in ("IfcStructuralAnalysisModel", "IfcZone"): + continue + results.append(group) + return results + + +def get_element_zones(element: ifcopenshell.entity_instance) -> list[ifcopenshell.entity_instance]: + results = [] + for rel in element.HasAssignments: + if not rel.is_a("IfcRelAssignsToGroup"): + continue + group = rel.RelatingGroup + if not group.is_a("IfcZone"): + continue + results.append(group) + return results + + +def get_ports( + element: ifcopenshell.entity_instance, flow_direction: Optional[FLOW_DIRECTION] = None +) -> list[ifcopenshell.entity_instance]: + results = [] + for rel in getattr(element, "IsNestedBy", []) or []: + for port in rel.RelatedObjects: + if not port.is_a("IfcDistributionPort"): + continue + if flow_direction and port.FlowDirection != flow_direction: + continue + results.append(port) + # IFC2X3 only, deprecated in IFC4 + for rel in getattr(element, "HasPorts", []) or []: + port = rel.RelatingPort + if flow_direction and port.FlowDirection != flow_direction: + continue + results.append(port) + return results + + +def get_connected_port(port: ifcopenshell.entity_instance) -> Union[ifcopenshell.entity_instance, None]: + for rel in port.ConnectedTo: + return rel.RelatedPort + for rel in port.ConnectedFrom: + return rel.RelatingPort + + +def get_port_element(port: ifcopenshell.entity_instance) -> ifcopenshell.entity_instance: + if hasattr(port, "Nests"): + for rel in port.Nests: + return rel.RelatingObject + # IFC2X3 only, deprecated in IFC4 + elif hasattr(port, "ContainedIn"): + for rel in port.ContainedIn: + return rel.RelatedElement + + +def get_connected_to( + element: ifcopenshell.entity_instance, flow_direction: Optional[FLOW_DIRECTION] = None +) -> list[ifcopenshell.entity_instance]: + results = [] + for port in ifcopenshell.util.system.get_ports(element, flow_direction=flow_direction): + for rel in port.ConnectedTo: + for other_port in [rel.RelatedPort, rel.RelatingPort]: + if other_port == port: + continue + other_element = get_port_element(other_port) + if other_element: + results.append(other_element) + return results + + +def get_connected_from( + element: ifcopenshell.entity_instance, flow_direction: Optional[FLOW_DIRECTION] = None +) -> list[ifcopenshell.entity_instance]: + results = [] + for port in ifcopenshell.util.system.get_ports(element, flow_direction=flow_direction): + for rel in port.ConnectedFrom: + for other_port in [rel.RelatedPort, rel.RelatingPort]: + if other_port == port: + continue + other_element = get_port_element(other_port) + if other_element: + results.append(other_element) + return results diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/type.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/type.py new file mode 100644 index 0000000000000000000000000000000000000000..ab588142671bd13905697a319eca5993ba078ea7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/type.py @@ -0,0 +1,80 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021, 2023 Dion Moult , @Andrej730 +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +import os +import json +import ifcopenshell.util.schema + +cwd = os.path.dirname(os.path.realpath(__file__)) + +entity_to_type_map: dict[ifcopenshell.util.schema.IFC_SCHEMA, dict[str, list[str]]] = {} +type_to_entity_map: dict[ifcopenshell.util.schema.IFC_SCHEMA, dict[str, list[str]]] = {} + +mapped_schemas = { + "IFC2X3": "entity_to_type_map_2x3.json", + "IFC4": "entity_to_type_map_4.json", + "IFC4X3": "entity_to_type_map_4x3.json", +} +for schema in mapped_schemas: + # load entity maps from json + schema_path = os.path.join(cwd, mapped_schemas[schema]) + with open(schema_path) as f: + entity_to_type_map[schema] = json.load(f) + + # create type_to_entity map + type_to_entity_map[schema] = {} + for element, element_types in entity_to_type_map[schema].items(): + for element_type in element_types: + type_to_entity_map[schema].setdefault(element_type, []).append(element) + + if schema == "IFC2X3": + # Prioritize IfcBuildingElementProxyType if it's available as it seems to be the most generic type. + # Otherwise classes that don't have a special type in IFC2X3 (e.g. IfcBuildingElementPart, IfcRoof) + # have IfcBeamType as their first matching type, which can be confusing. + for occurrence_type, element_types in entity_to_type_map[schema].items(): + if "IfcBuildingElementProxyType" in element_types: + element_types.sort(key=lambda x: x == "IfcBuildingElementProxyType", reverse=True) + + # There is no official mapping for IFC2X3 but this method gets us something that looks correct + # + # NOTE: currently `type_to_entity_map` in IFC2X3 doesn't completely match `entity_to_type_map`, + # e.g. `get_applicabl_types(IfcRoof)` returns `[IfcBuildingElementProxyType, IfcBeamType, ...]` + # but `get_applicable_entities(IfcBuildingElementProxyType)` returns `[IfcBuildingElementProxy`]. + for element_type, elements in type_to_entity_map[schema].items(): + # need to take both Type (4 symbols) and Style (5 symbols) into account + guessed_element = element_type[:-5] if element_type.endswith("Style") else element_type[:-4] + if guessed_element in elements: + type_to_entity_map[schema][element_type] = [e for e in elements if guessed_element in e] + + +def get_applicable_types(ifc_class: str, schema: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4") -> list[str]: + """Get applicable types IFC classes for the occurrence IFC class. + + E.g. "IfcWindow" -> ["IfcWindowType"]. + """ + schema = ifcopenshell.util.schema.get_fallback_schema(schema.upper()) + return entity_to_type_map[schema].get(ifc_class, []) + + +def get_applicable_entities(ifc_type_class: str, schema: ifcopenshell.util.schema.IFC_SCHEMA = "IFC4") -> list[str]: + """Get applicable occurrence IFC classes for the type IFC class. + + E.g. "IfcWindowType" -> ["IfcWindow"]. + """ + schema = ifcopenshell.util.schema.get_fallback_schema(schema.upper()) + return type_to_entity_map[schema].get(ifc_type_class, []) diff --git a/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/unit.py b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/unit.py new file mode 100644 index 0000000000000000000000000000000000000000..a364ed2467749f0ecef01e514ba3c4105154bd6e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/ifcopenshell/util/unit.py @@ -0,0 +1,932 @@ +# IfcOpenShell - IFC toolkit and geometry engine +# Copyright (C) 2021 Dion Moult +# +# This file is part of IfcOpenShell. +# +# IfcOpenShell 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. +# +# IfcOpenShell 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 IfcOpenShell. If not, see . + +from fractions import Fraction +from math import pi +from typing import Literal, Optional, Union +from collections.abc import Generator + +import ifcopenshell +import ifcopenshell.ifcopenshell_wrapper as ifcopenshell_wrapper +import ifcopenshell.api.unit + +prefixes = { + "EXA": 1e18, + "PETA": 1e15, + "TERA": 1e12, + "GIGA": 1e9, + "MEGA": 1e6, + "KILO": 1e3, + "HECTO": 1e2, + "DECA": 1e1, + "DECI": 1e-1, + "CENTI": 1e-2, + "MILLI": 1e-3, + "MICRO": 1e-6, + "NANO": 1e-9, + "PICO": 1e-12, + "FEMTO": 1e-15, + "ATTO": 1e-18, +} + +unit_names = [ + "AMPERE", + "BECQUEREL", + "CANDELA", + "COULOMB", + "CUBIC_METRE", + "DEGREE_CELSIUS", + "FARAD", + "GRAM", + "GRAY", + "HENRY", + "HERTZ", + "JOULE", + "KELVIN", + "LUMEN", + "LUX", + "MOLE", + "NEWTON", + "OHM", + "PASCAL", + "RADIAN", + "SECOND", + "SIEMENS", + "SIEVERT", + "SQUARE_METRE", + "METRE", + "STERADIAN", + "TESLA", + "VOLT", + "WATT", + "WEBER", +] + +si_dimensions = { + "METRE": (1, 0, 0, 0, 0, 0, 0), + "SQUARE_METRE": (2, 0, 0, 0, 0, 0, 0), + "CUBIC_METRE": (3, 0, 0, 0, 0, 0, 0), + "GRAM": (0, 1, 0, 0, 0, 0, 0), + "SECOND": (0, 0, 1, 0, 0, 0, 0), + "AMPERE": (0, 0, 0, 1, 0, 0, 0), + "KELVIN": (0, 0, 0, 0, 1, 0, 0), + "MOLE": (0, 0, 0, 0, 0, 1, 0), + "CANDELA": (0, 0, 0, 0, 0, 0, 1), + "RADIAN": (0, 0, 0, 0, 0, 0, 0), + "STERADIAN": (0, 0, 0, 0, 0, 0, 0), + "HERTZ": (0, 0, -1, 0, 0, 0, 0), + "NEWTON": (1, 1, -2, 0, 0, 0, 0), + "PASCAL": (-1, 1, -2, 0, 0, 0, 0), + "JOULE": (2, 1, -2, 0, 0, 0, 0), + "WATT": (2, 1, -3, 0, 0, 0, 0), + "COULOMB": (0, 0, 1, 1, 0, 0, 0), + "VOLT": (2, 1, -3, -1, 0, 0, 0), + "FARAD": (-2, -1, 4, 2, 0, 0, 0), + "OHM": (2, 1, -3, -2, 0, 0, 0), + "SIEMENS": (-2, -1, 3, 2, 0, 0, 0), + "WEBER": (2, 1, -2, -1, 0, 0, 0), + "TESLA": (0, 1, -2, -1, 0, 0, 0), + "HENRY": (2, 1, -2, -2, 0, 0, 0), + "DEGREE_CELSIUS": (0, 0, 0, 0, 1, 0, 0), + "LUMEN": (0, 0, 0, 0, 0, 0, 1), + "LUX": (-2, 0, 0, 0, 0, 0, 1), + "BECQUEREL": (0, 0, -1, 0, 0, 0, 0), + "GRAY": (2, 0, -2, 0, 0, 0, 0), + "SIEVERT": (2, 0, -2, 0, 0, 0, 0), + "OTHERWISE": (0, 0, 0, 0, 0, 0, 0), +} + +# See https://github.com/buildingSMART/IFC4.3.x-development/issues/72 +si_type_names = { + "ABSORBEDDOSEUNIT": "GRAY", + "AMOUNTOFSUBSTANCEUNIT": "MOLE", + "AREAUNIT": "SQUARE_METRE", + "DOSEEQUIVALENTUNIT": "SIEVERT", + "ELECTRICCAPACITANCEUNIT": "FARAD", + "ELECTRICCHARGEUNIT": "COULOMB", + "ELECTRICCONDUCTANCEUNIT": "SIEMENS", + "ELECTRICCURRENTUNIT": "AMPERE", + "ELECTRICRESISTANCEUNIT": "OHM", + "ELECTRICVOLTAGEUNIT": "VOLT", + "ENERGYUNIT": "JOULE", + "FORCEUNIT": "NEWTON", + "FREQUENCYUNIT": "HERTZ", + "ILLUMINANCEUNIT": "LUX", + "INDUCTANCEUNIT": "HENRY", + "LENGTHUNIT": "METRE", + "LUMINOUSFLUXUNIT": "LUMEN", + "LUMINOUSINTENSITYUNIT": "CANDELA", + "MAGNETICFLUXDENSITYUNIT": "TESLA", + "MAGNETICFLUXUNIT": "WEBER", + "MASSUNIT": "GRAM", + "PLANEANGLEUNIT": "RADIAN", + "POWERUNIT": "WATT", + "PRESSUREUNIT": "PASCAL", + "RADIOACTIVITYUNIT": "BECQUEREL", + "SOLIDANGLEUNIT": "STERADIAN", + "THERMODYNAMICTEMPERATUREUNIT": "KELVIN", # Or, DEGREE_CELSIUS, but this is a quirk of IFC + "TIMEUNIT": "SECOND", + "VOLUMEUNIT": "CUBIC_METRE", + "USERDEFINED": "METRE", +} + +# See IfcDimensionalExponents: +# (Length, Mass, Time, ElectricCurrent, ThermodynamicTemperature, AmountOfSubstance, LuminousIntensity) +named_dimensions = { + "ABSORBEDDOSEUNIT": (2, 0, -2, 0, 0, 0, 0), + "AMOUNTOFSUBSTANCEUNIT": (0, 0, 0, 0, 0, 1, 0), + "AREAUNIT": (2, 0, 0, 0, 0, 0, 0), + "DOSEEQUIVALENTUNIT": (2, 0, -2, 0, 0, 0, 0), + "ELECTRICCAPACITANCEUNIT": (-2, -1, 4, 2, 0, 0, 0), + "ELECTRICCHARGEUNIT": (0, 0, 1, 1, 0, 0, 0), + "ELECTRICCONDUCTANCEUNIT": (-2, -1, 3, 2, 0, 0, 0), + "ELECTRICCURRENTUNIT": (0, 0, 0, 1, 0, 0, 0), + "ELECTRICRESISTANCEUNIT": (2, 1, -3, -2, 0, 0, 0), + "ELECTRICVOLTAGEUNIT": (2, 1, -3, -1, 0, 0, 0), + "ENERGYUNIT": (2, 1, -2, 0, 0, 0, 0), + "FORCEUNIT": (1, 1, -2, 0, 0, 0, 0), + "FREQUENCYUNIT": (0, 0, -1, 0, 0, 0, 0), + "ILLUMINANCEUNIT": (-2, 0, 0, 0, 0, 1, 1), + "INDUCTANCEUNIT": (2, 1, -2, -2, 0, 0, 0), + "LENGTHUNIT": (1, 0, 0, 0, 0, 0, 0), + "LUMINOUSFLUXUNIT": (0, 0, 0, 0, 0, 1, 1), + "LUMINOUSINTENSITYUNIT": (0, 0, 0, 0, 0, 0, 1), + "MAGNETICFLUXDENSITYUNIT": (0, 1, -2, -1, 0, 0, 0), + "MAGNETICFLUXUNIT": (2, 1, -2, -1, 0, 0, 0), + "MASSUNIT": (0, 1, 0, 0, 0, 0, 0), + "PLANEANGLEUNIT": (0, 0, 0, 0, 0, 0, 0), + "POWERUNIT": (2, 1, -3, 0, 0, 0, 0), + "PRESSUREUNIT": (-1, 1, -2, 0, 0, 0, 0), + "RADIOACTIVITYUNIT": (0, 0, -1, 0, 0, 0, 0), + "SOLIDANGLEUNIT": (0, 0, 0, 0, 0, 0, 0), + "THERMODYNAMICTEMPERATUREUNIT": (0, 0, 0, 0, 1, 0, 0), + "TIMEUNIT": (0, 0, 1, 0, 0, 0, 0), + "VOLUMEUNIT": (3, 0, 0, 0, 0, 0, 0), + "USERDEFINED": (0, 0, 0, 0, 0, 0, 0), +} + +si_conversions = { + "thou": 0.0000254, + "inch": 0.0254, + "foot": 0.3048, + "yard": 0.914, + "mile": 1609, + "square thou": 6.4516e-10, + "square inch": 0.0006452, + "square foot": 0.09290304, + "square yard": 0.83612736, + "acre": 4046.86, + "square mile": 2588881, + "cubic thou": 1.6387064e-14, + "cubic inch": 0.00001639, + "cubic foot": 0.02831684671168849, + "cubic yard": 0.7636, + "cubic mile": 4165509529, + "litre": 0.001, + "fluid ounce UK": 0.0000284130625, + "fluid ounce US": 0.00002957353, + "pint UK": 0.000568, + "pint US": 0.000473, + "gallon UK": 0.004546, + "gallon US": 0.003785, + "degree": pi / 180, + "ounce": 0.02835, + "pound": 0.454, + "ton UK": 1016.0469088, + "ton US": 907.18474, + "lbf": 4.4482216153, + "kip": 4448.2216153, + "psi": 6894.7572932, + "ksi": 6894757.2932, + "minute": 60, + "hour": 3600, + "day": 86400, + "btu": 1055.056, + "fahrenheit": 1.8, +} + +si_offsets = { + "fahrenheit": -459.67, +} + +imperial_types = { + "thou": "LENGTHUNIT", + "inch": "LENGTHUNIT", + "foot": "LENGTHUNIT", + "yard": "LENGTHUNIT", + "mile": "LENGTHUNIT", + "square thou": "AREAUNIT", + "square inch": "AREAUNIT", + "square foot": "AREAUNIT", + "square yard": "AREAUNIT", + "acre": "AREAUNIT", + "square mile": "AREAUNIT", + "cubic thou": "VOLUMEUNIT", + "cubic inch": "VOLUMEUNIT", + "cubic foot": "VOLUMEUNIT", + "cubic yard": "VOLUMEUNIT", + "cubic mile": "VOLUMEUNIT", + "litre": "VOLUMEUNIT", + "fluid ounce UK": "VOLUMEUNIT", + "fluid ounce US": "VOLUMEUNIT", + "pint UK": "VOLUMEUNIT", + "pint US": "VOLUMEUNIT", + "gallon UK": "VOLUMEUNIT", + "gallon US": "VOLUMEUNIT", + "degree": "PLANEANGLEUNIT", + "ounce": "MASSUNIT", + "pound": "MASSUNIT", + "ton UK": "MASSUNIT", + "ton US": "MASSUNIT", + "lbf": "FORCEUNIT", + "kip": "FORCEUNIT", + "psi": "PRESSUREUNIT", + "ksi": "PRESSUREUNIT", + "minute": "TIMEUNIT", + "hour": "TIMEUNIT", + "day": "TIMEUNIT", + "btu": "ENERGYUNIT", + "fahrenheit": "THERMODYNAMICTEMPERATUREUNIT", +} + +prefix_symbols = { + "EXA": "E", + "PETA": "P", + "TERA": "T", + "GIGA": "G", + "MEGA": "M", + "KILO": "k", + "HECTO": "h", + "DECA": "da", + "DECI": "d", + "CENTI": "c", + "MILLI": "m", + "MICRO": "μ", + "NANO": "n", + "PICO": "p", + "FEMTO": "f", + "ATTO": "a", +} + +unit_symbols = { + # si units + "CUBIC_METRE": "m3", + "GRAM": "g", + "SECOND": "s", + "SQUARE_METRE": "m2", + "METRE": "m", + "NEWTON": "N", + "PASCAL": "Pa", + # conversion based units + "pound-force": "lbf", + "pound-force per square inch": "psi", + "thou": "th", + "inch": "in", + "foot": "ft", + "yard": "yd", + "mile": "mi", + "square thou": "th2", + "square inch": "in2", + "square foot": "ft2", + "square yard": "yd2", + "acre": "ac", + "square mile": "mi2", + "cubic thou": "th3", + "cubic inch": "in3", + "cubic foot": "ft3", + "cubic yard": "yd3", + "cubic mile": "mi3", + "litre": "L", + "fluid ounce UK": "fl oz", + "fluid ounce US": "fl oz", + "pint UK": "pt", + "pint US": "pt", + "gallon UK": "gal", + "gallon US": "gal", + "degree": "°", + "ounce": "oz", + "pound": "lb", + "ton UK": "ton", + "ton US": "ton", + "lbf": "lbf", + "kip": "kip", + "psi": "psi", + "ksi": "ksi", + "minute": "min", + "hour": "hr", + "day": "day", + "btu": "btu", + "fahrenheit": "°F", +} + +QUANTITY_CLASS = Literal[ + "IfcQuantityCount", + "IfcQuantityNumber", + "IfcQuantityLength", + "IfcQuantityArea", + "IfcQuantityVolume", + "IfcQuantityWeight", + "IfcQuantityTime", + "IfcQuantityCount", +] + +MEASURE_CLASS = Literal[ + "IfcNumericMeasure", + "IfcLengthMeasure", + "IfcAreaMeasure", + "IfcVolumeMeasure", + "IfcMassMeasure", +] + + +def get_prefix(text): + if text: + for prefix in prefixes.keys(): + if prefix in text.upper(): + return prefix + + +def get_prefix_multiplier(text): + if not text: + return 1 + prefix = get_prefix(text) + if prefix: + return prefixes[prefix] + return 1 + + +def get_unit_name(text: str) -> Union[str, None]: + """Get unit name from str, if unit is in SI.""" + text = text.upper().replace("METER", "METRE") + for name in unit_names: + if name.replace("_", " ") in text: + return name + + +def get_unit_name_universal(text: str) -> Union[str, None]: + """Get unit name from str, supports both SI and imperial system. + + Can be used to provide units for `convert()`""" + text = text.upper().replace("METER", "METRE") + for name in unit_names: + if name.replace("_", " ") in text: + return name + for name in imperial_types: + if name.upper() in text: + return name + + +def get_full_unit_name(unit: ifcopenshell.entity_instance) -> str: + prefix = getattr(unit, "Prefix", None) or "" + return prefix + unit.Name.upper() + + +def get_si_dimensions(name): + return si_dimensions.get(name, si_dimensions["OTHERWISE"]) + + +def get_named_dimensions(name): + return named_dimensions.get(name, (0, 0, 0, 0, 0, 0, 0)) + + +def get_unit_assignment(ifc_file: ifcopenshell.file) -> Union[ifcopenshell.entity_instance, None]: + return ifc_file.by_type("IfcProject")[0].UnitsInContext + + +def cache_units(ifc_file: ifcopenshell.file) -> None: + """Cache the default units for performance + + Repetitively fetching project units (such as for determining the unit of a + property) can be costly. This enables a cache to make it faster. If the + project units change, you can update the cache by rerunning this function. + + :param ifc_file: The IFC file. + """ + ifc_file.units = {} + if assignment := get_unit_assignment(ifc_file): + ifc_file.units = {u.UnitType: u for u in assignment.Units if getattr(u, "UnitType", None)} + + +def clear_unit_cache(ifc_file: ifcopenshell.file) -> None: + """Clears the unit cache of the project + + :param ifc_file: The IFC file. + """ + ifc_file.units = {} + + +def get_project_unit( + ifc_file: ifcopenshell.file, unit_type: str, use_cache: bool = False +) -> Union[ifcopenshell.entity_instance, None]: + """Get the default project unit of a particular unit type + + :param ifc_file: The IFC file. + :param unit_type: The type of unit, taken from the list of IFC unit types, + such as "LENGTHUNIT". + :return: The IFC unit entity, or nothing if there is no default project + unit defined. + """ + if use_cache and not ifc_file.units: + cache_units(ifc_file) + if units := ifc_file.units: + return units.get(unit_type, None) + if unit_assignment := get_unit_assignment(ifc_file): + for unit in unit_assignment.Units or []: + if getattr(unit, "UnitType", None) == unit_type: + return unit + + +def get_property_unit( + prop: ifcopenshell.entity_instance, ifc_file: Union[ifcopenshell.file, None], use_cache: bool = False +) -> Union[ifcopenshell.entity_instance, None]: + """Gets the unit definition of a property or quantity + + Properties and quantities in psets and qtos can be associated with a unit. + This unit may be defined at the property itself explicitly, or if not + specified, fallback to the project default. + + :param prop: The IfcProperty instance. You can fetch this via the instance + ID if doing :func:`ifcopenshell.util.element.get_psets` with + ``verbose=True``. + :param ifc_file: The IFC file being used. This is necessary to check + default project units. + :return: The IFC unit entity, or nothing if there is no default project + unit defined. + """ + if unit := getattr(prop, "Unit", None): + return unit + + value = None + measure_class = None + + if prop.is_a("IfcPhysicalSimpleQuantity"): + entity = prop.wrapped_data.declaration().as_entity() + measure_class = entity.attribute_by_index(3).type_of_attribute().declared_type().name() + elif prop.is_a("IfcPropertySingleValue"): + measure_class = prop.NominalValue.is_a() + elif prop.is_a("IfcPropertyEnumeratedValue"): + if prop.EnumerationReference: + if unit := prop.EnumerationReference.Unit: + return unit + if value := next(iter(prop.EnumerationReference.EnumerationValues or ()), None): + measure_class = value.is_a() + if value := next(iter(prop.EnumerationValues or ()), None): + measure_class = value.is_a() + elif prop.is_a("IfcPropertyListValue"): + if value := next(iter(prop.ListValues or ()), None): + measure_class = value.is_a() + elif prop.is_a("IfcPropertyBoundedValue"): + if value := (prop.UpperBoundValue or prop.LowerBoundValue or prop.SetPointValue): + measure_class = value.is_a() + + if measure_class and (unit_type := get_measure_unit_type(measure_class)): + if not ifc_file: + ifc_file = prop.file + return get_project_unit(ifc_file, unit_type, use_cache=use_cache) + + +def get_property_table_unit( + prop: ifcopenshell.entity_instance, ifc_file: Union[ifcopenshell.file, None], use_cache: bool = False +) -> dict[str, Union[ifcopenshell.entity_instance, None]]: + """ + Gets the unit definition of a property table + + Properties and quantities in psets and qtos can be associated with a unit. + This unit may be defined at the property itself explicitly, or if not + specified, fallback to the project default. + + :param prop: The property instance. You can fetch this via the instance ID + if doing :func:`ifcopenshell.util.element.get_psets` with + ``verbose=True``. + + :param ifc_file: The IFC file being used. This is necessary to check + default project units. + + :return: A dictionary containing IFC unit entity by keyword. + If a unit-entity is missing, + the value associated to the key is `null`. + """ + if not ifc_file: + ifc_file = prop.file + defining_unit = None + if unit := prop.DefiningUnit: + defining_unit = unit + elif value := next(iter(prop.DefiningValues or ()), None): + if unit_type := get_measure_unit_type(value.is_a()): + defining_unit = get_project_unit(ifc_file, unit_type, use_cache=use_cache) + + defined_unit = None + if unit := prop.DefinedUnit: + defined_unit = unit + elif value := next(iter(prop.DefinedValues or ()), None): + if unit_type := get_measure_unit_type(value.is_a()): + defined_unit = get_project_unit(ifc_file, unit_type, use_cache=use_cache) + + return { + "DefiningUnit": defining_unit, + "DefinedUnit": defined_unit, + } + + +def get_unit_measure_class(unit_type: str) -> MEASURE_CLASS: + """Get the IFC measure class for a unit type. + + IFC has specific classes used to measure different units. An example of an + IFC measure class is ``IfcLengthMeasure``. An example of the correlating + unit type (i.e. the IfcUnitEnum) is ``LENGTHUNIT``. + + The inverse function of this is :func:`get_measure_unit_type` + + :param unit_type: A string chosen from IfcUnitEnum, such as LENGTHUNIT + """ + if unit_type == "USERDEFINED": + # See https://github.com/buildingSMART/IFC4.3.x-development/issues/71 + return "IfcNumericMeasure" + return "Ifc" + unit_type[0:-4].lower().capitalize() + "Measure" + + +def get_measure_unit_type(measure_class: MEASURE_CLASS) -> str: + """Get the unit type of an IFC measure class + + IFC has different unit types which can be associated with units (e.g. SI + units, imperial units, derived units, etc). An example of a unit type (i.e. + an IfcUnitEnum) is ``LENGTHUNIT``. An example of the correlating measure + class used to store length data is ``IfcLengthMeasure``. + + The inverse fucntion of this is :func:`get_unit_measure_class` + + :param measure_class: The measure class, such as ``IfcLengthMeasure``. If + you have an ``IfcPropertySingleValue``, you can get this using + ``prop.NominalValue.is_a()``. + :return: The unit type, as an uppercase value of IfcUnitEnum. + """ + if measure_class == "IfcNumericMeasure": + # See https://github.com/buildingSMART/IFC4.3.x-development/issues/71 + return "USERDEFINED" + for text in ("Ifc", "Measure", "Non", "Positive", "Negative"): + measure_class = measure_class.replace(text, "") + return measure_class.upper() + "UNIT" + + +def get_symbol_measure_class(symbol: Optional[str] = None) -> MEASURE_CLASS: + # Dumb, but everybody gets it, unlike regex golf + if not symbol: + return "IfcNumericMeasure" + symbol = symbol.lower() + if symbol in ["km", "m", "cm", "mm", "ly", "lf", "lin", "yd", "ft", "in"]: + return "IfcLengthMeasure" + elif symbol in ["km2", "m2", "cm2", "mm2", "sqy", "sqft", "sqin"]: + return "IfcAreaMeasure" + elif symbol in ["km3", "m3", "cm3", "mm3", "cy", "cft", "cin"]: + return "IfcVolumeMeasure" + elif symbol in ["kg", "g", "mt", "kt", "t"]: + return "IfcMassMeasure" + elif symbol in ["day", "d", "hour", "hr", "h", "minute", "min", "m", "second", "sec", "s"]: + return "IfcTimeMeasure" + return "IfcNumericMeasure" + + +def get_symbol_quantity_class(symbol: Optional[str] = None) -> QUANTITY_CLASS: + # Dumb, but everybody gets it, unlike regex golf + if not symbol: + return "IfcQuantityCount" + symbol = symbol.lower() + if symbol in ["km", "m", "cm", "mm", "ly", "lf", "lin", "yd", "ft", "in"]: + return "IfcQuantityLength" + elif symbol in ["km2", "m2", "cm2", "mm2", "sqy", "sqft", "sqin"]: + return "IfcQuantityArea" + elif symbol in ["km3", "m3", "cm3", "mm3", "cy", "cft", "cin"]: + return "IfcQuantityVolume" + elif symbol in ["kg", "g", "mt", "kt", "t"]: + return "IfcQuantityWeight" + elif symbol in ["day", "d", "hour", "hr", "h", "minute", "min", "m", "second", "sec", "s"]: + return "IfcQuantityTime" + return "IfcQuantityCount" + + +def get_unit_symbol(unit: ifcopenshell.entity_instance) -> str: + symbol: str = "" + if unit.is_a("IfcSIUnit"): + symbol += prefix_symbols.get(unit.Prefix, "") + symbol += unit_symbols.get(unit.Name.replace("METER", "METRE"), "?") + if unit.is_a("IfcContextDependentUnit") and unit.UnitType == "USERDEFINED": + symbol = unit.Name + return symbol + + +def convert_unit(value: float, from_unit: ifcopenshell.entity_instance, to_unit: ifcopenshell.entity_instance) -> float: + """Convert from one unit to another unit + + :param value: The numeric value you want to convert + :param from_unit: The IfcNamedUnit to confirm from. + :param to_unit: The IfcNamedUnit to confirm from. + :return: The converted value. + """ + return convert( + value, getattr(from_unit, "Prefix", None), from_unit.Name, getattr(to_unit, "Prefix", None), to_unit.Name + ) + + +def convert(value: float, from_prefix: Optional[str], from_unit: str, to_prefix: Optional[str], to_unit: str) -> float: + """Converts between length, area, and volume units + + In this case, you manually specify the names and (optionally) prefixes to + convert to and from. In case you want to automatically convert to units + already available as IFC entities, consider using convert_unit() instead. + + :param value: The numeric value you want to convert + :param from_prefix: A prefix from IfcSIPrefix. Can be None + :param from_unit: IfcSIUnitName or IfcConversionBasedUnit.Name + :param to_prefix: A prefix from IfcSIPrefix. Can be None + :param to_unit: IfcSIUnitName or IfcConversionBasedUnit.Name + :return: The converted value. + """ + if from_unit.lower() in si_conversions: + value *= si_conversions[from_unit.lower()] + elif from_prefix: + value *= get_prefix_multiplier(from_prefix) + if "SQUARE" in from_unit: + value *= get_prefix_multiplier(from_prefix) + elif "CUBIC" in from_unit: + value *= get_prefix_multiplier(from_prefix) + value *= get_prefix_multiplier(from_prefix) + if to_unit.lower() in si_conversions: + return value * (1 / si_conversions[to_unit.lower()]) + elif to_prefix: + value *= 1 / get_prefix_multiplier(to_prefix) + if "SQUARE" in from_unit: + value *= 1 / get_prefix_multiplier(to_prefix) + elif "CUBIC" in from_unit: + value *= 1 / get_prefix_multiplier(to_prefix) + value *= 1 / get_prefix_multiplier(to_prefix) + return value + + +def calculate_unit_scale(ifc_file: ifcopenshell.file, unit_type: str = "LENGTHUNIT") -> float: + """Returns a unit scale factor to convert to and from IFC project units and SI units. + + Example: + + .. code:: python + + ifc_project_length * unit_scale = si_meters + si_meters / unit_scale = ifc_project_length + + :param ifc_file: The IFC file. + :param unit_type: The type of SI unit, defaults to "LENGTHUNIT" + :returns: The scale factor + """ + if ( + type(ifc_file) is ifcopenshell.file + and unit_type + not in ifcopenshell.ifcopenshell_wrapper.schema_by_name(ifc_file.schema_identifier) + .declaration_by_name("IfcUnitEnum") + .enumeration_items() + ): + raise ValueError(f"Unit type {unit_type!r} does not name a valid type") + + # Currently we assume that all ifc projects must have IfcProject. + if not (projects := ifc_file.by_type("IfcProject")) or not (units := projects[0].UnitsInContext): + return 1 + unit_scale = 1 + unit: ifcopenshell.entity_instance + for unit in units.Units: + if getattr(unit, "UnitType", ...) != unit_type: + continue + while unit.is_a("IfcConversionBasedUnit"): + conversion_factor = unit.ConversionFactor + unit_scale *= conversion_factor.ValueComponent.wrappedValue + unit = conversion_factor.UnitComponent + if unit.is_a("IfcSIUnit"): + unit_scale *= get_prefix_multiplier(unit.Prefix) + return unit_scale + + +def format_length( + value: float, + precision: float, + decimal_places: int = 2, + suppress_zero_inches=True, + unit_system: Literal["metric", "imperial"] = "imperial", + input_unit: Literal["foot", "inch"] = "foot", + output_unit: Literal["foot", "inch"] = "foot", +) -> str: + """Formats a length for readability and imperial formatting + + :param value: The value in meters if metric, or either decimal feet or + inches if imperial depending on input_unit. + :param precision: How precise the format should be. I.e. round to nearest. + For imperial, it is 1/Nth. E.g. 12 means to the nearest 1/12th of an + inch. + :param decimal_places: How many decimal places to display. Defaults to 2. + :param suppress_zero_inches: If imperial, whether or not to supress the + inches if the inches is zero. + :param unit_system: Choose whether your value is "metric" or "imperial" + :param input_unit: If imperial, specify whether your value is "foot" or + "inch". + :param output_unit: If imperial, specify whether your value is "foot" to + format as both feet and inches, or "inch" if only inches should be + shown. + :returns: The formatted string, such as 1' - 5 1/2". + """ + if unit_system == "imperial": + if input_unit == "foot": + feet = int(value) + inches = (value - feet) * 12 + elif input_unit == "inch": + inches = value % 12 + feet = int(round((value - inches) / 12)) + + # Round to the nearest 1/N + nearest = round(inches * precision) + + # Create a fraction based on the rounded value and the precision + frac = Fraction(nearest, precision) + + # If fraction is a whole number, format it accordingly + if frac.denominator == 1: + if suppress_zero_inches and frac.numerator == 0: + if output_unit == "foot": + return f"{feet}'" + return f'{feet * 12}"' + if output_unit == "foot": + return f"{feet}' - {frac.numerator}\"" + return f'{(feet * 12) + frac.numerator}"' + if frac.numerator > frac.denominator: + remainder = frac.numerator % frac.denominator + whole = int((frac.numerator - remainder) / frac.denominator) + if output_unit == "foot": + return f"{feet}' - {whole} {remainder}/{frac.denominator}\"" + return f'{(feet * 12) + whole} {remainder}/{frac.denominator}"' + if output_unit == "foot": + return f"{feet}' - {frac.numerator}/{frac.denominator}\"" + return f'{feet * 12} {frac.numerator}/{frac.denominator}"' + elif unit_system == "metric": + rounded_val = round(value / precision) * precision + return f"{rounded_val:.{decimal_places}f}" + + +def is_attr_type( + content_type: ifcopenshell_wrapper.parameter_type, + ifc_unit_type_name: str, + include_select_types: bool = True, +) -> Union[ifcopenshell_wrapper.type_declaration, None]: + cur_decl = content_type + + if hasattr(cur_decl, "name") and cur_decl.name() == ifc_unit_type_name: + return cur_decl + + if include_select_types: + if hasattr(cur_decl, "select_list"): + for select_item in cur_decl.select_list(): + if is_attr_type(select_item, ifc_unit_type_name): + return select_item + + if hasattr(cur_decl, "declared_type"): + return is_attr_type(cur_decl.declared_type(), ifc_unit_type_name, include_select_types) + + if isinstance(cur_decl, ifcopenshell_wrapper.aggregation_type): + # support aggregate of aggregates, as in IfcCartesianPointList3D.CoordList + def get_declared_type_from_aggregate(cur_decl): + cur_decl = cur_decl.type_of_element() + if not isinstance(cur_decl, ifcopenshell_wrapper.aggregation_type): + return cur_decl.declared_type() + return get_declared_type_from_aggregate(cur_decl) + + cur_decl = get_declared_type_from_aggregate(cur_decl) + return is_attr_type(cur_decl, ifc_unit_type_name, include_select_types) + + return None + + +FloatOrSequenceOfFloats = Union[float, tuple["FloatOrSequenceOfFloats", ...]] + + +def iter_element_and_attributes_per_type(ifc_file: ifcopenshell.file, attr_type_name: str) -> Generator[ + tuple[ + ifcopenshell.entity_instance, + ifcopenshell_wrapper.attribute, + Union[FloatOrSequenceOfFloats, ifcopenshell.entity_instance], + ], + None, + None, +]: + schema = ifcopenshell_wrapper.schema_by_name(ifc_file.schema_identifier) + + for element in ifc_file: + entity = schema.declaration_by_name(element.is_a()).as_entity() + assert entity + attrs = entity.all_attributes() + attrs_derived = entity.derived() + for attr, val, is_derived in zip(attrs, list(element), attrs_derived): + if is_derived: + continue + + # Get all methods and attributes of the element + attr_type = attr.type_of_attribute() + base_type = is_attr_type(attr_type, attr_type_name) + if base_type is None: + continue + + if val is None: + continue + + if isinstance(val, ifcopenshell.entity_instance) and not val.is_a(attr_type_name): + continue + elif isinstance(val, tuple): + if not val: + continue + val_ = val[0] + # If it's a tuple of entities, just yield the entities we need to edit. + if isinstance(val_, ifcopenshell.entity_instance): + for val_ in val: + if not val_.is_a(attr_type_name): + continue + yield element, attr, val_ + continue + + yield element, attr, val + + +def convert_file_length_units(ifc_file: ifcopenshell.file, target_units: str = "METER") -> ifcopenshell.file: + """Converts all units in an IFC file to the specified target units. Returns a new file.""" + import ifcopenshell.util.element + import ifcopenshell.util.geolocation + import ifcopenshell.api.georeference + import ifcopenshell.api.unit + + prefix = get_prefix(target_units) + si_unit = get_unit_name(target_units) + + # Copy all elements from the original file to the patched file + file_patched = ifcopenshell.file.from_string(ifc_file.wrapped_data.to_string()) + + old_length = get_project_unit(file_patched, "LENGTHUNIT") + if si_unit: + new_length = ifcopenshell.api.unit.add_si_unit(file_patched, unit_type="LENGTHUNIT", prefix=prefix) + else: + target_units = target_units.lower() + if imperial_types.get(target_units) != "LENGTHUNIT": + raise Exception( + f'Couldn\'t identify target units "{target_units}". ' + 'The method supports singular unit names like "CENTIMETER", "METER", "FOOT", etc.' + ) + new_length = ifcopenshell.api.unit.add_conversion_based_unit(file_patched, name=target_units) + + # support tuple of tuples, as in IfcCartesianPointList3D.CoordList + def convert_value(value: FloatOrSequenceOfFloats) -> FloatOrSequenceOfFloats: + if not isinstance(value, tuple): + return convert_unit(value, old_length, new_length) + return tuple(convert_value(v) for v in value) + + # Traverse all elements and their nested attributes in the file and convert them + for element, attr, val in iter_element_and_attributes_per_type(file_patched, "IfcLengthMeasure"): + # NOTE: There is no risk of editing same entities twice as they're all recreated + # after file is reloaded as `file_patched`. + if isinstance(val, ifcopenshell.entity_instance): + val.wrappedValue = convert_value(val.wrappedValue) + else: + new_value = convert_value(val) + setattr(element, attr.name(), new_value) + + has_map_unit = False + if ( + ifc_file.schema == "IFC2X3" + and (crs := ifcopenshell.util.element.get_pset(ifc_file.by_type("IfcProject")[0], name="ePSet_ProjectedCRS")) + and crs.get("MapUnit") + ) or (ifc_file.schema != "IFC2X3" and (crs := ifc_file.by_type("IfcProjectedCRS")) and crs[0].MapUnit): + has_map_unit = True + + if has_map_unit: + parameters = ifcopenshell.util.geolocation.get_helmert_transformation_parameters(ifc_file) + ifcopenshell.api.georeference.edit_georeferencing( + file_patched, + coordinate_operation={ + "Eastings": parameters.e, + "Northings": parameters.n, + "OrthogonalHeight": parameters.h, + "Scale": parameters.scale / convert_value(1), + }, + ) + + unit_assignment = get_unit_assignment(file_patched) + unit_assignment.Units = [new_length, *(u for u in unit_assignment.Units if u.UnitType != new_length.UnitType)] + if not file_patched.get_total_inverses(old_length): + ifcopenshell.util.element.remove_deep2(file_patched, old_length) + + return file_patched diff --git a/data/miniconda3/lib/python3.13/site-packages/keyring-25.7.0.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/keyring-25.7.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..f60bd572013c6abcb3a82ba9b50d84935de6394f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/keyring-25.7.0.dist-info/licenses/LICENSE @@ -0,0 +1,18 @@ +MIT License + +Copyright (c) 2025 + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and +associated documentation files (the "Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the +following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial +portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT +LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO +EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f530aec613944ddea377a0d124c90bf91c0049e3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..582a79fb5bfc3e91c58de428fcb7fba4f4beaa29 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_schema.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_schema.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e922fc54967c71e2af1a97251c1e3546142aa418 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_schema.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d62e39a4f43286af568183bdd54908a6f224d70a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/api.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/api.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c1b6e446aa9c22d0f2a4021d260798b6b0b916c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/api.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/conda_plugin.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/conda_plugin.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..083cc7b8e65ae25b82303ffc8f8f2ed7f1b1d090 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/conda_plugin.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5ad774cb430fb105dc0f3b409d497d16eb1365f1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__init__.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9726eabf6d1abaeb25a30ecf5f202107e09b7e96 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__init__.py @@ -0,0 +1,87 @@ +# Copyright (c) 2008-2011 by Enthought, Inc. +# Copyright (c) 2013-2015 Continuum Analytics, Inc. +# All rights reserved. + +from __future__ import absolute_import + +import json +import logging +import sys +from os.path import abspath, basename, exists, join + +try: + from .._version import __version__ +except ImportError: + __version__ = "dev" + +from ..utils import DEFAULT_BASE_PREFIX, DEFAULT_PREFIX, python_executable + +if sys.platform == 'win32': + from ..platforms.win_utils.win_elevate import isUserAdmin, runAsAdmin + from .win32 import Menu, ShortCut + + +def _install(path, remove=False, prefix=None, mode=None, root_prefix=None): + prefix = prefix or DEFAULT_PREFIX + root_prefix = root_prefix or DEFAULT_BASE_PREFIX + if abspath(prefix) == abspath(root_prefix): + env_name = None + else: + env_name = basename(prefix) + + data = json.load(open(path)) + try: + menu_name = data['menu_name'] + except KeyError: + menu_name = 'Python-%d.%d' % sys.version_info[:2] + + shortcuts = data['menu_items'] + m = Menu(menu_name, prefix=prefix, env_name=env_name, mode=mode, root_prefix=root_prefix) + if remove: + for sc in shortcuts: + ShortCut(m, sc).remove() + m.remove() + else: + m.create() + for sc in shortcuts: + ShortCut(m, sc).create() + + +def install(path, remove=False, prefix=None, recursing=False, root_prefix=None): + """ + Install Menu and shortcuts + + # Specifying `root_prefix` is used with conda-standalone, because we can't use + # `sys.prefix`, therefore we need to specify it + """ + prefix = prefix or DEFAULT_PREFIX + root_prefix = root_prefix or DEFAULT_BASE_PREFIX + if not sys.platform == 'win32': + raise RuntimeError("menuinst._legacy is only supported on Windows.") + + if not exists(join(prefix, ".nonadmin")) and not exists(join(root_prefix, ".nonadmin")): + if isUserAdmin(): + _install(path, remove, prefix, mode='system', root_prefix=root_prefix) + else: + retcode = 1 + try: + if not recursing: + retcode = runAsAdmin( + [ + *python_executable(), + '-c', + "import menuinst; menuinst.install(%r, %r, %r, %r, %r)" + % (path, bool(remove), prefix, True, root_prefix), + ] + ) + except OSError: + pass + + if retcode != 0: + logging.warning( + "Insufficient permissions to write menu folder. " + "Falling back to user location" + ) + _install(path, remove, prefix, mode='user', root_prefix=root_prefix) + else: + _install(path, remove, prefix, mode='user', root_prefix=root_prefix) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..473e3910b763ef3032456b7c29f3854d8a1a53a8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/cwp.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/cwp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fcbf3534c02b0cb148ecae5dee03c05d859a431 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/cwp.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/main.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/main.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1ffe037491013ec2a504a9b53ee8ff1ff636b528 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/main.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ba59bc1f976e2effd7f0b6240bcbe70d7a0f12c9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/win32.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/win32.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d9ceb9e501591486f933f55f9b51ce49eae37266 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/__pycache__/win32.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/cwp.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/cwp.py new file mode 100644 index 0000000000000000000000000000000000000000..93d56282bfbe3eed4c00e30670a52a28558f1856 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/cwp.py @@ -0,0 +1,56 @@ +# this script is used on windows to wrap shortcuts so that they are executed within an environment +# It only sets the appropriate prefix PATH entries - it does not actually activate environments + +import argparse +import os +import subprocess +import sys +from os.path import join, pathsep + +# this must be an absolute import since the cwp.py script is copied to $PREFIX +from menuinst.knownfolders import FOLDERID, get_folder_path + + +def main(argv=None): + # call as: python cwp.py [--no-console] PREFIX ARGs... + parser = argparse.ArgumentParser() + parser.add_argument( + "--no-console", action="store_true", help="Create subprocess with CREATE_NO_WINDOW flag." + ) + parser.add_argument("prefix", help="Prefix to be 'activated' before calling `args`.") + parser.add_argument( + "args", nargs=argparse.REMAINDER, help="Command (and arguments) to be executed." + ) + parsed_args = parser.parse_args(argv) + + no_console = parsed_args.no_console + prefix = parsed_args.prefix + args = parsed_args.args + + new_paths = pathsep.join( + [ + prefix, + join(prefix, "Library", "mingw-w64", "bin"), + join(prefix, "Library", "usr", "bin"), + join(prefix, "Library", "bin"), + join(prefix, "Scripts"), + ] + ) + env = os.environ.copy() + env["PATH"] = new_paths + pathsep + env["PATH"] + env["CONDA_PREFIX"] = prefix + + documents_folder, exception = get_folder_path(FOLDERID.Documents) + if exception: + documents_folder, exception = get_folder_path(FOLDERID.PublicDocuments) + if not exception: + os.chdir(documents_folder) + + creationflags = {} + if no_console: + creationflags["creationflags"] = getattr(subprocess, "CREATE_NO_WINDOW", 0x08000000) + sys.exit(subprocess.call(args, env=env, **creationflags)) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/main.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/main.py new file mode 100644 index 0000000000000000000000000000000000000000..6c62f2aa52e565c496783b9f0b969548e4d79314 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/main.py @@ -0,0 +1,30 @@ +import sys +from os.path import join + +from .. import __version__, install +from ..utils import DEFAULT_PREFIX + + +def main(): + from optparse import OptionParser + + p = OptionParser(usage="usage: %prog [options] MENU_FILE", description="install a menu item") + + p.add_option('-p', '--prefix', action="store", default=DEFAULT_PREFIX) + + p.add_option('--remove', action="store_true") + + p.add_option('--version', action="store_true") + + opts, args = p.parse_args() + + if opts.version: + sys.stdout.write("menuinst: %s\n" % __version__) + return + + for arg in args: + install(join(opts.prefix, arg), opts.remove, opts.prefix) + + +if __name__ == '__main__': + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/utils.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c5911a44705168bf5f87ec6284fc961bc9006d41 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/utils.py @@ -0,0 +1,21 @@ +import os +import shutil +from os.path import isdir, isfile, islink + + +def rm_empty_dir(path): + try: + os.rmdir(path) + except OSError: # directory might not exist or not be empty + pass + + +def rm_rf(path): + if islink(path) or isfile(path): + # Note that we have to check if the destination is a link because + # exists('/path/to/dead-link') will return False, although + # islink('/path/to/dead-link') is True. + os.unlink(path) + + elif isdir(path): + shutil.rmtree(path) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/win32.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/win32.py new file mode 100644 index 0000000000000000000000000000000000000000..b33f2d7f59edf1d86d2fb440b86ca82adeba5e3e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_legacy/win32.py @@ -0,0 +1,325 @@ +# Copyright (c) 2008-2011 by Enthought, Inc. +# Copyright (c) 2013-2017 Continuum Analytics, Inc. +# All rights reserved. + +from __future__ import absolute_import, unicode_literals + +import ctypes +import locale +import logging +import os +import sys +from os.path import exists, isdir, join + +from ..platforms.win_utils.knownfolders import dirs_src, folder_path +from ..platforms.win_utils.winshortcut import create_shortcut +from ..utils import DEFAULT_BASE_PREFIX +from .utils import rm_empty_dir, rm_rf + +# This allows debugging installer issues using DebugView from Microsoft. +OutputDebugString = ctypes.windll.kernel32.OutputDebugStringW +OutputDebugString.argtypes = [ctypes.c_wchar_p] + + +class DbgViewHandler(logging.Handler): + def emit(self, record): + OutputDebugString(self.format(record)) + + +logger = logging.getLogger("menuinst_win32") +logger.setLevel(logging.DEBUG) +stream_handler = logging.StreamHandler() +stream_handler.setLevel(logging.WARNING) +dbgview = DbgViewHandler() +dbgview.setLevel(logging.DEBUG) +logger.addHandler(dbgview) +logger.addHandler(stream_handler) + + +def quoted(s): + """ + quotes a string if necessary. + """ + # strip any existing quotes + s = s.strip(u'"') + # don't add quotes for minus or leading space + if s[0] in (u'-', u' '): + return s + if u' ' in s or u'/' in s: + return u'"%s"' % s + else: + return s + + +def ensure_pad(name, pad="_"): + """ + + Examples: + >>> ensure_pad('conda') + '_conda_' + + """ + if not name or name[0] == name[-1] == pad: + return name + else: + return "%s%s%s" % (pad, name, pad) + + +def to_unicode(var, codec=locale.getpreferredencoding()): + if not codec: + codec = "utf-8" + if hasattr(var, "decode"): + var = var.decode(codec) + return var + + +def to_bytes(var, codec=locale.getpreferredencoding()): + if isinstance(var, bytes): + return var + if not codec: + codec = "utf-8" + if hasattr(var, "encode"): + var = var.encode(codec) + return var + + +unicode_root_prefix = to_unicode(DEFAULT_BASE_PREFIX) +if u'\\envs\\' in unicode_root_prefix: + logger.warning('menuinst called from non-root env %s', unicode_root_prefix) + + +def substitute_env_variables(text, dir): + # When conda is using Menuinst, only the root conda installation ever + # calls menuinst. Thus, these calls to sys refer to the root conda + # installation, NOT the child environment + py_major_ver = sys.version_info[0] + py_bitness = 8 * tuple.__itemsize__ + + env_prefix = to_unicode(dir['prefix']) + root_prefix = to_unicode(dir['root_prefix']) + text = to_unicode(text) + env_name = to_unicode(dir['env_name']) + + for a, b in ( + (u'${PREFIX}', env_prefix), + (u'${ROOT_PREFIX}', root_prefix), + (u'${DISTRIBUTION_NAME}', os.path.split(root_prefix)[-1]), + ( + u'${PYTHON_SCRIPTS}', + os.path.normpath(join(env_prefix, u'Scripts')).replace(u"\\", u"/"), + ), + (u'${MENU_DIR}', join(env_prefix, u'Menu')), + (u'${PERSONALDIR}', dir['documents']), + (u'${USERPROFILE}', dir['profile']), + (u'${ENV_NAME}', env_name), + (u'${PY_VER}', u'%d' % (py_major_ver)), + (u'${PLATFORM}', u"(%s-bit)" % py_bitness), + ): + if b: + text = text.replace(a, b) + return text + + +class Menu(object): + def __init__( + self, + name, + prefix=unicode_root_prefix, + env_name=u"", + mode=None, + root_prefix=unicode_root_prefix, + ): + """ + Prefix is the system prefix to be used -- this is needed since + there is the possibility of a different Python's packages being managed. + """ + + # bytestrings passed in need to become unicode + self.prefix = to_unicode(prefix) + self.root_prefix = to_unicode(root_prefix) + used_mode = ( + mode if mode else ('user' if exists(join(self.prefix, u'.nonadmin')) else 'system') + ) + logger.debug( + "Menu: name: '%s', prefix: '%s', env_name: '%s', mode: '%s', used_mode: '%s', root_prefix: '%s'" # noqa + % (name, self.prefix, env_name, mode, used_mode, root_prefix) + ) + try: + self.set_dir(name, self.prefix, env_name, used_mode, root_prefix) + except WindowsError: + # We get here if we aren't elevated. This is different from + # permissions: a user can have permission, but elevation is still + # required. If the process isn't elevated, we get the + # WindowsError + if 'user' in dirs_src and used_mode == 'system': + logger.warning( + "Insufficient permissions to write menu folder. " + "Falling back to user location" + ) + try: + self.set_dir(name, self.prefix, env_name, 'user') + except: # noqa + pass + else: + logger.fatal("Unable to create AllUsers menu folder") + + def set_dir(self, name, prefix, env_name, mode, root_prefix): + self.mode = mode + self.dir = dict() + # I have chickened out on allowing check_other_mode. Really there needs + # to be 3 distinct cases that 'menuinst' cares about: + # priv-user doing system install + # priv-user doing user-only install + # non-priv-user doing user-only install + # (priv-user only exists in an AllUsers installation). + check_other_mode = False + for k, v in dirs_src[mode].items(): + # We may want to cache self.dir to some files, one for AllUsers + # (system) installs and one for each subsequent user install? + self.dir[k] = folder_path(mode, check_other_mode, k) + self.dir['prefix'] = prefix + self.dir['root_prefix'] = root_prefix + self.dir['env_name'] = env_name + folder_name = substitute_env_variables(name, self.dir) + self.path = join(self.dir["start"], folder_name) + self.create() + + def create(self): + if not isdir(self.path): + os.mkdir(self.path) + + def remove(self): + rm_empty_dir(self.path) + + +def extend_script_args(args, shortcut): + try: + args.append(shortcut['scriptargument']) + except KeyError: + pass + try: + args.extend(shortcut['scriptarguments']) + except KeyError: + pass + + +def quote_args(args): + # cmd.exe /K or /C expects a single string argument and requires + # doubled-up quotes when any sub-arguments have spaces: + # https://stackoverflow.com/a/6378038/3257826 + if ( + len(args) > 2 + and ("CMD.EXE" in args[0].upper() or "%COMSPEC%" in args[0].upper()) + and (args[1].upper() == '/K' or args[1].upper() == '/C') + and any(' ' in arg for arg in args[2:]) + ): + args = [ + ensure_pad(args[0], '"'), # cmd.exe + args[1], # /K or /C + '"%s"' % (' '.join(ensure_pad(arg, '"') for arg in args[2:])), # double-quoted + ] + else: + args = [quoted(arg) for arg in args] + return args + + +class ShortCut(object): + def __init__(self, menu, shortcut): + self.menu = menu + self.shortcut = shortcut + + def remove(self): + self.create(remove=True) + + def create(self, remove=False): + # Substitute env variables early because we may need to escape spaces in the value. + args = [] + fix_win_slashes = [0] + prefix = self.menu.prefix.replace('/', '\\') + unicode_root_prefix = self.menu.root_prefix.replace('/', '\\') + root_py = join(unicode_root_prefix, u"python.exe") + root_pyw = join(unicode_root_prefix, u"pythonw.exe") + env_py = join(prefix, u"python.exe") + env_pyw = join(prefix, u"pythonw.exe") + cwp_py = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix, env_py] + cwp_pyw = [root_pyw, join(unicode_root_prefix, u'cwp.py'), prefix, env_pyw] + if "pywscript" in self.shortcut: + args = cwp_pyw + fix_win_slashes = [len(args)] + args += self.shortcut["pywscript"].split() + elif "pyscript" in self.shortcut: + args = cwp_py + fix_win_slashes = [len(args)] + args += self.shortcut["pyscript"].split() + elif "webbrowser" in self.shortcut: + args = [root_pyw, '-m', 'webbrowser', '-t', self.shortcut['webbrowser']] + elif "script" in self.shortcut: + # It is unclear whether running through cwp.py is what we want here. In + # the long term I would rather this was made an explicit choice. + args = [root_py, join(unicode_root_prefix, u'cwp.py'), prefix] + fix_win_slashes = [len(args)] + args += self.shortcut["script"].split() + extend_script_args(args, self.shortcut) + elif "system" in self.shortcut: + args = self.shortcut["system"].split() + extend_script_args(args, self.shortcut) + else: + raise Exception("Nothing to do: %r" % self.shortcut) + args = [substitute_env_variables(arg, self.menu.dir) for arg in args] + for fws in fix_win_slashes: + args[fws] = args[fws].replace('/', '\\') + + args = quote_args(args) + + cmd = args[0] + args = args[1:] + logger.debug('Shortcut cmd is %s, args are %s' % (cmd, args)) + workdir = self.shortcut.get('workdir', '') + icon = self.shortcut.get('icon', '') + + workdir = substitute_env_variables(workdir, self.menu.dir) + icon = substitute_env_variables(icon, self.menu.dir) + + # Fix up the '/' to '\' + workdir = workdir.replace('/', '\\') + icon = icon.replace('/', '\\') + + # Create the working directory if it doesn't exist + if workdir: + if not isdir(workdir): + os.makedirs(workdir) + else: + workdir = '%HOMEPATH%' + + # Menu link + dst_dirs = [self.menu.path] + + # Desktop link + if self.shortcut.get('desktop'): + dst_dirs.append(self.menu.dir['desktop']) + + # Quicklaunch link + if self.shortcut.get('quicklaunch') and 'quicklaunch' in self.menu.dir: + dst_dirs.append(self.menu.dir['quicklaunch']) + + name_suffix = ( + " ({})".format(self.menu.dir['env_name']) if self.menu.dir['env_name'] else "" + ) + for dst_dir in dst_dirs: + name = substitute_env_variables(self.shortcut['name'], self.menu.dir) + dst = join(dst_dir, name + name_suffix + '.lnk') + if remove: + rm_rf(dst) + else: + # The API for the call to 'create_shortcut' has 3 + # required arguments (path, description and filename) + # and 4 optional ones (args, working_dir, icon_path and + # icon_index). + create_shortcut( + u'' + cmd, + u'' + name + name_suffix, + u'' + dst, + u' '.join(arg for arg in args), + u'' + workdir, + u'' + icon, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/LICENSE b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..ff33b8f7ca0b1c05bb0bdc546aa760c8e78757be --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/LICENSE @@ -0,0 +1,18 @@ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__init__.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..efd65767f14a5cbf9fa58db5a23f92e93d965ce5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__init__.py @@ -0,0 +1,39 @@ +""" +apipkg: control the exported namespace of a Python package. + +see https://pypi.python.org/pypi/apipkg + +(c) holger krekel, 2009 - MIT license +""" +from __future__ import annotations + +__all__ = ["initpkg", "ApiModule", "AliasModule", "__version__", "distribution_version"] +import sys +from typing import Any + +from ._alias_module import AliasModule +from ._importing import distribution_version as distribution_version +from ._module import _initpkg +from ._module import ApiModule +from ._version import version as __version__ + + +def initpkg( + pkgname: str, + exportdefs: dict[str, Any], + attr: dict[str, object] | None = None, + eager: bool = False, +) -> ApiModule: + """initialize given package from the export definitions.""" + attr = attr or {} + mod = sys.modules.get(pkgname) + + mod = _initpkg(mod, pkgname, exportdefs, attr=attr) + + # eagerload in bypthon to avoid their monkeypatching breaking packages + if "bpython" in sys.modules or eager: + for module in list(sys.modules.values()): + if isinstance(module, ApiModule): + getattr(module, "__dict__") + + return mod diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8d1dd16657b401943cfd67499fdac287c945d82 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_alias_module.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_alias_module.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13d5cb53ee51ebdddb0065768065f1f55f34e7ea Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_alias_module.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_importing.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_importing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..686f15da1c73af0604df159dbe7da1f42e863f18 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_importing.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_module.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_module.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef49864cee058f955012c1cc4ed52b7f9a28d293 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_module.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_syncronized.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_syncronized.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7012c25d3d4ee5f5809ea546f8a688c0023024ed Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_syncronized.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..75a000177c22962c2faf46938b7becacad9f24cb Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/__pycache__/_version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_alias_module.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_alias_module.py new file mode 100644 index 0000000000000000000000000000000000000000..a6f219aedfbcb34d1cfeba68942c9d8e9ce42309 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_alias_module.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +from types import ModuleType + +from ._importing import importobj + + +def AliasModule(modname: str, modpath: str, attrname: str | None = None) -> ModuleType: + + cached_obj: object | None = None + + def getmod() -> object: + nonlocal cached_obj + if cached_obj is None: + cached_obj = importobj(modpath, attrname) + return cached_obj + + x = modpath + ("." + attrname if attrname else "") + repr_result = f"" + + class AliasModule(ModuleType): + def __repr__(self) -> str: + return repr_result + + def __getattribute__(self, name: str) -> object: + try: + return getattr(getmod(), name) + except ImportError: + if modpath == "pytest" and attrname is None: + # hack for pylibs py.test + return None + else: + raise + + def __setattr__(self, name: str, value: object) -> None: + setattr(getmod(), name, value) + + def __delattr__(self, name: str) -> None: + delattr(getmod(), name) + + return AliasModule(str(modname)) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_importing.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_importing.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4587054e6dc0bb6977a385687f376ccc03cbe8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_importing.py @@ -0,0 +1,41 @@ +from __future__ import annotations + +import os +import sys + + +def _py_abspath(path: str) -> str: + """ + special version of abspath + that will leave paths from jython jars alone + """ + if path.startswith("__pyclasspath__"): + return path + else: + return os.path.abspath(path) + + +def distribution_version(name: str) -> str | None: + """try to get the version of the named distribution, + returns None on failure""" + if sys.version_info >= (3, 8): + from importlib.metadata import PackageNotFoundError, version + else: + from importlib_metadata import PackageNotFoundError, version + try: + return version(name) + except PackageNotFoundError: + return None + + +def importobj(modpath: str, attrname: str | None) -> object: + """imports a module, then resolves the attrname on it""" + module = __import__(modpath, None, None, ["__doc__"]) + if not attrname: + return module + + retval = module + names = attrname.split(".") + for x in names: + retval = getattr(retval, x) + return retval diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_module.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_module.py new file mode 100644 index 0000000000000000000000000000000000000000..5088034b6e8bd0d875d00e2390a47cfe06feda1a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_module.py @@ -0,0 +1,184 @@ +from __future__ import annotations + +import sys +import threading +from types import ModuleType +from typing import Any +from typing import Callable +from typing import cast +from typing import Iterable + +from ._importing import _py_abspath +from ._importing import importobj +from ._syncronized import _synchronized +from menuinst._vendor.apipkg import AliasModule + + +class ApiModule(ModuleType): + """the magical lazy-loading module standing""" + + def __docget(self) -> str | None: + try: + return self.__doc + except AttributeError: + if "__doc__" in self.__map__: + return cast(str, self.__makeattr("__doc__")) + else: + return None + + def __docset(self, value: str) -> None: + self.__doc = value + + __doc__ = property(__docget, __docset) # type: ignore + __map__: dict[str, tuple[str, str]] + + def __init__( + self, + name: str, + importspec: dict[str, Any], + implprefix: str | None = None, + attr: dict[str, Any] | None = None, + ) -> None: + super().__init__(name) + self.__name__ = name + self.__all__ = [x for x in importspec if x != "__onfirstaccess__"] + self.__map__ = {} + self.__implprefix__ = implprefix or name + if attr: + for name, val in attr.items(): + setattr(self, name, val) + for name, importspec in importspec.items(): + if isinstance(importspec, dict): + subname = f"{self.__name__}.{name}" + apimod = ApiModule(subname, importspec, implprefix) + sys.modules[subname] = apimod + setattr(self, name, apimod) + else: + parts = importspec.split(":") + modpath = parts.pop(0) + attrname = parts and parts[0] or "" + if modpath[0] == ".": + modpath = implprefix + modpath + + if not attrname: + subname = f"{self.__name__}.{name}" + apimod = AliasModule(subname, modpath) + sys.modules[subname] = apimod + if "." not in name: + setattr(self, name, apimod) + else: + self.__map__[name] = (modpath, attrname) + + def __repr__(self): + repr_list = [f"") + return "".join(repr_list) + + @_synchronized + def __makeattr(self, name, isgetattr=False): + """lazily compute value for name or raise AttributeError if unknown.""" + target = None + if "__onfirstaccess__" in self.__map__: + target = self.__map__.pop("__onfirstaccess__") + fn = cast(Callable[[], None], importobj(*target)) + fn() + try: + modpath, attrname = self.__map__[name] + except KeyError: + # __getattr__ is called when the attribute does not exist, but it may have + # been set by the onfirstaccess call above. Infinite recursion is not + # possible as __onfirstaccess__ is removed before the call (unless the call + # adds __onfirstaccess__ to __map__ explicitly, which is not our problem) + if target is not None and name != "__onfirstaccess__": + return getattr(self, name) + # Attribute may also have been set during a concurrent call to __getattr__ + # which executed after this call was already waiting on the lock. Check + # for a recently set attribute while avoiding infinite recursion: + # * Don't call __getattribute__ if __makeattr was called from a data + # descriptor such as the __doc__ or __dict__ properties, since data + # descriptors are called as part of object.__getattribute__ + # * Only call __getattribute__ if there is a possibility something has set + # the attribute we're looking for since __getattr__ was called + if threading is not None and isgetattr: + return super().__getattribute__(name) + raise AttributeError(name) + else: + result = importobj(modpath, attrname) + setattr(self, name, result) + # in a recursive-import situation a double-del can happen + self.__map__.pop(name, None) + return result + + def __getattr__(self, name): + return self.__makeattr(name, isgetattr=True) + + def __dir__(self) -> Iterable[str]: + yield from super().__dir__() + yield from self.__map__ + + @property + def __dict__(self) -> dict[str, Any]: # type: ignore + # force all the content of the module + # to be loaded when __dict__ is read + dictdescr = ModuleType.__dict__["__dict__"] # type: ignore + ns: dict[str, Any] = dictdescr.__get__(self) + if ns is not None: + hasattr(self, "some") + for name in self.__all__: + try: + self.__makeattr(name) + except AttributeError: + pass + return ns + + +_PRESERVED_MODULE_ATTRS = { + "__file__", + "__version__", + "__loader__", + "__path__", + "__package__", + "__doc__", + "__spec__", + "__dict__", +} + + +def _initpkg(mod: ModuleType | None, pkgname, exportdefs, attr=None) -> ApiModule: + """Helper for initpkg. + + Python 3.3+ uses finer grained locking for imports, and checks sys.modules before + acquiring the lock to avoid the overhead of the fine-grained locking. This + introduces a race condition when a module is imported by multiple threads + concurrently - some threads will see the initial module and some the replacement + ApiModule. We avoid this by updating the existing module in-place. + + """ + if mod is None: + d = {"__file__": None, "__spec__": None} + d.update(attr) + mod = ApiModule(pkgname, exportdefs, implprefix=pkgname, attr=d) + sys.modules[pkgname] = mod + return mod + else: + f = getattr(mod, "__file__", None) + if f: + f = _py_abspath(f) + mod.__file__ = f + if hasattr(mod, "__path__"): + mod.__path__ = [_py_abspath(p) for p in mod.__path__] + if "__doc__" in exportdefs and hasattr(mod, "__doc__"): + del mod.__doc__ + for name in dir(mod): + if name not in _PRESERVED_MODULE_ATTRS: + delattr(mod, name) + + # Updating class of existing module as per importlib.util.LazyLoader + mod.__class__ = ApiModule + apimod = cast(ApiModule, mod) + ApiModule.__init__(apimod, pkgname, exportdefs, implprefix=pkgname, attr=attr) + return apimod diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_syncronized.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_syncronized.py new file mode 100644 index 0000000000000000000000000000000000000000..71d3c2cb207dea7664d39a536ba0de09342e0466 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_syncronized.py @@ -0,0 +1,18 @@ +from __future__ import annotations + +import functools +import threading + + +def _synchronized(wrapped_function): + """Decorator to synchronise __getattr__ calls.""" + + # Lock shared between all instances of ApiModule to avoid possible deadlocks + lock = threading.RLock() + + @functools.wraps(wrapped_function) + def synchronized_wrapper_function(*args, **kwargs): + with lock: + return wrapped_function(*args, **kwargs) + + return synchronized_wrapper_function diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_version.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_version.py new file mode 100644 index 0000000000000000000000000000000000000000..773afd396bfcaf4f0d3f3e283c8817feca2884d1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/_version.py @@ -0,0 +1,5 @@ +# coding: utf-8 +# file generated by setuptools_scm +# don't change, don't track in version control +version = '3.0.1' +version_tuple = (3, 0, 1) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/py.typed b/data/miniconda3/lib/python3.13/site-packages/menuinst/_vendor/apipkg/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__init__.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed32c05eb7a24557e824c24abb90233b27ddf678 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__init__.py @@ -0,0 +1,3 @@ +from .cli import main + +__all__ = ["main"] diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3fb536db1685ed3c9f96f06bb142ba0639e9281b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/cli.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..deaa54965c5c6196b8709c07dd8e3bf2216f44b9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/__pycache__/cli.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/cli.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/cli.py new file mode 100644 index 0000000000000000000000000000000000000000..133eb8548a6a541967dd53d7fc75a0ef9491de39 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/cli/cli.py @@ -0,0 +1,99 @@ +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +from ..api import _install_adapter + +_MENU_RE = re.compile(r"(?:[-\._]menu)?\.json$", re.IGNORECASE) + + +def _add_install_group(parser: argparse.ArgumentParser) -> None: + install_group = parser.add_mutually_exclusive_group(required=True) + install_group.add_argument( + "--install", + nargs="*", + metavar="PKG", + help="create menu items for the given metadata JSON files or packages; " + "if none are given, create menu items for all packages " + "in the prefix", + ) + install_group.add_argument( + "--remove", + nargs="*", + metavar="PKG", + help="remove menu items for the given metadata JSON files or packages; " + "if none are given, remove menu items for all packages " + "in the prefix", + ) + + +def _add_prefix(parser: argparse.ArgumentParser): + parser.add_argument( + "--prefix", + required=True, + help="The prefix containing the shortcuts metadate inside `Menu`", + ) + + +def _add_root_prefix(parser: argparse.ArgumentParser): + parser.add_argument( + "--root-prefix", + help="The menuinst base/root prefix", + ) + + +def configure_parser(parser: argparse.ArgumentParser) -> None: + _add_prefix(parser) + _add_install_group(parser) + _add_root_prefix(parser) + + +def install( + prefix: Path, + root_prefix: str | None = None, + install_shortcuts: list[str] | None = None, + remove_shortcuts: list[str] | None = None, +): + packages = None + if install_shortcuts is not None: + packages = install_shortcuts + remove = False + elif remove_shortcuts is not None: + packages = remove_shortcuts + remove = True + else: + raise argparse.ArgumentError(None, "Must select shortcuts to install or remove.") + + if root_prefix: + root_prefix = str(Path(root_prefix).expanduser().resolve()) + + for json_path in (prefix / "Menu").glob("*.json"): + if ( + packages + and json_path.name not in packages + and _MENU_RE.sub("", json_path.name) not in packages + ): + continue + _install_adapter( + str(json_path), remove=remove, prefix=str(prefix), root_prefix=root_prefix + ) + + +def main(argv: list[str] | None = None): + argv = sys.argv[1:] if argv is None else argv + parser = argparse.ArgumentParser() + configure_parser(parser) + args = parser.parse_args(argv) + install( + Path(args.prefix).expanduser().resolve(), + root_prefix=args.root_prefix, + install_shortcuts=args.install, + remove_shortcuts=args.remove, + ) + + +if __name__ == "__main__": + main() diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.default.json new file mode 100644 index 0000000000000000000000000000000000000000..b220ad39118131774470cfb959bf8760d68ac878 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.default.json @@ -0,0 +1,66 @@ +{ + "id_": "https://schemas.conda.io/menuinst-1.schema.json", + "schema_": "https://json-schema.org/draft-07/schema", + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": true, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ] +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..b76b8ba7bf99c2962ff4395827584996db11f437 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-0.schema.json @@ -0,0 +1,676 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with ``menuinst``.", + "type": "object", + "properties": { + "$id": { + "title": "$Id", + "description": "Version of the menuinst schema.", + "enum": [ + "https://schemas.conda.io/menuinst-1.schema.json" + ], + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Standard of the JSON schema we adhere to.", + "enum": [ + "https://json-schema.org/draft-07/schema" + ], + "type": "string" + }, + "menu_name": { + "title": "Menu Name", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + } + }, + "required": [ + "$id", + "$schema", + "menu_name", + "menu_items" + ], + "additionalProperties": false, + "definitions": { + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions.\n\nCheck the `Desktop entry specification `__ for more details.\n\n.. desktop-entry-spec: https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html#recognized-keys", + "type": "object", + "properties": { + "name": { + "title": "Name", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "type": "string" + }, + "glob_patterns": { + "title": "Glob Patterns", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": ".*\\*.*" + } + } + }, + "additionalProperties": false + }, + "CFBundleURLTypesModel": { + "title": "CFBundleURLTypesModel", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "type": "string" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "additionalProperties": false + }, + "CFBundleDocumentTypesModel": { + "title": "CFBundleDocumentTypesModel", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false + }, + "UTTypeDeclarationModel": { + "title": "UTTypeDeclarationModel", + "type": "object", + "properties": { + "UTTypeConformsTo": { + "title": "Uttypeconformsto", + "type": "array", + "items": { + "type": "string" + } + }, + "UTTypeDescription": { + "title": "Uttypedescription", + "type": "string" + }, + "UTTypeIconFile": { + "title": "Uttypeiconfile", + "type": "string" + }, + "UTTypeIdentifier": { + "title": "Uttypeidentifier", + "type": "string" + }, + "UTTypeReferenceURL": { + "title": "Uttypereferenceurl", + "type": "string" + }, + "UTTypeTagSpecification": { + "title": "Uttypetagspecification", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- ``CF*`` keys: see `Core Foundation Keys `_\n- ``LS*`` keys: see `Launch Services Keys `_\n- ``entitlements``: see `entitlements docs `_\n\n.. _cf-keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html\n.. _ls-keys: https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html\n.. _entitlements-docs: https://developer.apple.com/documentation/bundleresources/entitlements.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleURLTypesModel" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleDocumentTypesModel" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "type": "boolean" + }, + "UTExportedTypeDeclarations": { + "title": "Utexportedtypedeclarations", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "UTImportedTypeDeclarations": { + "title": "Utimportedtypedeclarations", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "entitlements": { + "title": "Entitlements", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + }, + "event_handler": { + "title": "Event Handler", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false + }, + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "default": true, + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "default": true, + "type": "boolean" + }, + "url_protocols": { + "title": "Url Protocols", + "type": "array", + "items": { + "type": "string", + "pattern": "\\S+" + } + }, + "file_extensions": { + "title": "File Extensions", + "type": "array", + "items": { + "type": "string", + "pattern": "\\.\\S*" + } + }, + "app_user_model_id": { + "title": "App User Model Id", + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + } + }, + "additionalProperties": false + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level :class:`MenuItem`\n(sans ``platforms`` itself), in case overrides are needed.", + "type": "object", + "properties": { + "linux": { + "$ref": "#/definitions/Linux" + }, + "osx": { + "$ref": "#/definitions/MacOS" + }, + "win": { + "$ref": "#/definitions/Windows" + } + }, + "additionalProperties": false + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "minLength": 1, + "type": "string" + }, + "description": { + "title": "Description", + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "default": true, + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "default": false, + "type": "boolean" + }, + "platforms": { + "$ref": "#/definitions/Platforms" + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.default.json new file mode 100644 index 0000000000000000000000000000000000000000..c9acad433d51244392ad0cea1d18aacb9c8912f1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.default.json @@ -0,0 +1,68 @@ +{ + "id_": "https://schemas.conda.io/menuinst-1.schema.json", + "schema_": "https://json-schema.org/draft-07/schema", + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": true, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ] +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9e49980bf18b012d3f140ee05cf8a8403d8fa370 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-1.schema.json @@ -0,0 +1,731 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with ``menuinst``.", + "type": "object", + "properties": { + "$id": { + "title": "$Id", + "description": "Version of the menuinst schema.", + "enum": [ + "https://schemas.conda.io/menuinst-1.schema.json" + ], + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Standard of the JSON schema we adhere to.", + "enum": [ + "https://json-schema.org/draft-07/schema" + ], + "type": "string" + }, + "menu_name": { + "title": "Menu Name", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + } + }, + "required": [ + "$id", + "$schema", + "menu_name", + "menu_items" + ], + "additionalProperties": false, + "definitions": { + "MenuItemNameDict": { + "title": "MenuItemNameDict", + "description": "Variable menu item name.\nUse this dictionary if the menu item name depends on installation parameters\nsuch as the target environment.", + "type": "object", + "properties": { + "target_environment_is_base": { + "title": "Target Environment Is Base", + "minLength": 1, + "type": "string" + }, + "target_environment_is_not_base": { + "title": "Target Environment Is Not Base", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false + }, + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions.\n\nCheck the `Desktop entry specification\n`__\nfor more details.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "type": "string" + }, + "glob_patterns": { + "title": "Glob Patterns", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": ".*\\*.*" + } + } + }, + "additionalProperties": false + }, + "CFBundleURLTypesModel": { + "title": "CFBundleURLTypesModel", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "type": "string" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "additionalProperties": false + }, + "CFBundleDocumentTypesModel": { + "title": "CFBundleDocumentTypesModel", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false + }, + "UTTypeDeclarationModel": { + "title": "UTTypeDeclarationModel", + "type": "object", + "properties": { + "UTTypeConformsTo": { + "title": "Uttypeconformsto", + "type": "array", + "items": { + "type": "string" + } + }, + "UTTypeDescription": { + "title": "Uttypedescription", + "type": "string" + }, + "UTTypeIconFile": { + "title": "Uttypeiconfile", + "type": "string" + }, + "UTTypeIdentifier": { + "title": "Uttypeidentifier", + "type": "string" + }, + "UTTypeReferenceURL": { + "title": "Uttypereferenceurl", + "type": "string" + }, + "UTTypeTagSpecification": { + "title": "Uttypetagspecification", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- ``CF*`` keys: see `Core Foundation Keys `__\n- ``LS*`` keys: see `Launch Services Keys `__\n- ``entitlements``: see `Entitlements documentation `__", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleURLTypesModel" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleDocumentTypesModel" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "type": "boolean" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "title": "Nssupportsautomaticgraphicsswitching", + "type": "boolean" + }, + "UTExportedTypeDeclarations": { + "title": "Utexportedtypedeclarations", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "UTImportedTypeDeclarations": { + "title": "Utimportedtypedeclarations", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "entitlements": { + "title": "Entitlements", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + }, + "event_handler": { + "title": "Event Handler", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false + }, + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "type": "string" + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "default": true, + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "default": true, + "type": "boolean" + }, + "terminal_profile": { + "title": "Terminal Profile", + "minLength": 1, + "type": "string" + }, + "url_protocols": { + "title": "Url Protocols", + "type": "array", + "items": { + "type": "string", + "pattern": "\\S+" + } + }, + "file_extensions": { + "title": "File Extensions", + "type": "array", + "items": { + "type": "string", + "pattern": "\\.\\S*" + } + }, + "app_user_model_id": { + "title": "App User Model Id", + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + } + }, + "additionalProperties": false + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level :class:`MenuItem`\n(sans ``platforms`` itself), in case overrides are needed.", + "type": "object", + "properties": { + "linux": { + "$ref": "#/definitions/Linux" + }, + "osx": { + "$ref": "#/definitions/MacOS" + }, + "win": { + "$ref": "#/definitions/Windows" + } + }, + "additionalProperties": false + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "type": "string" + }, + "command": { + "title": "Command", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "icon": { + "title": "Icon", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "minLength": 1, + "type": "string" + }, + "working_dir": { + "title": "Working Dir", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "default": true, + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "default": false, + "type": "boolean" + }, + "platforms": { + "$ref": "#/definitions/Platforms" + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.default.json new file mode 100644 index 0000000000000000000000000000000000000000..489958b1556fd2c556625563ebdc1086f8dc9575 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.default.json @@ -0,0 +1,69 @@ +{ + "id_": "https://schemas.conda.io/menuinst-1.schema.json", + "schema_": "https://json-schema.org/draft-07/schema", + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ] +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8491ce9f6938c2ecd69036ad32b5b0caa7fb4efc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-0-2.schema.json @@ -0,0 +1,967 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "type": "object", + "properties": { + "$id": { + "title": "$Id", + "description": "Version of the menuinst schema.", + "markdownDescription": "Version of the menuinst schema.", + "enum": [ + "https://schemas.conda.io/menuinst-1.schema.json" + ], + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Standard of the JSON schema we adhere to.", + "markdownDescription": "Standard of the JSON schema we adhere to.", + "enum": [ + "https://json-schema.org/draft-07/schema" + ], + "type": "string" + }, + "menu_name": { + "title": "Menu Name", + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "description": "List of menu entries to create across main desktop systems.", + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + } + }, + "required": [ + "$id", + "$schema", + "menu_name", + "menu_items" + ], + "additionalProperties": false, + "markdownDescription": "Metadata required to create menu items across operating systems with `menuinst`.", + "definitions": { + "MenuItemNameDict": { + "title": "MenuItemNameDict", + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "type": "object", + "properties": { + "target_environment_is_base": { + "title": "Target Environment Is Base", + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "minLength": 1, + "type": "string" + }, + "target_environment_is_not_base": { + "title": "Target Environment Is Not Base", + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment." + }, + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "type": "boolean" + }, + "SingleMainWindow": { + "title": "Singlemainwindow", + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "type": "string" + }, + "glob_patterns": { + "title": "Glob Patterns", + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": ".*\\*.*" + } + } + }, + "additionalProperties": false, + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details." + }, + "CFBundleURLTypesModel": { + "title": "CFBundleURLTypesModel", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "additionalProperties": false, + "markdownDescription": "Describes a URL scheme associated with the app." + }, + "CFBundleDocumentTypesModel": { + "title": "CFBundleDocumentTypesModel", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false, + "markdownDescription": "Describes a document type associated with the app." + }, + "UTTypeDeclarationModel": { + "title": "UTTypeDeclarationModel", + "type": "object", + "properties": { + "UTTypeConformsTo": { + "title": "Uttypeconformsto", + "description": "The Uniform Type Identifier types that this type conforms to.", + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "type": "array", + "items": { + "type": "string" + } + }, + "UTTypeDescription": { + "title": "Uttypedescription", + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "type": "string" + }, + "UTTypeIconFile": { + "title": "Uttypeiconfile", + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "type": "string" + }, + "UTTypeIdentifier": { + "title": "Uttypeidentifier", + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "type": "string" + }, + "UTTypeReferenceURL": { + "title": "Uttypereferenceurl", + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "type": "string" + }, + "UTTypeTagSpecification": { + "title": "Uttypetagspecification", + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "description": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleURLTypesModel" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "description": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "markdownDescription": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleDocumentTypesModel" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "type": "boolean" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "title": "Nssupportsautomaticgraphicsswitching", + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "type": "boolean" + }, + "UTExportedTypeDeclarations": { + "title": "Utexportedtypedeclarations", + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "UTImportedTypeDeclarations": { + "title": "Utimportedtypedeclarations", + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "entitlements": { + "title": "Entitlements", + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + }, + "event_handler": { + "title": "Event Handler", + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)" + }, + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "default": true, + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "default": false, + "deprecated": true, + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "type": "boolean" + }, + "terminal_profile": { + "title": "Terminal Profile", + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "minLength": 1, + "type": "string" + }, + "url_protocols": { + "title": "Url Protocols", + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\S+" + } + }, + "file_extensions": { + "title": "File Extensions", + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\.\\S*" + } + }, + "app_user_model_id": { + "title": "App User Model Id", + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed" + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "type": "object", + "properties": { + "linux": { + "title": "Linux", + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Linux" + } + ] + }, + "osx": { + "title": "Osx", + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details.", + "allOf": [ + { + "$ref": "#/definitions/MacOS" + } + ] + }, + "win": { + "title": "Win", + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Windows" + } + ] + } + }, + "additionalProperties": false, + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed." + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "default": true, + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "default": false, + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "platforms": { + "title": "Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "allOf": [ + { + "$ref": "#/definitions/Platforms" + } + ] + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false, + "markdownDescription": "Instructions to create a menu item across operating systems." + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.default.json new file mode 100644 index 0000000000000000000000000000000000000000..ab13c3e5d0af46619cb75278ebc8321efa25b09d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.default.json @@ -0,0 +1,68 @@ +{ + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ], + "$schema": "https://schemas.conda.org/menuinst-1-1-0.schema.json" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..6c815e64761a0e3999476b7b6c128c43684dcae2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-0.schema.json @@ -0,0 +1,966 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "type": "object", + "properties": { + "$id": { + "title": "$Id", + "description": "DEPRECATED. Use ``$schema``.", + "default": "https://schemas.conda.org/menuinst-1-1-0.schema.json", + "deprecated": true, + "markdownDescription": "DEPRECATED. Use ``$schema``.", + "minLength": 1, + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Version of the menuinst schema to validate against.", + "default": "https://schemas.conda.org/menuinst-1-1-0.schema.json", + "markdownDescription": "Version of the menuinst schema to validate against.", + "minLength": 1, + "type": "string" + }, + "menu_name": { + "title": "Menu Name", + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "description": "List of menu entries to create across main desktop systems.", + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + } + }, + "required": [ + "menu_name", + "menu_items" + ], + "additionalProperties": false, + "$schema": "http://json-schema.org/draft-07/schema#", + "$id": "https://schemas.conda.org/menuinst-1-1-0.schema.json", + "$version": "1-1-0", + "definitions": { + "MenuItemNameDict": { + "title": "MenuItemNameDict", + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "type": "object", + "properties": { + "target_environment_is_base": { + "title": "Target Environment Is Base", + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "minLength": 1, + "type": "string" + }, + "target_environment_is_not_base": { + "title": "Target Environment Is Not Base", + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment." + }, + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "type": "boolean" + }, + "SingleMainWindow": { + "title": "Singlemainwindow", + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "type": "string" + }, + "glob_patterns": { + "title": "Glob Patterns", + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": ".*\\*.*" + } + } + }, + "additionalProperties": false, + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details." + }, + "CFBundleURLTypesModel": { + "title": "CFBundleURLTypesModel", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "additionalProperties": false, + "markdownDescription": "Describes a URL scheme associated with the app." + }, + "CFBundleDocumentTypesModel": { + "title": "CFBundleDocumentTypesModel", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false, + "markdownDescription": "Describes a document type associated with the app." + }, + "UTTypeDeclarationModel": { + "title": "UTTypeDeclarationModel", + "type": "object", + "properties": { + "UTTypeConformsTo": { + "title": "Uttypeconformsto", + "description": "The Uniform Type Identifier types that this type conforms to.", + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "type": "array", + "items": { + "type": "string" + } + }, + "UTTypeDescription": { + "title": "Uttypedescription", + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "type": "string" + }, + "UTTypeIconFile": { + "title": "Uttypeiconfile", + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "type": "string" + }, + "UTTypeIdentifier": { + "title": "Uttypeidentifier", + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "type": "string" + }, + "UTTypeReferenceURL": { + "title": "Uttypereferenceurl", + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "type": "string" + }, + "UTTypeTagSpecification": { + "title": "Uttypetagspecification", + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "description": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleURLTypesModel" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "description": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "markdownDescription": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleDocumentTypesModel" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "type": "boolean" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "title": "Nssupportsautomaticgraphicsswitching", + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "type": "boolean" + }, + "UTExportedTypeDeclarations": { + "title": "Utexportedtypedeclarations", + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "UTImportedTypeDeclarations": { + "title": "Utimportedtypedeclarations", + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "entitlements": { + "title": "Entitlements", + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + }, + "event_handler": { + "title": "Event Handler", + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)" + }, + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "default": true, + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "default": false, + "deprecated": true, + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "type": "boolean" + }, + "terminal_profile": { + "title": "Terminal Profile", + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "minLength": 1, + "type": "string" + }, + "url_protocols": { + "title": "Url Protocols", + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\S+" + } + }, + "file_extensions": { + "title": "File Extensions", + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\.\\S*" + } + }, + "app_user_model_id": { + "title": "App User Model Id", + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed" + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "type": "object", + "properties": { + "linux": { + "title": "Linux", + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Linux" + } + ] + }, + "osx": { + "title": "Osx", + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details.", + "allOf": [ + { + "$ref": "#/definitions/MacOS" + } + ] + }, + "win": { + "title": "Win", + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Windows" + } + ] + } + }, + "additionalProperties": false, + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed." + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "default": true, + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "default": false, + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "platforms": { + "title": "Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "allOf": [ + { + "$ref": "#/definitions/Platforms" + } + ] + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false, + "markdownDescription": "Instructions to create a menu item across operating systems." + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.default.json new file mode 100644 index 0000000000000000000000000000000000000000..a81799c1af8ffacf12b21c5d3ef30147e36e8412 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.default.json @@ -0,0 +1,68 @@ +{ + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ], + "$schema": "https://schemas.conda.org/menuinst-1-1-1.schema.json" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..d17d07b1e839f5aee64d1441846f7247f440da25 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-1.schema.json @@ -0,0 +1,1605 @@ +{ + "$defs": { + "CFBundleDocumentTypesModel": { + "additionalProperties": false, + "description": "Describes a document type associated with the app.", + "markdownDescription": "Describes a document type associated with the app.", + "properties": { + "CFBundleTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundletypeiconfile" + }, + "CFBundleTypeName": { + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "title": "Cfbundletypename", + "type": "string" + }, + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "title": "Cfbundletyperole" + }, + "LSItemContentTypes": { + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "items": { + "type": "string" + }, + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "title": "Lsitemcontenttypes", + "type": "array" + }, + "LSHandlerRank": { + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "title": "Lshandlerrank", + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "title": "CFBundleDocumentTypesModel", + "type": "object" + }, + "CFBundleURLTypesModel": { + "additionalProperties": false, + "description": "Describes a URL scheme associated with the app.", + "markdownDescription": "Describes a URL scheme associated with the app.", + "properties": { + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "title": "Cfbundletyperole" + }, + "CFBundleURLSchemes": { + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "items": { + "type": "string" + }, + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "title": "Cfbundleurlschemes", + "type": "array" + }, + "CFBundleURLName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "title": "Cfbundleurlname" + }, + "CFBundleURLIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundleurliconfile" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "title": "CFBundleURLTypesModel", + "type": "object" + }, + "Linux": { + "additionalProperties": false, + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "Categories": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "title": "Categories" + }, + "DBusActivatable": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "title": "Dbusactivatable" + }, + "GenericName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "title": "Genericname" + }, + "Hidden": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "title": "Hidden" + }, + "Implements": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "title": "Implements" + }, + "Keywords": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "title": "Keywords" + }, + "MimeType": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "title": "Mimetype" + }, + "NoDisplay": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "title": "Nodisplay" + }, + "NotShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Notshowin" + }, + "OnlyShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Onlyshowin" + }, + "PrefersNonDefaultGPU": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "title": "Prefersnondefaultgpu" + }, + "SingleMainWindow": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "title": "Singlemainwindow" + }, + "StartupNotify": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupnotify" + }, + "StartupWMClass": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupwmclass" + }, + "TryExec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "title": "Tryexec" + }, + "glob_patterns": { + "anyOf": [ + { + "additionalProperties": { + "pattern": ".*\\*.*", + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "title": "Glob Patterns" + } + }, + "title": "Linux", + "type": "object" + }, + "MacOS": { + "additionalProperties": false, + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "CFBundleDisplayName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "title": "Cfbundledisplayname" + }, + "CFBundleIdentifier": { + "anyOf": [ + { + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundleidentifier" + }, + "CFBundleName": { + "anyOf": [ + { + "maxLength": 16, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundlename" + }, + "CFBundleSpokenName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "title": "Cfbundlespokenname" + }, + "CFBundleVersion": { + "anyOf": [ + { + "pattern": "^\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "title": "Cfbundleversion" + }, + "CFBundleURLTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleURLTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "title": "Cfbundleurltypes" + }, + "CFBundleDocumentTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleDocumentTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "markdownDescription": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "title": "Cfbundledocumenttypes" + }, + "LSApplicationCategoryType": { + "anyOf": [ + { + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "title": "Lsapplicationcategorytype" + }, + "LSBackgroundOnly": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "title": "Lsbackgroundonly" + }, + "LSEnvironment": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "title": "Lsenvironment" + }, + "LSMinimumSystemVersion": { + "anyOf": [ + { + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "title": "Lsminimumsystemversion" + }, + "LSMultipleInstancesProhibited": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "title": "Lsmultipleinstancesprohibited" + }, + "LSRequiresNativeExecution": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "title": "Lsrequiresnativeexecution" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "title": "Nssupportsautomaticgraphicsswitching" + }, + "UTExportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "title": "Utexportedtypedeclarations" + }, + "UTImportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "title": "Utimportedtypedeclarations" + }, + "entitlements": { + "anyOf": [ + { + "items": { + "pattern": "[a-z0-9\\.\\-]+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "title": "Entitlements" + }, + "link_in_bundle": { + "anyOf": [ + { + "additionalProperties": { + "pattern": "^[^/]+.*", + "type": "string" + }, + "propertyNames": { + "minLength": 1 + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "title": "Link In Bundle" + }, + "event_handler": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "title": "Event Handler" + } + }, + "title": "MacOS", + "type": "object" + }, + "MenuItem": { + "additionalProperties": false, + "description": "Instructions to create a menu item across operating systems.", + "markdownDescription": "Instructions to create a menu item across operating systems.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + } + ], + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description", + "type": "string" + }, + "command": { + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "items": { + "type": "string" + }, + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "title": "Command", + "type": "array" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "platforms": { + "$ref": "#/$defs/Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform." + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "title": "MenuItem", + "type": "object" + }, + "MenuItemNameDict": { + "additionalProperties": false, + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "properties": { + "target_environment_is_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "title": "Target Environment Is Base" + }, + "target_environment_is_not_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "title": "Target Environment Is Not Base" + } + }, + "title": "MenuItemNameDict", + "type": "object" + }, + "Platforms": { + "additionalProperties": false, + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "properties": { + "linux": { + "anyOf": [ + { + "$ref": "#/$defs/Linux" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details." + }, + "osx": { + "anyOf": [ + { + "$ref": "#/$defs/MacOS" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details." + }, + "win": { + "anyOf": [ + { + "$ref": "#/$defs/Windows" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details." + } + }, + "title": "Platforms", + "type": "object" + }, + "UTTypeDeclarationModel": { + "additionalProperties": false, + "properties": { + "UTTypeConformsTo": { + "description": "The Uniform Type Identifier types that this type conforms to.", + "items": { + "type": "string" + }, + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "title": "Uttypeconformsto", + "type": "array" + }, + "UTTypeDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "title": "Uttypedescription" + }, + "UTTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "title": "Uttypeiconfile" + }, + "UTTypeIdentifier": { + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "title": "Uttypeidentifier", + "type": "string" + }, + "UTTypeReferenceURL": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "title": "Uttypereferenceurl" + }, + "UTTypeTagSpecification": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "title": "Uttypetagspecification", + "type": "object" + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "title": "UTTypeDeclarationModel", + "type": "object" + }, + "Windows": { + "additionalProperties": false, + "description": "Windows-specific instructions. You can override global keys here if needed", + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "desktop": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "title": "Desktop" + }, + "quicklaunch": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "deprecated": true, + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "title": "Quicklaunch" + }, + "terminal_profile": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "title": "Terminal Profile" + }, + "url_protocols": { + "anyOf": [ + { + "items": { + "pattern": "\\S+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "title": "Url Protocols" + }, + "file_extensions": { + "anyOf": [ + { + "items": { + "pattern": "\\.\\S*", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "title": "File Extensions" + }, + "app_user_model_id": { + "anyOf": [ + { + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "title": "App User Model Id" + } + }, + "title": "Windows", + "type": "object" + } + }, + "$id": "https://schemas.conda.org/menuinst-1-1-1.schema.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "$version": "1-1-1", + "additionalProperties": false, + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "properties": { + "$id": { + "default": "https://schemas.conda.org/menuinst-1-1-1.schema.json", + "deprecated": true, + "description": "DEPRECATED. Use ``$schema``.", + "markdownDescription": "DEPRECATED. Use ``$schema``.", + "minLength": 1, + "title": "$Id", + "type": "string" + }, + "$schema": { + "default": "https://schemas.conda.org/menuinst-1-1-1.schema.json", + "description": "Version of the menuinst schema to validate against.", + "markdownDescription": "Version of the menuinst schema to validate against.", + "minLength": 1, + "title": "$Schema", + "type": "string" + }, + "menu_name": { + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "title": "Menu Name", + "type": "string" + }, + "menu_items": { + "description": "List of menu entries to create across main desktop systems.", + "items": { + "$ref": "#/$defs/MenuItem" + }, + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "title": "Menu Items", + "type": "array" + } + }, + "required": [ + "menu_name", + "menu_items" + ], + "title": "MenuInstSchema", + "type": "object" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.default.json new file mode 100644 index 0000000000000000000000000000000000000000..760fb0b7453ea3179bc47b7ce12c4d6e9476a46c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.default.json @@ -0,0 +1,72 @@ +{ + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSAudioCaptureUsageDescription": null, + "NSCameraUsageDescription": null, + "NSMainCameraUsageDescription": null, + "NSMicrophoneUsageDescription": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ], + "$schema": "https://schemas.conda.org/menuinst-1-1-2.schema.json" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..9e9281cda400b82d2f18b7162a62b2d7641f9a3c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-2.schema.json @@ -0,0 +1,1661 @@ +{ + "$defs": { + "CFBundleDocumentTypesModel": { + "additionalProperties": false, + "description": "Describes a document type associated with the app.", + "markdownDescription": "Describes a document type associated with the app.", + "properties": { + "CFBundleTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundletypeiconfile" + }, + "CFBundleTypeName": { + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "title": "Cfbundletypename", + "type": "string" + }, + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "title": "Cfbundletyperole" + }, + "LSItemContentTypes": { + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "items": { + "type": "string" + }, + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "title": "Lsitemcontenttypes", + "type": "array" + }, + "LSHandlerRank": { + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "title": "Lshandlerrank", + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "title": "CFBundleDocumentTypesModel", + "type": "object" + }, + "CFBundleURLTypesModel": { + "additionalProperties": false, + "description": "Describes a URL scheme associated with the app.", + "markdownDescription": "Describes a URL scheme associated with the app.", + "properties": { + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "title": "Cfbundletyperole" + }, + "CFBundleURLSchemes": { + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "items": { + "type": "string" + }, + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "title": "Cfbundleurlschemes", + "type": "array" + }, + "CFBundleURLName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "title": "Cfbundleurlname" + }, + "CFBundleURLIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundleurliconfile" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "title": "CFBundleURLTypesModel", + "type": "object" + }, + "Linux": { + "additionalProperties": false, + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "Categories": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "title": "Categories" + }, + "DBusActivatable": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "title": "Dbusactivatable" + }, + "GenericName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "title": "Genericname" + }, + "Hidden": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "title": "Hidden" + }, + "Implements": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "title": "Implements" + }, + "Keywords": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "title": "Keywords" + }, + "MimeType": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "title": "Mimetype" + }, + "NoDisplay": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "title": "Nodisplay" + }, + "NotShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Notshowin" + }, + "OnlyShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Onlyshowin" + }, + "PrefersNonDefaultGPU": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "title": "Prefersnondefaultgpu" + }, + "SingleMainWindow": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "title": "Singlemainwindow" + }, + "StartupNotify": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupnotify" + }, + "StartupWMClass": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupwmclass" + }, + "TryExec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "title": "Tryexec" + }, + "glob_patterns": { + "anyOf": [ + { + "additionalProperties": { + "pattern": ".*\\*.*", + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "title": "Glob Patterns" + } + }, + "title": "Linux", + "type": "object" + }, + "MacOS": { + "additionalProperties": false, + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "CFBundleDisplayName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "title": "Cfbundledisplayname" + }, + "CFBundleIdentifier": { + "anyOf": [ + { + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundleidentifier" + }, + "CFBundleName": { + "anyOf": [ + { + "maxLength": 16, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundlename" + }, + "CFBundleSpokenName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "title": "Cfbundlespokenname" + }, + "CFBundleVersion": { + "anyOf": [ + { + "pattern": "^\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "title": "Cfbundleversion" + }, + "CFBundleURLTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleURLTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "markdownDescription": "URL types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "title": "Cfbundleurltypes" + }, + "CFBundleDocumentTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleDocumentTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Document types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "markdownDescription": "Document types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "title": "Cfbundledocumenttypes" + }, + "LSApplicationCategoryType": { + "anyOf": [ + { + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "title": "Lsapplicationcategorytype" + }, + "LSBackgroundOnly": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "title": "Lsbackgroundonly" + }, + "LSEnvironment": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "title": "Lsenvironment" + }, + "LSMinimumSystemVersion": { + "anyOf": [ + { + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "title": "Lsminimumsystemversion" + }, + "LSMultipleInstancesProhibited": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "title": "Lsmultipleinstancesprohibited" + }, + "LSRequiresNativeExecution": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "title": "Lsrequiresnativeexecution" + }, + "NSAudioCaptureUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to capture system audio.", + "markdownDescription": "A message describing why an app is requesting access to capture system audio.", + "title": "Nsaudiocaptureusagedescription" + }, + "NSCameraUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's camera.", + "markdownDescription": "A message describing why an app is requesting access to the device's camera.", + "title": "Nscamerausagedescription" + }, + "NSMainCameraUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's main camera.", + "markdownDescription": "A message describing why an app is requesting access to the device's main camera.", + "title": "Nsmaincamerausagedescription" + }, + "NSMicrophoneUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's microphone.", + "markdownDescription": "A message describing why an app is requesting access to the device's microphone.", + "title": "Nsmicrophoneusagedescription" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "title": "Nssupportsautomaticgraphicsswitching" + }, + "UTExportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "title": "Utexportedtypedeclarations" + }, + "UTImportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "title": "Utimportedtypedeclarations" + }, + "entitlements": { + "anyOf": [ + { + "items": { + "pattern": "[a-z0-9\\.\\-]+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "title": "Entitlements" + }, + "link_in_bundle": { + "anyOf": [ + { + "additionalProperties": { + "pattern": "^[^/]+.*", + "type": "string" + }, + "propertyNames": { + "minLength": 1 + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "title": "Link In Bundle" + }, + "event_handler": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above. Using this key will inject a custom Swift launcher in the `.app` bundle to listen to Apple Events and forward them to your application. If your app is already handling Apple Events (e.g. via Qt's `QFileOpenEvent`), you do not need this.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above. Using this key will inject a custom Swift launcher in the `.app` bundle to listen to Apple Events and forward them to your application. If your app is already handling Apple Events (e.g. via Qt's `QFileOpenEvent`), you do not need this.", + "title": "Event Handler" + } + }, + "title": "MacOS", + "type": "object" + }, + "MenuItem": { + "additionalProperties": false, + "description": "Instructions to create a menu item across operating systems.", + "markdownDescription": "Instructions to create a menu item across operating systems.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + } + ], + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description", + "type": "string" + }, + "command": { + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "items": { + "type": "string" + }, + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "title": "Command", + "type": "array" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "platforms": { + "$ref": "#/$defs/Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform." + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "title": "MenuItem", + "type": "object" + }, + "MenuItemNameDict": { + "additionalProperties": false, + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "properties": { + "target_environment_is_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "title": "Target Environment Is Base" + }, + "target_environment_is_not_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "title": "Target Environment Is Not Base" + } + }, + "title": "MenuItemNameDict", + "type": "object" + }, + "Platforms": { + "additionalProperties": false, + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "properties": { + "linux": { + "anyOf": [ + { + "$ref": "#/$defs/Linux" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details." + }, + "osx": { + "anyOf": [ + { + "$ref": "#/$defs/MacOS" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details." + }, + "win": { + "anyOf": [ + { + "$ref": "#/$defs/Windows" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details." + } + }, + "title": "Platforms", + "type": "object" + }, + "UTTypeDeclarationModel": { + "additionalProperties": false, + "properties": { + "UTTypeConformsTo": { + "description": "The Uniform Type Identifier types that this type conforms to.", + "items": { + "type": "string" + }, + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "title": "Uttypeconformsto", + "type": "array" + }, + "UTTypeDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "title": "Uttypedescription" + }, + "UTTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "title": "Uttypeiconfile" + }, + "UTTypeIdentifier": { + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "title": "Uttypeidentifier", + "type": "string" + }, + "UTTypeReferenceURL": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "title": "Uttypereferenceurl" + }, + "UTTypeTagSpecification": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "title": "Uttypetagspecification", + "type": "object" + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "title": "UTTypeDeclarationModel", + "type": "object" + }, + "Windows": { + "additionalProperties": false, + "description": "Windows-specific instructions. You can override global keys here if needed", + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "desktop": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "title": "Desktop" + }, + "quicklaunch": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "deprecated": true, + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "title": "Quicklaunch" + }, + "terminal_profile": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "title": "Terminal Profile" + }, + "url_protocols": { + "anyOf": [ + { + "items": { + "pattern": "\\S+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "title": "Url Protocols" + }, + "file_extensions": { + "anyOf": [ + { + "items": { + "pattern": "\\.\\S*", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "title": "File Extensions" + }, + "app_user_model_id": { + "anyOf": [ + { + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "title": "App User Model Id" + } + }, + "title": "Windows", + "type": "object" + } + }, + "$id": "https://schemas.conda.org/menuinst-1-1-2.schema.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "$version": "1-1-2", + "additionalProperties": false, + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "properties": { + "$id": { + "default": "https://schemas.conda.org/menuinst-1-1-2.schema.json", + "deprecated": true, + "description": "DEPRECATED. Use ``$schema``.", + "markdownDescription": "DEPRECATED. Use ``$schema``.", + "minLength": 1, + "title": "$Id", + "type": "string" + }, + "$schema": { + "default": "https://schemas.conda.org/menuinst-1-1-2.schema.json", + "description": "Version of the menuinst schema to validate against.", + "markdownDescription": "Version of the menuinst schema to validate against.", + "minLength": 1, + "title": "$Schema", + "type": "string" + }, + "menu_name": { + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "title": "Menu Name", + "type": "string" + }, + "menu_items": { + "description": "List of menu entries to create across main desktop systems.", + "items": { + "$ref": "#/$defs/MenuItem" + }, + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "title": "Menu Items", + "type": "array" + } + }, + "required": [ + "menu_name", + "menu_items" + ], + "title": "MenuInstSchema", + "type": "object" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.default.json new file mode 100644 index 0000000000000000000000000000000000000000..73c6f5d3c329d0d01042c76a01d9fe4a68484740 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.default.json @@ -0,0 +1,73 @@ +{ + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSAudioCaptureUsageDescription": null, + "NSCameraUsageDescription": null, + "NSMainCameraUsageDescription": null, + "NSMicrophoneUsageDescription": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "info_plist_extra": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ], + "$schema": "https://schemas.conda.org/menuinst-1-1-3.schema.json" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..571f56a792ee50a274f9ce501fa7e8b87788aa56 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst-1-1-3.schema.json @@ -0,0 +1,1679 @@ +{ + "$defs": { + "CFBundleDocumentTypesModel": { + "additionalProperties": false, + "description": "Describes a document type associated with the app.", + "markdownDescription": "Describes a document type associated with the app.", + "properties": { + "CFBundleTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundletypeiconfile" + }, + "CFBundleTypeName": { + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "title": "Cfbundletypename", + "type": "string" + }, + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "title": "Cfbundletyperole" + }, + "LSItemContentTypes": { + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "items": { + "type": "string" + }, + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "title": "Lsitemcontenttypes", + "type": "array" + }, + "LSHandlerRank": { + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "title": "Lshandlerrank", + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "title": "CFBundleDocumentTypesModel", + "type": "object" + }, + "CFBundleURLTypesModel": { + "additionalProperties": false, + "description": "Describes a URL scheme associated with the app.", + "markdownDescription": "Describes a URL scheme associated with the app.", + "properties": { + "CFBundleTypeRole": { + "anyOf": [ + { + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "title": "Cfbundletyperole" + }, + "CFBundleURLSchemes": { + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "items": { + "type": "string" + }, + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "title": "Cfbundleurlschemes", + "type": "array" + }, + "CFBundleURLName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "title": "Cfbundleurlname" + }, + "CFBundleURLIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "title": "Cfbundleurliconfile" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "title": "CFBundleURLTypesModel", + "type": "object" + }, + "Linux": { + "additionalProperties": false, + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "Categories": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "title": "Categories" + }, + "DBusActivatable": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "title": "Dbusactivatable" + }, + "GenericName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "title": "Genericname" + }, + "Hidden": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "title": "Hidden" + }, + "Implements": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "title": "Implements" + }, + "Keywords": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "title": "Keywords" + }, + "MimeType": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "title": "Mimetype" + }, + "NoDisplay": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "title": "Nodisplay" + }, + "NotShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Notshowin" + }, + "OnlyShowIn": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "type": "array" + }, + { + "pattern": "^.+;$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "title": "Onlyshowin" + }, + "PrefersNonDefaultGPU": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "title": "Prefersnondefaultgpu" + }, + "SingleMainWindow": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "title": "Singlemainwindow" + }, + "StartupNotify": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupnotify" + }, + "StartupWMClass": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "title": "Startupwmclass" + }, + "TryExec": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "title": "Tryexec" + }, + "glob_patterns": { + "anyOf": [ + { + "additionalProperties": { + "pattern": ".*\\*.*", + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "title": "Glob Patterns" + } + }, + "title": "Linux", + "type": "object" + }, + "MacOS": { + "additionalProperties": false, + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "CFBundleDisplayName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "title": "Cfbundledisplayname" + }, + "CFBundleIdentifier": { + "anyOf": [ + { + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundleidentifier" + }, + "CFBundleName": { + "anyOf": [ + { + "maxLength": 16, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "title": "Cfbundlename" + }, + "CFBundleSpokenName": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "title": "Cfbundlespokenname" + }, + "CFBundleVersion": { + "anyOf": [ + { + "pattern": "^\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "title": "Cfbundleversion" + }, + "CFBundleURLTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleURLTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "markdownDescription": "URL types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "title": "Cfbundleurltypes" + }, + "CFBundleDocumentTypes": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/CFBundleDocumentTypesModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Document types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "markdownDescription": "Document types supported by this app. Requires macOS 10.14.4 or above. Refer to `event_handler` if your application does not have support for Apple Events handling.", + "title": "Cfbundledocumenttypes" + }, + "LSApplicationCategoryType": { + "anyOf": [ + { + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "title": "Lsapplicationcategorytype" + }, + "LSBackgroundOnly": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "title": "Lsbackgroundonly" + }, + "LSEnvironment": { + "anyOf": [ + { + "additionalProperties": { + "type": "string" + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "title": "Lsenvironment" + }, + "LSMinimumSystemVersion": { + "anyOf": [ + { + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "title": "Lsminimumsystemversion" + }, + "LSMultipleInstancesProhibited": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "title": "Lsmultipleinstancesprohibited" + }, + "LSRequiresNativeExecution": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "title": "Lsrequiresnativeexecution" + }, + "NSAudioCaptureUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to capture system audio.", + "markdownDescription": "A message describing why an app is requesting access to capture system audio.", + "title": "Nsaudiocaptureusagedescription" + }, + "NSCameraUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's camera.", + "markdownDescription": "A message describing why an app is requesting access to the device's camera.", + "title": "Nscamerausagedescription" + }, + "NSMainCameraUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's main camera.", + "markdownDescription": "A message describing why an app is requesting access to the device's main camera.", + "title": "Nsmaincamerausagedescription" + }, + "NSMicrophoneUsageDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A message describing why an app is requesting access to the device's microphone.", + "markdownDescription": "A message describing why an app is requesting access to the device's microphone.", + "title": "Nsmicrophoneusagedescription" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "title": "Nssupportsautomaticgraphicsswitching" + }, + "UTExportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "title": "Utexportedtypedeclarations" + }, + "UTImportedTypeDeclarations": { + "anyOf": [ + { + "items": { + "$ref": "#/$defs/UTTypeDeclarationModel" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "title": "Utimportedtypedeclarations" + }, + "entitlements": { + "anyOf": [ + { + "items": { + "pattern": "[a-z0-9\\.\\-]+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "title": "Entitlements" + }, + "info_plist_extra": { + "anyOf": [ + { + "additionalProperties": true, + "propertyNames": { + "minLength": 1 + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Set of extra properties for the Info.plist file. These properties are not validated by `menuinst.`", + "markdownDescription": "Set of extra properties for the Info.plist file. These properties are not validated by `menuinst.`", + "title": "Info Plist Extra" + }, + "link_in_bundle": { + "anyOf": [ + { + "additionalProperties": { + "pattern": "^[^/]+.*", + "type": "string" + }, + "propertyNames": { + "minLength": 1 + }, + "type": "object" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "title": "Link In Bundle" + }, + "event_handler": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above. Using this key will inject a custom Swift launcher in the `.app` bundle to listen to Apple Events and forward them to your application. If your app is already handling Apple Events (e.g. via Qt's `QFileOpenEvent`), you do not need this.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above. Using this key will inject a custom Swift launcher in the `.app` bundle to listen to Apple Events and forward them to your application. If your app is already handling Apple Events (e.g. via Qt's `QFileOpenEvent`), you do not need this.", + "title": "Event Handler" + } + }, + "title": "MacOS", + "type": "object" + }, + "MenuItem": { + "additionalProperties": false, + "description": "Instructions to create a menu item across operating systems.", + "markdownDescription": "Instructions to create a menu item across operating systems.", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + } + ], + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description", + "type": "string" + }, + "command": { + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "items": { + "type": "string" + }, + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "title": "Command", + "type": "array" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "platforms": { + "$ref": "#/$defs/Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform." + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "title": "MenuItem", + "type": "object" + }, + "MenuItemNameDict": { + "additionalProperties": false, + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "properties": { + "target_environment_is_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "title": "Target Environment Is Base" + }, + "target_environment_is_not_base": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "title": "Target Environment Is Not Base" + } + }, + "title": "MenuItemNameDict", + "type": "object" + }, + "Platforms": { + "additionalProperties": false, + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "properties": { + "linux": { + "anyOf": [ + { + "$ref": "#/$defs/Linux" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details." + }, + "osx": { + "anyOf": [ + { + "$ref": "#/$defs/MacOS" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details." + }, + "win": { + "anyOf": [ + { + "$ref": "#/$defs/Windows" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details." + } + }, + "title": "Platforms", + "type": "object" + }, + "UTTypeDeclarationModel": { + "additionalProperties": false, + "properties": { + "UTTypeConformsTo": { + "description": "The Uniform Type Identifier types that this type conforms to.", + "items": { + "type": "string" + }, + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "title": "Uttypeconformsto", + "type": "array" + }, + "UTTypeDescription": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "title": "Uttypedescription" + }, + "UTTypeIconFile": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "title": "Uttypeiconfile" + }, + "UTTypeIdentifier": { + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "title": "Uttypeidentifier", + "type": "string" + }, + "UTTypeReferenceURL": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "title": "Uttypereferenceurl" + }, + "UTTypeTagSpecification": { + "additionalProperties": { + "items": { + "type": "string" + }, + "type": "array" + }, + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "title": "Uttypetagspecification", + "type": "object" + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "title": "UTTypeDeclarationModel", + "type": "object" + }, + "Windows": { + "additionalProperties": false, + "description": "Windows-specific instructions. You can override global keys here if needed", + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed", + "properties": { + "name": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "$ref": "#/$defs/MenuItemNameDict" + }, + { + "type": "null" + } + ], + "default": null, + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "title": "Name" + }, + "description": { + "anyOf": [ + { + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "title": "Description" + }, + "icon": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "title": "Icon" + }, + "command": { + "anyOf": [ + { + "items": { + "type": "string" + }, + "minItems": 1, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "title": "Command" + }, + "working_dir": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "title": "Working Dir" + }, + "precommand": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "title": "Precommand" + }, + "precreate": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "title": "Precreate" + }, + "activate": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "title": "Activate" + }, + "terminal": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "title": "Terminal" + }, + "desktop": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": true, + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "title": "Desktop" + }, + "quicklaunch": { + "anyOf": [ + { + "type": "boolean" + }, + { + "type": "null" + } + ], + "default": false, + "deprecated": true, + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "title": "Quicklaunch" + }, + "terminal_profile": { + "anyOf": [ + { + "minLength": 1, + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "title": "Terminal Profile" + }, + "url_protocols": { + "anyOf": [ + { + "items": { + "pattern": "\\S+", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "title": "Url Protocols" + }, + "file_extensions": { + "anyOf": [ + { + "items": { + "pattern": "\\.\\S*", + "type": "string" + }, + "type": "array" + }, + { + "type": "null" + } + ], + "default": null, + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "title": "File Extensions" + }, + "app_user_model_id": { + "anyOf": [ + { + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + }, + { + "type": "null" + } + ], + "default": null, + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "title": "App User Model Id" + } + }, + "title": "Windows", + "type": "object" + } + }, + "$id": "https://schemas.conda.org/menuinst-1-1-3.schema.json", + "$schema": "http://json-schema.org/draft-07/schema#", + "$version": "1-1-3", + "additionalProperties": false, + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "properties": { + "$id": { + "default": "https://schemas.conda.org/menuinst-1-1-3.schema.json", + "deprecated": true, + "description": "DEPRECATED. Use ``$schema``.", + "markdownDescription": "DEPRECATED. Use ``$schema``.", + "minLength": 1, + "title": "$Id", + "type": "string" + }, + "$schema": { + "default": "https://schemas.conda.org/menuinst-1-1-3.schema.json", + "description": "Version of the menuinst schema to validate against.", + "markdownDescription": "Version of the menuinst schema to validate against.", + "minLength": 1, + "title": "$Schema", + "type": "string" + }, + "menu_name": { + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "title": "Menu Name", + "type": "string" + }, + "menu_items": { + "description": "List of menu entries to create across main desktop systems.", + "items": { + "$ref": "#/$defs/MenuItem" + }, + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "title": "Menu Items", + "type": "array" + } + }, + "required": [ + "menu_name", + "menu_items" + ], + "title": "MenuInstSchema", + "type": "object" +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.default.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.default.json new file mode 100644 index 0000000000000000000000000000000000000000..489958b1556fd2c556625563ebdc1086f8dc9575 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.default.json @@ -0,0 +1,69 @@ +{ + "id_": "https://schemas.conda.io/menuinst-1.schema.json", + "schema_": "https://json-schema.org/draft-07/schema", + "menu_name": "REQUIRED", + "menu_items": [ + { + "name": "REQUIRED", + "description": "REQUIRED", + "command": [ + "REQUIRED" + ], + "icon": null, + "precommand": null, + "precreate": null, + "working_dir": null, + "activate": true, + "terminal": false, + "platforms": { + "linux": { + "Categories": null, + "DBusActivatable": null, + "GenericName": null, + "Hidden": null, + "Implements": null, + "Keywords": null, + "MimeType": null, + "NoDisplay": null, + "NotShowIn": null, + "OnlyShowIn": null, + "PrefersNonDefaultGPU": null, + "SingleMainWindow": null, + "StartupNotify": null, + "StartupWMClass": null, + "TryExec": null, + "glob_patterns": null + }, + "osx": { + "CFBundleDisplayName": null, + "CFBundleIdentifier": null, + "CFBundleName": null, + "CFBundleSpokenName": null, + "CFBundleVersion": null, + "CFBundleURLTypes": null, + "CFBundleDocumentTypes": null, + "LSApplicationCategoryType": null, + "LSBackgroundOnly": null, + "LSEnvironment": null, + "LSMinimumSystemVersion": null, + "LSMultipleInstancesProhibited": null, + "LSRequiresNativeExecution": null, + "NSSupportsAutomaticGraphicsSwitching": null, + "UTExportedTypeDeclarations": null, + "UTImportedTypeDeclarations": null, + "entitlements": null, + "link_in_bundle": null, + "event_handler": null + }, + "win": { + "desktop": true, + "quicklaunch": false, + "terminal_profile": null, + "url_protocols": null, + "file_extensions": null, + "app_user_model_id": null + } + } + } + ] +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.schema.json b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.schema.json new file mode 100644 index 0000000000000000000000000000000000000000..8491ce9f6938c2ecd69036ad32b5b0caa7fb4efc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/menuinst.schema.json @@ -0,0 +1,967 @@ +{ + "title": "MenuInstSchema", + "description": "Metadata required to create menu items across operating systems with `menuinst`.", + "type": "object", + "properties": { + "$id": { + "title": "$Id", + "description": "Version of the menuinst schema.", + "markdownDescription": "Version of the menuinst schema.", + "enum": [ + "https://schemas.conda.io/menuinst-1.schema.json" + ], + "type": "string" + }, + "$schema": { + "title": "$Schema", + "description": "Standard of the JSON schema we adhere to.", + "markdownDescription": "Standard of the JSON schema we adhere to.", + "enum": [ + "https://json-schema.org/draft-07/schema" + ], + "type": "string" + }, + "menu_name": { + "title": "Menu Name", + "description": "Name for the category containing the items specified in `menu_items`.", + "markdownDescription": "Name for the category containing the items specified in `menu_items`.", + "minLength": 1, + "type": "string" + }, + "menu_items": { + "title": "Menu Items", + "description": "List of menu entries to create across main desktop systems.", + "markdownDescription": "List of menu entries to create across main desktop systems.", + "minItems": 1, + "type": "array", + "items": { + "$ref": "#/definitions/MenuItem" + } + } + }, + "required": [ + "$id", + "$schema", + "menu_name", + "menu_items" + ], + "additionalProperties": false, + "markdownDescription": "Metadata required to create menu items across operating systems with `menuinst`.", + "definitions": { + "MenuItemNameDict": { + "title": "MenuItemNameDict", + "description": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment.", + "type": "object", + "properties": { + "target_environment_is_base": { + "title": "Target Environment Is Base", + "description": "Name when target environment is the base environment.", + "markdownDescription": "Name when target environment is the base environment.", + "minLength": 1, + "type": "string" + }, + "target_environment_is_not_base": { + "title": "Target Environment Is Not Base", + "description": "Name when target environment is not the base environment.", + "markdownDescription": "Name when target environment is not the base environment.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Variable menu item name. Use this dictionary if the menu item name depends on installation parameters such as the target environment." + }, + "Linux": { + "title": "Linux", + "description": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "Categories": { + "title": "Categories", + "description": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "markdownDescription": "Categories in which the entry should be shown in a menu. See 'Registered categories' in the [Menu Spec]( http://www.freedesktop.org/Standards/menu-spec).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "DBusActivatable": { + "title": "Dbusactivatable", + "description": "A boolean value specifying if D-Bus activation is supported for this application.", + "markdownDescription": "A boolean value specifying if D-Bus activation is supported for this application.", + "type": "boolean" + }, + "GenericName": { + "title": "Genericname", + "description": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "markdownDescription": "Generic name of the application; e.g. if the name is 'conda', this would be 'Package Manager'.", + "type": "string" + }, + "Hidden": { + "title": "Hidden", + "description": "Disable shortcut, signaling a missing resource.", + "markdownDescription": "Disable shortcut, signaling a missing resource.", + "type": "boolean" + }, + "Implements": { + "title": "Implements", + "description": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "markdownDescription": "List of supported interfaces. See 'Interfaces' in [Desktop Entry Spec]( https://specifications.freedesktop.org/desktop-entry-spec/latest/interfaces.html).", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "Keywords": { + "title": "Keywords", + "description": "Additional terms to describe this shortcut to aid in searching.", + "markdownDescription": "Additional terms to describe this shortcut to aid in searching.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "MimeType": { + "title": "Mimetype", + "description": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "markdownDescription": "The MIME type(s) supported by this application. Note this includes file types and URL protocols. For URL protocols, use `x-scheme-handler/your-protocol-here`. For example, if you want to register `menuinst:`, you would include `x-scheme-handler/menuinst`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "NoDisplay": { + "title": "Nodisplay", + "description": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "markdownDescription": "Do not show this item in the menu. Useful to associate MIME types and other registrations, without having an actual clickable item. Not to be confused with 'Hidden'.", + "type": "boolean" + }, + "NotShowIn": { + "title": "Notshowin", + "description": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should NOT display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "OnlyShowIn": { + "title": "Onlyshowin", + "description": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "markdownDescription": "Desktop environments that should display this item. It'll check against `$XDG_CURRENT_DESKTOP`.", + "anyOf": [ + { + "type": "array", + "items": { + "type": "string" + } + }, + { + "type": "string", + "pattern": "^.+;$" + } + ] + }, + "PrefersNonDefaultGPU": { + "title": "Prefersnondefaultgpu", + "description": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "markdownDescription": "Hint that the app prefers to be run on a more powerful discrete GPU if available.", + "type": "boolean" + }, + "SingleMainWindow": { + "title": "Singlemainwindow", + "description": "Do not show the 'New Window' option in the app's context menu.", + "markdownDescription": "Do not show the 'New Window' option in the app's context menu.", + "type": "boolean" + }, + "StartupNotify": { + "title": "Startupnotify", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "boolean" + }, + "StartupWMClass": { + "title": "Startupwmclass", + "description": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "markdownDescription": "Advanced. See [Startup Notification spec]( https://www.freedesktop.org/wiki/Specifications/startup-notification-spec/).", + "type": "string" + }, + "TryExec": { + "title": "Tryexec", + "description": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "markdownDescription": "Filename or absolute path to an executable file on disk used to determine if the program is actually installed and can be run. If the test fails, the shortcut might be ignored / hidden.", + "type": "string" + }, + "glob_patterns": { + "title": "Glob Patterns", + "description": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "markdownDescription": "Map of custom MIME types to their corresponding glob patterns (e.g. `*.txt`). Only needed if you define custom MIME types in `MimeType`.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": ".*\\*.*" + } + } + }, + "additionalProperties": false, + "markdownDescription": "Linux-specific instructions.\n\nCheck the [Desktop entry specification]( https://specifications.freedesktop.org/desktop-entry-spec/latest/recognized-keys.html) for more details." + }, + "CFBundleURLTypesModel": { + "title": "CFBundleURLTypesModel", + "description": "Describes a URL scheme associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the URL.", + "markdownDescription": "This key specifies the app's role with respect to the URL.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "CFBundleURLSchemes": { + "title": "Cfbundleurlschemes", + "description": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "markdownDescription": "URL schemes / protocols handled by this type (e.g. 'mailto').", + "type": "array", + "items": { + "type": "string" + } + }, + "CFBundleURLName": { + "title": "Cfbundleurlname", + "description": "Abstract name for this URL type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this URL type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleURLIconFile": { + "title": "Cfbundleurliconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + } + }, + "required": [ + "CFBundleURLSchemes" + ], + "additionalProperties": false, + "markdownDescription": "Describes a URL scheme associated with the app." + }, + "CFBundleDocumentTypesModel": { + "title": "CFBundleDocumentTypesModel", + "description": "Describes a document type associated with the app.", + "type": "object", + "properties": { + "CFBundleTypeIconFile": { + "title": "Cfbundletypeiconfile", + "description": "Name of the icon image file (minus the .icns extension).", + "markdownDescription": "Name of the icon image file (minus the .icns extension).", + "type": "string" + }, + "CFBundleTypeName": { + "title": "Cfbundletypename", + "description": "Abstract name for this document type. Uniqueness recommended.", + "markdownDescription": "Abstract name for this document type. Uniqueness recommended.", + "type": "string" + }, + "CFBundleTypeRole": { + "title": "Cfbundletyperole", + "description": "This key specifies the app's role with respect to the type.", + "markdownDescription": "This key specifies the app's role with respect to the type.", + "enum": [ + "Editor", + "Viewer", + "Shell", + "None" + ], + "type": "string" + }, + "LSItemContentTypes": { + "title": "Lsitemcontenttypes", + "description": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "markdownDescription": "List of UTI strings defining a supported file type; e.g. for PNG files, use 'public.png'. See [UTI Reference]( https://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/UTIRef/Articles/System-DeclaredUniformTypeIdentifiers.html) for more info about the system-defined UTIs. Custom UTIs can be defined via 'UTExportedTypeDeclarations'. UTIs defined by other apps (not the system) need to be imported via 'UTImportedTypeDeclarations'.\n\nSee [Fun with UTIs](https://www.cocoanetics.com/2012/09/fun-with-uti/) for more info.", + "type": "array", + "items": { + "type": "string" + } + }, + "LSHandlerRank": { + "title": "Lshandlerrank", + "description": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "markdownDescription": "Determines how Launch Services ranks this app among the apps that declare themselves editors or viewers of files of this type.", + "enum": [ + "Owner", + "Default", + "Alternate" + ], + "type": "string" + } + }, + "required": [ + "CFBundleTypeName", + "LSItemContentTypes", + "LSHandlerRank" + ], + "additionalProperties": false, + "markdownDescription": "Describes a document type associated with the app." + }, + "UTTypeDeclarationModel": { + "title": "UTTypeDeclarationModel", + "type": "object", + "properties": { + "UTTypeConformsTo": { + "title": "Uttypeconformsto", + "description": "The Uniform Type Identifier types that this type conforms to.", + "markdownDescription": "The Uniform Type Identifier types that this type conforms to.", + "type": "array", + "items": { + "type": "string" + } + }, + "UTTypeDescription": { + "title": "Uttypedescription", + "description": "A description for this type.", + "markdownDescription": "A description for this type.", + "type": "string" + }, + "UTTypeIconFile": { + "title": "Uttypeiconfile", + "description": "The bundle icon resource to associate with this type.", + "markdownDescription": "The bundle icon resource to associate with this type.", + "type": "string" + }, + "UTTypeIdentifier": { + "title": "Uttypeidentifier", + "description": "The Uniform Type Identifier to assign to this type.", + "markdownDescription": "The Uniform Type Identifier to assign to this type.", + "type": "string" + }, + "UTTypeReferenceURL": { + "title": "Uttypereferenceurl", + "description": "The webpage for a reference document that describes this type.", + "markdownDescription": "The webpage for a reference document that describes this type.", + "type": "string" + }, + "UTTypeTagSpecification": { + "title": "Uttypetagspecification", + "description": "A dictionary defining one or more equivalent type identifiers.", + "markdownDescription": "A dictionary defining one or more equivalent type identifiers.", + "type": "object", + "additionalProperties": { + "type": "array", + "items": { + "type": "string" + } + } + } + }, + "required": [ + "UTTypeConformsTo", + "UTTypeIdentifier", + "UTTypeTagSpecification" + ], + "additionalProperties": false + }, + "MacOS": { + "title": "MacOS", + "description": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "CFBundleDisplayName": { + "title": "Cfbundledisplayname", + "description": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "markdownDescription": "Display name of the bundle, visible to users and used by Siri. If not provided, 'menuinst' will use the 'name' field.", + "type": "string" + }, + "CFBundleIdentifier": { + "title": "Cfbundleidentifier", + "description": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Unique identifier for the shortcut. Typically uses a reverse-DNS format. If not provided, 'menuinst' will generate one from the 'name' field.", + "pattern": "^[A-z0-9\\-\\.]+$", + "type": "string" + }, + "CFBundleName": { + "title": "Cfbundlename", + "description": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "markdownDescription": "Short name of the bundle. May be used if `CFBundleDisplayName` is absent. If not provided, 'menuinst' will generate one from the 'name' field.", + "maxLength": 16, + "type": "string" + }, + "CFBundleSpokenName": { + "title": "Cfbundlespokenname", + "description": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "markdownDescription": "Suitable replacement for text-to-speech operations on the app. For example, 'my app one two three' instead of 'MyApp123'.", + "type": "string" + }, + "CFBundleVersion": { + "title": "Cfbundleversion", + "description": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "markdownDescription": "Build version number for the bundle. In the context of 'menuinst' this can be used to signal a new version of the menu item for the same application version.", + "pattern": "^\\S+$", + "type": "string" + }, + "CFBundleURLTypes": { + "title": "Cfbundleurltypes", + "description": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "URL types supported by this app. Requires setting `event_handler` too. Note this feature requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleURLTypesModel" + } + }, + "CFBundleDocumentTypes": { + "title": "Cfbundledocumenttypes", + "description": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "markdownDescription": "Document types supported by this app. Requires setting `event_handler` too. Requires macOS 10.14.4 or above.", + "type": "array", + "items": { + "$ref": "#/definitions/CFBundleDocumentTypesModel" + } + }, + "LSApplicationCategoryType": { + "title": "Lsapplicationcategorytype", + "description": "The App Store uses this string to determine the appropriate categorization.", + "markdownDescription": "The App Store uses this string to determine the appropriate categorization.", + "pattern": "^public\\.app-category\\.\\S+$", + "type": "string" + }, + "LSBackgroundOnly": { + "title": "Lsbackgroundonly", + "description": "Specifies whether this app runs only in the background.", + "markdownDescription": "Specifies whether this app runs only in the background.", + "type": "boolean" + }, + "LSEnvironment": { + "title": "Lsenvironment", + "description": "List of key-value pairs used to define environment variables.", + "markdownDescription": "List of key-value pairs used to define environment variables.", + "type": "object", + "additionalProperties": { + "type": "string" + } + }, + "LSMinimumSystemVersion": { + "title": "Lsminimumsystemversion", + "description": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "markdownDescription": "Minimum version of macOS required for this app to run, as `x.y.z`. For example, for macOS v10.4 and later, use `10.4.0`.", + "pattern": "^\\d+\\.\\d+\\.\\d+$", + "type": "string" + }, + "LSMultipleInstancesProhibited": { + "title": "Lsmultipleinstancesprohibited", + "description": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "markdownDescription": "Whether an app is prohibited from running simultaneously in multiple user sessions.", + "type": "boolean" + }, + "LSRequiresNativeExecution": { + "title": "Lsrequiresnativeexecution", + "description": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "markdownDescription": "If true, prevent a universal binary from being run under Rosetta emulation on an Intel-based Mac.", + "type": "boolean" + }, + "NSSupportsAutomaticGraphicsSwitching": { + "title": "Nssupportsautomaticgraphicsswitching", + "description": "If true, allows an OpenGL app to utilize the integrated GPU.", + "markdownDescription": "If true, allows an OpenGL app to utilize the integrated GPU.", + "type": "boolean" + }, + "UTExportedTypeDeclarations": { + "title": "Utexportedtypedeclarations", + "description": "The uniform type identifiers owned and exported by the app.", + "markdownDescription": "The uniform type identifiers owned and exported by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "UTImportedTypeDeclarations": { + "title": "Utimportedtypedeclarations", + "description": "The uniform type identifiers inherently supported, but not owned, by the app.", + "markdownDescription": "The uniform type identifiers inherently supported, but not owned, by the app.", + "type": "array", + "items": { + "$ref": "#/definitions/UTTypeDeclarationModel" + } + }, + "entitlements": { + "title": "Entitlements", + "description": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "markdownDescription": "List of permissions to request for the launched application. See [the entitlements docs]( https://developer.apple.com/documentation/bundleresources/entitlements) for a full list of possible values.", + "type": "array", + "items": { + "type": "string", + "pattern": "[a-z0-9\\.\\-]+" + } + }, + "link_in_bundle": { + "title": "Link In Bundle", + "description": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "markdownDescription": "Paths that should be symlinked into the shortcut app bundle. It takes a mapping of source to destination paths. Destination paths must be relative. Placeholder `{{ MENU_ITEM_LOCATION }}` can be useful.", + "type": "object", + "additionalProperties": { + "type": "string", + "pattern": "^(?!\\/)(?!\\.\\./).*" + } + }, + "event_handler": { + "title": "Event Handler", + "description": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "markdownDescription": "Required shell script logic to handle opened URL payloads. Note this feature requires macOS 10.14.4 or above.", + "minLength": 1, + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Mac-specific instructions. Check these URLs for more info:\n\n- `CF*` keys: see [Core Foundation Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html) - `LS*` keys: see [Launch Services Keys](https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/LaunchServicesKeys.html) - `entitlements`: see [Entitlements documentation](https://developer.apple.com/documentation/bundleresources/entitlements)" + }, + "Windows": { + "title": "Windows", + "description": "Windows-specific instructions. You can override global keys here if needed", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "desktop": { + "title": "Desktop", + "description": "Whether to create a desktop icon in addition to the Start Menu item.", + "default": true, + "markdownDescription": "Whether to create a desktop icon in addition to the Start Menu item.", + "type": "boolean" + }, + "quicklaunch": { + "title": "Quicklaunch", + "description": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "default": false, + "deprecated": true, + "markdownDescription": "DEPRECATED. Whether to create a quick launch icon in addition to the Start Menu item.", + "type": "boolean" + }, + "terminal_profile": { + "title": "Terminal Profile", + "description": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "markdownDescription": "Name of the Windows Terminal profile to create. This name must be unique across multiple installations because menuinst will overwrite Terminal profiles with the same name.", + "minLength": 1, + "type": "string" + }, + "url_protocols": { + "title": "Url Protocols", + "description": "URL protocols that will be associated with this program.", + "markdownDescription": "URL protocols that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\S+" + } + }, + "file_extensions": { + "title": "File Extensions", + "description": "File extensions that will be associated with this program.", + "markdownDescription": "File extensions that will be associated with this program.", + "type": "array", + "items": { + "type": "string", + "pattern": "\\.\\S*" + } + }, + "app_user_model_id": { + "title": "App User Model Id", + "description": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "markdownDescription": "Identifier used in Windows 7 and above to associate processes, files and windows with a particular application. If your shortcut produces duplicated icons, you need to define this field. If not set, it will default to `Menuinst.`.\n\nSee [AppUserModelID docs]( https://learn.microsoft.com/en-us/windows/win32/shell/appids#how-to-form-an-application-defined-appusermodelid) for more information on the required string format.", + "maxLength": 128, + "pattern": "\\S+\\.\\S+", + "type": "string" + } + }, + "additionalProperties": false, + "markdownDescription": "Windows-specific instructions. You can override global keys here if needed" + }, + "Platforms": { + "title": "Platforms", + "description": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed.", + "type": "object", + "properties": { + "linux": { + "title": "Linux", + "description": "Options for Linux. See `Linux` model for details.", + "markdownDescription": "Options for Linux. See `Linux` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Linux" + } + ] + }, + "osx": { + "title": "Osx", + "description": "Options for macOS. See `MacOS` model for details.", + "markdownDescription": "Options for macOS. See `MacOS` model for details.", + "allOf": [ + { + "$ref": "#/definitions/MacOS" + } + ] + }, + "win": { + "title": "Win", + "description": "Options for Windows. See `Windows` model for details.", + "markdownDescription": "Options for Windows. See `Windows` model for details.", + "allOf": [ + { + "$ref": "#/definitions/Windows" + } + ] + } + }, + "additionalProperties": false, + "markdownDescription": "Platform specific options.\n\nNote each of these fields supports the same keys as the top-level `MenuItem` (sans `platforms` itself), in case overrides are needed." + }, + "MenuItem": { + "title": "MenuItem", + "description": "Instructions to create a menu item across operating systems.", + "type": "object", + "properties": { + "name": { + "title": "Name", + "description": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "markdownDescription": "The name of the menu item. Can be a dictionary if the name depends on installation parameters. See `MenuItemNameDict` for details.", + "anyOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "$ref": "#/definitions/MenuItemNameDict" + } + ] + }, + "description": { + "title": "Description", + "description": "A longer description of the menu item. Shown on popup messages.", + "markdownDescription": "A longer description of the menu item. Shown on popup messages.", + "type": "string" + }, + "command": { + "title": "Command", + "description": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "markdownDescription": "Command to run with the menu item, expressed as a list of strings where each string is an argument.", + "minItems": 1, + "type": "array", + "items": { + "type": "string" + } + }, + "icon": { + "title": "Icon", + "description": "Path to the file representing or containing the icon.", + "markdownDescription": "Path to the file representing or containing the icon.", + "minLength": 1, + "type": "string" + }, + "precommand": { + "title": "Precommand", + "description": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the command is run. Runs before the environment is activated, if that applies.", + "minLength": 1, + "type": "string" + }, + "precreate": { + "title": "Precreate", + "description": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "markdownDescription": "(Simple, preferrably single-line) logic to run before the shortcut is created.", + "minLength": 1, + "type": "string" + }, + "working_dir": { + "title": "Working Dir", + "description": "Working directory for the running process. Defaults to user directory on each platform.", + "markdownDescription": "Working directory for the running process. Defaults to user directory on each platform.", + "minLength": 1, + "type": "string" + }, + "activate": { + "title": "Activate", + "description": "Whether to activate the target environment before running `command`.", + "default": true, + "markdownDescription": "Whether to activate the target environment before running `command`.", + "type": "boolean" + }, + "terminal": { + "title": "Terminal", + "description": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "default": false, + "markdownDescription": "Whether run the program in a terminal/console or not. On Windows, it only has an effect if `activate` is true. On MacOS, the application will ignore command-line arguments.", + "type": "boolean" + }, + "platforms": { + "title": "Platforms", + "description": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "markdownDescription": "Platform-specific options. Presence of a platform field enables menu items in that platform.", + "allOf": [ + { + "$ref": "#/definitions/Platforms" + } + ] + } + }, + "required": [ + "name", + "description", + "command", + "platforms" + ], + "additionalProperties": false, + "markdownDescription": "Instructions to create a menu item across operating systems." + } + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_arm64 b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_arm64 new file mode 100644 index 0000000000000000000000000000000000000000..818c5fc103e418e6c7157274945fd2c90f5b6847 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_arm64 differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_x86_64 b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_x86_64 new file mode 100644 index 0000000000000000000000000000000000000000..ca03454c6b271aa12dd8c46f352f9e90900159b3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/data/osx_launcher_x86_64 differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__init__.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..5282c8545551279c47c4efff0ab3f0b73d4e2435 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__init__.py @@ -0,0 +1,27 @@ +import sys +from typing import Tuple + +from .base import Menu as BaseMenu +from .base import MenuItem as BaseMenuItem + + +def menu_api_for_platform(platform: str = sys.platform) -> Tuple[BaseMenu, BaseMenuItem]: + if platform == "win32": + from .win import WindowsMenu as Menu + from .win import WindowsMenuItem as MenuItem + + elif platform == "darwin": + from .osx import MacOSMenu as Menu + from .osx import MacOSMenuItem as MenuItem + + elif platform.startswith("linux"): + from .linux import LinuxMenu as Menu + from .linux import LinuxMenuItem as MenuItem + + else: + raise ValueError(f"platform {platform} is not supported") + + return Menu, MenuItem + + +Menu, MenuItem = menu_api_for_platform() diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4ec56933a8188767f38930fe2e18fda05ec4690c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4632c508442b93ad8009fc5e15bbc4889a50ffe9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/linux.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/linux.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..25a27bf9743d223899022adaf8ca34116473f395 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/linux.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/osx.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/osx.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dda3fee3e4a3dab838b5b1b8a40b3caed8c97e74 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/osx.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/win.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/win.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bdb183f671c888c342b972c11fe22ff891e9d88e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/__pycache__/win.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/base.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/base.py new file mode 100644 index 0000000000000000000000000000000000000000..0e268b5e898de66cb836d5ded8b494ae7e15b481 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/base.py @@ -0,0 +1,277 @@ +""" """ + +from __future__ import annotations + +import json +import os +import sys +from copy import deepcopy +from logging import getLogger +from pathlib import Path +from subprocess import check_output +from tempfile import NamedTemporaryFile +from typing import Any, Iterable, Mapping + +from ..utils import ( + DEFAULT_BASE_PREFIX, + DEFAULT_PREFIX, + _UserOrSystem, + data_path, + deep_update, + logged_run, + slugify, +) + +log = getLogger(__name__) +SCHEMA_VERSION = "1-1-3" + + +class Menu: + def __init__( + self, + name: str, + prefix: str = DEFAULT_PREFIX, + base_prefix: str = DEFAULT_BASE_PREFIX, + mode: _UserOrSystem = "user", + ): + assert mode in ("user", "system"), f"mode={mode} must be `user` or `system`" + self.mode = mode + self.name = name + self.prefix = Path(prefix) + self.base_prefix = Path(base_prefix) + + if self.prefix.samefile(self.base_prefix): + self.env_name = "base" + else: + self.env_name = self.prefix.name + + def create(self) -> tuple[os.PathLike]: + raise NotImplementedError + + def remove(self) -> tuple[os.PathLike]: + raise NotImplementedError + + def render(self, value: Any, slug: bool = False, extra: dict | None = None) -> Any: + if not hasattr(value, "replace"): + return value + if extra: + placeholders = {**self.placeholders, **extra} + else: + placeholders = self.placeholders + for placeholder, replacement in placeholders.items(): + value = value.replace("{{ " + placeholder + " }}", replacement) + if slug: + value = slugify(value) + return value + + @property + def placeholders(self) -> dict[str, str]: + """ + Additional placeholders added at runtime: + - MENU_ITEM_LOCATION -> *MenuItem().location + + Subclasses may extend this dictionary! + """ + return { + "BASE_PREFIX": str(self.base_prefix), + "DISTRIBUTION_NAME": self.base_prefix.name, + "BASE_PYTHON": str(self.base_prefix / "bin" / "python"), + "PREFIX": str(self.prefix), + "ENV_NAME": self.env_name, + "PYTHON": str(self.prefix / "bin" / "python"), + "MENU_DIR": str(self.prefix / "Menu"), + "BIN_DIR": str(self.prefix / "bin"), + "PY_VER": "N.A", + "HOME": os.path.expanduser("~"), + "ICON_EXT": "png", + } + + def _conda_exe_path_candidates(self) -> tuple[Path, ...]: + return ( + self.base_prefix / "_conda.exe", + self.base_prefix / "conda.exe", + Path(os.environ.get("CONDA_EXE", "/oops/a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "conda", + self.base_prefix / "bin" / "conda", + Path(os.environ.get("MAMBA_EXE", "/oops/a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "micromamba", + self.base_prefix / "bin" / "micromamba", + ) + + @property + def conda_exe(self) -> Path: + if sys.executable.endswith("conda.exe"): + # This is the case with `constructor` calls + return Path(sys.executable) + + for path in self._conda_exe_path_candidates(): + if path.is_file(): + return path + + return Path("conda") + + def _is_micromamba(self, exe: Path) -> bool: + if "micromamba" in exe.name: + return True + if exe.name in ("conda.exe", "_conda.exe"): + out = check_output([str(exe), "info"], universal_newlines=True) + return "micromamba version" in out + return False + + def _site_packages(self, prefix: Path | str | None = None) -> Path: + """ + Locate the python site-packages location on unix systems + """ + if os.name == "nt": + raise NotImplementedError + if prefix is None: + prefix = self.prefix + lib = Path(prefix) / "lib" + lib_python = next((p for p in lib.glob("python*") if p.is_dir()), lib / "pythonN.A") + return lib_python / "site-packages" + + def _paths(self) -> Iterable[os.PathLike]: + """ + This method should return the paths created by the menu + so they can be removed upon uninstallation + """ + raise NotImplementedError + + +class MenuItem: + def __init__(self, menu: Menu, metadata: Mapping[str, Any]): + self.menu = menu + self._data = self._initialize_on_defaults(metadata) + self.metadata = self._flatten_for_platform(self._data) + if isinstance(self.metadata["name"], dict): + if self.menu.prefix.samefile(self.menu.base_prefix): + name = self.metadata["name"].get("target_environment_is_base", "") + else: + name = self.metadata["name"].get("target_environment_is_not_base", "") + if not name: + raise ValueError("Cannot parse `name` from dictionary representation.") + self.metadata["name"] = name + + @property + def location(self) -> Path: + "Path to the main menu item artifact (file or directory, depends on the platform)" + raise NotImplementedError + + def create(self) -> Iterable[os.PathLike]: + raise NotImplementedError + + def remove(self) -> Iterable[os.PathLike]: + raise NotImplementedError + + @property + def placeholders(self) -> dict[str, str]: + return { + "MENU_ITEM_LOCATION": str(self.location), + } + + def render_key(self, key: str, slug: bool = False, extra: dict[str, str] | None = None) -> Any: + value = self.metadata.get(key) + return self.render(value, slug=slug, extra=extra) + + def render(self, value: Any, slug: bool = False, extra: dict[str, str] | None = None) -> Any: + if value in (None, True, False): + return value + kwargs = { + "slug": slug, + "extra": extra if extra is not None else self.placeholders, + } + if isinstance(value, str): + return self.menu.render(value, **kwargs) + if hasattr(value, "items"): + return {key: self.menu.render(value, **kwargs) for key, value in value.items()} + return [self.menu.render(item, **kwargs) for item in value] + + def _precreate(self): + """ + Logic to run before the shortcut files are created. + """ + if os.name == "nt": + raise NotImplementedError + + precreate_code = self.render_key("precreate") + if not precreate_code: + return + with NamedTemporaryFile(delete=False, mode="w") as tmp: + tmp.write(precreate_code) + if precreate_code.startswith("#!"): + os.chmod(tmp.name, 0o755) + cmd = [tmp.name] + else: + cmd = ["bash", tmp.name] + logged_run(cmd, check=True) + os.unlink(tmp.name) + + def _paths(self) -> Iterable[os.PathLike]: + """ + This method should return the paths created by the item + so they can be removed upon uninstallation + """ + raise NotImplementedError + + @staticmethod + def _initialize_on_defaults(data) -> Mapping[str, Any]: + with open(data_path(f"menuinst-{SCHEMA_VERSION}.default.json")) as f: + defaults = json.load(f)["menu_items"][0] + original = deepcopy(data.copy()) + data = deep_update(defaults, data) + # remove platforms that were not originally in 'data' + data["platforms"] = { + platform: value + for platform, value in data.get("platforms", {}).items() + if original.get("platforms", {}).get(platform) not in (None, False) + } + return data + + @staticmethod + def _flatten_for_platform( + data: Mapping[str, Any], platform: str = sys.platform + ) -> Mapping[str, Any]: + """ + Merge platform keys with global keys, overwriting if needed. + """ + flattened = deepcopy(data) + all_platforms = flattened.pop("platforms", {}) + this_platform = all_platforms.pop(platform_key(platform), None) + if this_platform: + for key, value in this_platform.items(): + if key not in flattened: + # bring missing keys, since they are platform specific + flattened[key] = value + elif value is not None: + # if the key was in global, it was not platform specific + # this is an override and we only do so if is not None + log.debug("Platform value %s=%s overrides global value", key, value) + flattened[key] = value + else: # restore + flattened["platforms"] = all_platforms + + # in the merged metadata, platforms becomes a list of str stating which + # platforms are enabled for this item + flattened["platforms"] = [ + key for key, value in data["platforms"].items() if value is not None + ] + return flattened + + def enabled_for_platform(self, platform: str = sys.platform) -> bool: + return self._data["platforms"].get(platform_key(platform)) is not None + + +def platform_key(platform: str = sys.platform) -> str: + if platform == "win32": + return "win" + if platform == "darwin": + return "osx" + if platform.startswith("linux"): + return "linux" + + raise ValueError(f"Platform {platform} is not supported") + + +menuitem_defaults = json.loads( + (Path(__file__).parents[1] / "data" / f"menuinst-{SCHEMA_VERSION}.default.json").read_text() +)["menu_items"][0] diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/linux.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/linux.py new file mode 100644 index 0000000000000000000000000000000000000000..3fcfe43f178eb78a87ee9c3b99cc3bc3ba767241 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/linux.py @@ -0,0 +1,423 @@ +""" """ + +from __future__ import annotations + +import os +import shlex +import shutil +import time +from configparser import ConfigParser +from logging import getLogger +from pathlib import Path +from subprocess import CalledProcessError +from tempfile import TemporaryDirectory +from typing import Iterable +from xml.etree import ElementTree + +from ..utils import UnixLex, add_xml_child, indent_xml_tree, logged_run, unlink +from .base import Menu, MenuItem, menuitem_defaults + +log = getLogger(__name__) + + +class LinuxMenu(Menu): + """ + Menus in Linux are governed by the freedesktop.org standards, + spec'd here https://specifications.freedesktop.org/menu-spec/menu-spec-latest.html + + menuinst will populate the relevant XML config and create a .directory entry + """ + + _system_config_directory = Path("/etc/xdg/") + _system_data_directory = Path("/usr/share") + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if self.mode == "system": + self.config_directory = self._system_config_directory + self.data_directory = self._system_data_directory + else: + self.config_directory = Path( + os.environ.get("XDG_CONFIG_HOME", "~/.config") + ).expanduser() + self.data_directory = Path( + os.environ.get("XDG_DATA_HOME", "~/.local/share") + ).expanduser() + + # XML Config paths + menu_fname = f"{os.environ.get('XDG_MENU_PREFIX', '')}applications.menu" + self.system_menu_config_location = self._system_config_directory / "menus" / menu_fname + self.menu_config_location = self.config_directory / "menus" / menu_fname + # .desktop / .directory paths + self.directory_entry_location = ( + self.data_directory + / "desktop-directories" + / f"{self.render(self.name, slug=True)}.directory" + ) + self.desktop_entries_location = self.data_directory / "applications" + + def create(self) -> tuple[os.PathLike]: + self._ensure_directories_exist() + path = self._write_directory_entry() + if self._is_valid_menu_file() and self._has_this_menu(): + return (path,) + self._ensure_menu_file() + self._add_this_menu() + return (path,) + + def remove(self) -> tuple[os.PathLike]: + if not Path(self.desktop_entries_location).exists(): + return tuple() + for fn in os.listdir(self.desktop_entries_location): + if fn.startswith(f"{self.render(self.name, slug=True)}_"): + # found one shortcut, so don't remove the name from menu + return tuple() + self._remove_this_menu() + if self.directory_entry_location.exists(): + unlink(self.directory_entry_location, missing_ok=True) + return (self.directory_entry_location,) + return tuple() + + @property + def placeholders(self) -> dict[str, str]: + placeholders = super().placeholders + placeholders["SP_DIR"] = str(self._site_packages()) + return placeholders + + def _ensure_directories_exist(self): + paths = [ + self.config_directory / "menus", + self.data_directory / "desktop-directories", + self.data_directory / "applications", + ] + for path in paths: + log.debug("Ensuring path %s exists", path) + path.mkdir(parents=True, exist_ok=True) + + # + # .directory stuff methods + # + + def _write_directory_entry(self) -> Path: + lines = [ + "[Desktop Entry]", + "Type=Directory", + "Encoding=UTF-8", + f"Name={self.render(self.name)}", + ] + log.debug("Writing directory entry at %s", self.directory_entry_location) + with open(self.directory_entry_location, "w") as f: + f.write("\n".join(lines)) + + return self.directory_entry_location + + # + # XML config stuff methods + # + + def _remove_this_menu(self): + if not Path(self.menu_config_location).exists(): + return + log.debug( + "Editing %s to remove %s config", self.menu_config_location, self.render(self.name) + ) + tree = ElementTree.parse(self.menu_config_location) + root = tree.getroot() + for elt in root.findall("Menu"): + if elt.find("Name").text == self.render(self.name): + root.remove(elt) + self._write_menu_file(tree) + + def _has_this_menu(self) -> bool: + root = ElementTree.parse(self.menu_config_location).getroot() + return any(e.text == self.render(self.name) for e in root.findall("Menu/Name")) + + def _add_this_menu(self): + log.debug("Editing %s to add %s config", self.menu_config_location, self.render(self.name)) + tree = ElementTree.parse(self.menu_config_location) + root = tree.getroot() + menu_elt = add_xml_child(root, "Menu") + add_xml_child(menu_elt, "Name", self.render(self.name)) + add_xml_child(menu_elt, "Directory", f"{self.render(self.name, slug=True)}.directory") + inc_elt = add_xml_child(menu_elt, "Include") + add_xml_child(inc_elt, "Category", self.render(self.name)) + self._write_menu_file(tree) + + def _is_valid_menu_file(self) -> bool: + try: + root = ElementTree.parse(self.menu_config_location).getroot() + return root is not None and root.tag == "Menu" + except Exception: + return False + + def _write_menu_file(self, tree: ElementTree.ElementTree): + log.debug("Writing %s", self.menu_config_location) + indent_xml_tree(tree.getroot()) # inplace! + with open(self.menu_config_location, "wb") as f: + f.write(b'\n') + tree.write(f) + f.write(b"\n") + + def _ensure_menu_file(self): + # ensure any existing version is a file + if self.menu_config_location.exists() and not self.menu_config_location.is_file(): + raise RuntimeError(f"Menu config location {self.menu_config_location} is not a file!") + # shutil.rmtree(self.menu_config_location) + + # ensure any existing file is actually a menu file + if self.menu_config_location.is_file(): + # make a backup of the menu file to be edited + cur_time = time.strftime("%Y-%m-%d_%Hh%Mm%S") + backup_menu_file = f"{self.menu_config_location}.{cur_time}" + shutil.copyfile(self.menu_config_location, backup_menu_file) + + if not self._is_valid_menu_file(): + os.remove(self.menu_config_location) + else: + self._new_menu_file() + + def _new_menu_file(self): + log.debug("Creating %s", self.menu_config_location) + with open(self.menu_config_location, "w") as f: + f.write("Applications") + if self.mode == "user": + f.write(f'{self.system_menu_config_location}') + f.write("\n") + + def _paths(self) -> tuple[Path]: + return (self.directory_entry_location,) + + +class LinuxMenuItem(MenuItem): + @property + def location(self) -> Path: + menu_prefix = self.render(self.menu.name, slug=True, extra={}) + # TODO: filename should conform to D-Bus well known name conventions + # https://specifications.freedesktop.org/desktop-entry-spec/latest/ar01s02.html + filename = f"{menu_prefix}_{self.render_key('name', slug=True, extra={})}.desktop" + return self.menu.desktop_entries_location / filename + + def create(self) -> Iterable[os.PathLike]: + log.debug("Creating %s", self.location) + self._precreate() + self._write_desktop_file() + self._maybe_register_mime_types(register=True) + self._update_desktop_database() + return self._paths() + + def remove(self) -> Iterable[os.PathLike]: + paths = (path for path in self._paths() if Path(path).is_file()) + self._maybe_register_mime_types(register=False) + if paths: + for path in paths: + log.debug("Removing %s", path) + unlink(path) + self._update_desktop_database() + return paths + + def _update_desktop_database(self): + exe = shutil.which("update-desktop-database") + if exe: + logged_run( + [exe, str(self.menu.desktop_entries_location)], + check=False, + ) + + def _command(self) -> str: + parts = [] + precommand = self.render_key("precommand") + if precommand: + parts.append(precommand) + if self.metadata["activate"]: + conda_exe = self.menu.conda_exe + if self.menu._is_micromamba(conda_exe): + activate = "shell activate" + else: + activate = "shell.bash activate" + parts.append(f'eval "$("{conda_exe}" {activate} "{self.menu.prefix}")"') + parts.append(" ".join(UnixLex.quote_args(self.render_key("command")))) + return "bash -c " + shlex.quote(" && ".join(parts)) + + def _write_desktop_file(self): + if self.location.exists(): + log.warning("Overwriting existing file at %s.", self.location) + + lines = [ + "[Desktop Entry]", + "Type=Application", + "Encoding=UTF-8", + f"Name={self.render_key('name')}", + f"Exec={self._command()}", + f"Terminal={str(self.render_key('terminal')).lower()}", + ] + + icon = self.render_key("icon") + if icon: + lines.append(f"Icon={self.render_key('icon')}") + + description = self.render_key("description") + if description: + lines.append(f"Comment={self.render_key('description')}") + + working_dir = self.render_key("working_dir") + if working_dir: + Path(os.path.expandvars(working_dir)).mkdir(parents=True, exist_ok=True) + lines.append(f"Path={working_dir}") + + for key in menuitem_defaults["platforms"]["linux"]: + if key in (*menuitem_defaults, "glob_patterns"): + continue + value = self.render_key(key) + if value is None: + continue + if isinstance(value, bool): + value = str(value).lower() + elif isinstance(value, (list, tuple)): + value = ";".join(value) + ";" + lines.append(f"{key}={value}") + + with open(self.location, "w") as f: + f.write("\n".join(lines)) + f.write("\n") + + def _maybe_register_mime_types(self, register: bool = True): + mime_types = self.render_key("MimeType") + if not mime_types: + return + self._register_mime_types(mime_types, register=register) + + def _register_mime_types(self, mime_types: Iterable[str], register: bool = True): + glob_patterns = self.render_key("glob_patterns") or {} + for mime_type in mime_types: + glob_pattern = glob_patterns.get(mime_type) + if glob_pattern: + self._glob_pattern_for_mime_type(mime_type, glob_pattern, install=register) + + mimeapps = self.menu.config_directory / "mimeapps.list" + if register: + config = ConfigParser(default_section=None) + if mimeapps.is_file(): + config.read(mimeapps) + log.debug("Registering %s to %s...", mime_types, mimeapps) + if "Default Applications" not in config.sections(): + config.add_section("Default Applications") + if "Added Associations" not in config.sections(): + config.add_section("Added Associations") + defaults = config["Default Applications"] + added = config["Added Associations"] + for mime_type in mime_types: + if mime_type not in defaults: + # Do not override existing defaults + defaults[mime_type] = self.location.name + if mime_type in added and self.location.name not in added[mime_type]: + added[mime_type] = f"{added[mime_type]};{self.location.name}" + else: + added[mime_type] = self.location.name + with open(mimeapps, "w") as f: + config.write(f, space_around_delimiters=False) + elif mimeapps.is_file(): + # Remove entries + config = ConfigParser(default_section=None) + config.read(mimeapps) + log.debug("Deregistering %s from %s...", mime_types, mimeapps) + for section_name in "Default Applications", "Added Associations": + if section_name not in config.sections(): + continue + section = config[section_name] + for mimetype, desktop_files in section.items(): + if self.location.name == desktop_files: + section.pop(mimetype) + elif self.location.name in desktop_files.split(";"): + section[mimetype] = ";".join( + [x for x in desktop_files.split(";") if x != self.location.name] + ) + if not section.keys(): + config.remove_section(section_name) + with open(mimeapps, "w") as f: + config.write(f, space_around_delimiters=False) + + update_mime_database = shutil.which("update-mime-database") + if update_mime_database: + logged_run( + [update_mime_database, "-V", self.menu.data_directory / "mime"], + check=False, + ) + + def _xml_path_for_mime_type(self, mime_type: str) -> tuple[Path, bool]: + basename = mime_type.replace("/", "-") + xml_files = list( + (self.menu.data_directory / "mime" / "applications").glob(f"*{basename}*.xml") + ) + if xml_files: + if len(xml_files) > 1: + msg = "Found multiple files for MIME type %s: %s. Returning first." + log.debug(msg, mime_type, xml_files) + return xml_files[0], True + return self.menu.data_directory / "mime" / "packages" / f"{basename}.xml", False + + def _glob_pattern_for_mime_type( + self, + mime_type: str, + glob_pattern: str, + install: bool = True, + ) -> Path | None: + """ + See https://specifications.freedesktop.org/mime-apps-spec/mime-apps-spec-latest.html + for more information on the default locations. + """ + xml_path, exists = self._xml_path_for_mime_type(mime_type) + if exists: + return xml_path + + # Write the XML that binds our current mime type to the glob pattern + xmlns = "http://www.freedesktop.org/standards/shared-mime-info" + mime_info = ElementTree.Element("mime-info", xmlns=xmlns) + mime_type_tag = ElementTree.SubElement(mime_info, "mime-type", type=mime_type) + ElementTree.SubElement(mime_type_tag, "glob", pattern=glob_pattern) + descr = f"Custom MIME type {mime_type} for '{glob_pattern}' files (registered by menuinst)" + ElementTree.SubElement(mime_type_tag, "comment").text = descr + tree = ElementTree.ElementTree(mime_info) + + subcommand = "install" if install else "uninstall" + # Install the XML file and register it as default for our app + use_fallback = False + try: + with TemporaryDirectory() as tmp: + with open(os.path.join(tmp, os.path.basename(xml_path)), "wb") as f: + tree.write(f, encoding="UTF-8", xml_declaration=True) + + xdg_mime = shutil.which("xdg-mime") + if xdg_mime: + logged_run( + [xdg_mime, subcommand, "--mode", self.menu.mode, "--novendor", f.name], + check=True, + ) + else: + name = self.render_key("name") + log.warning( + "Unable to un/register MIME type '%s' " + "for Desktop Entry of name '%s': " + "'xdg-mime' is not present on the system.'", + glob_pattern, + name, + ) + use_fallback = True + except CalledProcessError: + # Note that the error from 'xdg-mime' is already logged earlier via + # the call to 'logged_run'. + use_fallback = True + log.debug("Could not un/register MIME type %s with xdg-mime.", mime_type) + + if use_fallback: + log.debug("Writing to '%s' as a fallback.", xml_path) + tree.write(xml_path, encoding="UTF-8", xml_declaration=True) + + def _paths(self) -> Iterable[os.PathLike]: + paths = [self.location] + mime_types = self.render_key("MimeType") or () + for mime in mime_types: + xml_path, exists = self._xml_path_for_mime_type(mime) + if exists and "registered by menuinst" in xml_path.read_text(): + paths.append(xml_path) + return tuple(paths) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/osx.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/osx.py new file mode 100644 index 0000000000000000000000000000000000000000..9ddfa1ee3b13c5e8ddb0aa2dcaae0215a96665a6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/osx.py @@ -0,0 +1,351 @@ +""" """ + +from __future__ import annotations + +import os +import platform +import plistlib +import shutil +from hashlib import sha1 +from logging import getLogger +from pathlib import Path + +from .. import data as _menuinst_data +from ..utils import UnixLex, logged_run +from .base import Menu, MenuItem, menuitem_defaults + +log = getLogger(__name__) + + +class MacOSMenu(Menu): + def create(self) -> tuple[os.PathLike]: + return self._paths() + + def remove(self) -> tuple[os.PathLike]: + return self._paths() + + @property + def placeholders(self) -> dict[str, str]: + placeholders = super().placeholders + placeholders.update( + { + "SP_DIR": str(self._site_packages()), + "ICON_EXT": "icns", + "PYTHONAPP": str(self.prefix / "python.app" / "Contents" / "MacOS" / "python"), + } + ) + return placeholders + + def _paths(self) -> tuple: + return () + + +class MacOSMenuItem(MenuItem): + @property + def location(self) -> Path: + "Path to the .app directory defining the menu item" + return self._base_location() / "Applications" / self._bundle_name + + @property + def _bundle_name(self) -> str: + return f"{self.render_key('name', extra={})}.app" + + @property + def _nested_location(self) -> Path: + "Path to the nested .app directory defining the menu item main app" + return self.location / "Contents" / "Resources" / self._bundle_name + + def _base_location(self) -> Path: + if self.menu.mode == "user": + return Path("~").expanduser() + return Path("/") + + def _precreate(self): + super()._precreate() + for src, dest in (self.metadata["link_in_bundle"] or {}).items(): + rendered_dest: Path = (self.location / self.render(dest)).resolve() + # if not rendered_dest.is_relative_to(self.location): # FUTURE: Only for 3.9+ + if not str(rendered_dest).startswith(str(self.location)): + raise ValueError( + "'link_in_bundle' destinations MUST be created " + f"inside the .app bundle ({self.location}), but it points to '{rendered_dest}." + ) + rendered_dest.parent.mkdir(parents=True, exist_ok=True) + os.symlink(self.render(src), rendered_dest) + + def create(self) -> tuple[Path]: + if self.location.exists(): + message = ( + f"App already exists at {self.location}. " + "Please remove the existing shortcut before installing. " + "If you used conda to install this package, " + "reinstall the package with --force-reinstall to " + "create the shortcut once the location is cleared." + ) + raise RuntimeError(message) + log.debug("Creating %s", self.location) + self._create_application_tree() + self._precreate() + self._copy_icon() + self._write_pkginfo() + self._write_plistinfo() + self._write_appkit_launcher() + self._write_launcher() + self._write_script() + self._write_event_handler() + self._maybe_register_with_launchservices() + self._sign_with_entitlements() + return (self.location,) + + def remove(self) -> tuple[Path]: + log.debug("Removing %s", self.location) + self._maybe_register_with_launchservices(register=False) + if self.location.exists(): + shutil.rmtree(self.location, ignore_errors=True) + return (self.location,) + return tuple() + + def _create_application_tree(self) -> tuple[Path]: + paths = [ + self.location / "Contents" / "Resources", + self.location / "Contents" / "MacOS", + ] + if self._needs_appkit_launcher: + paths += [ + self._nested_location / "Contents" / "Resources", + self._nested_location / "Contents" / "MacOS", + ] + for path in paths: + path.mkdir(parents=True, exist_ok=False) + return tuple(paths) + + def _copy_icon(self): + icon = self.render_key("icon") + if icon: + shutil.copy(icon, self.location / "Contents" / "Resources") + if self._needs_appkit_launcher: + shutil.copy(icon, self._nested_location / "Contents" / "Resources") + + def _write_pkginfo(self): + app_bundles = [self.location] + if self._needs_appkit_launcher: + app_bundles.append(self._nested_location) + for app in app_bundles: + with open(app / "Contents" / "PkgInfo", "w") as f: + f.write(f"APPL{self.render_key('name', slug=True)[:8]}") + + def _write_plistinfo(self): + name = self.render_key("name") + slugname = self.render_key("name", slug=True) + if len(slugname) > 16: + shortname = slugname[:10] + sha1(slugname.encode()).hexdigest()[:6] + else: + shortname = slugname + pl = { + "CFBundleName": shortname, + "CFBundleDisplayName": name, + "CFBundleExecutable": slugname, + "CFBundleGetInfoString": f"{slugname}-1.0.0", + "CFBundleIdentifier": f"com.{slugname}", + "CFBundlePackageType": "APPL", + "CFBundleVersion": "1.0.0", + "CFBundleShortVersionString": "1.0.0", + } + + icon = self.render_key("icon") + if icon: + pl["CFBundleIconFile"] = Path(icon).name + + if self._needs_appkit_launcher: + # write only the basic plist info into the nested bundle + with open(self._nested_location / "Contents" / "Info.plist", "wb") as f: + plistlib.dump(pl, f) + # the *outer* bundle is background-only and needs a different ID + pl["LSBackgroundOnly"] = True + pl["CFBundleIdentifier"] = f"com.{slugname}-appkit-launcher" + + # Override defaults with (potentially) user provided values + ignore_keys = (*menuitem_defaults, "entitlements", "link_in_bundle", "info_plist_extra") + info_plist_extra = self.metadata.get("info_plist_extra") or {} + for key in menuitem_defaults["platforms"]["osx"]: + if key in ignore_keys: + continue + if key in info_plist_extra: + raise ValueError( + f"Duplicate Info.plist property found: {key}. " + "Remove the property from `info_plist_extra`." + ) + value = self.render_key(key) + if value is None: + continue + if key == "CFBundleVersion": + # setting the version also changes these two values + pl["CFBundleShortVersionString"] = value + pl["CFBundleGetInfoString"] = f"{slugname}-{value}" + pl[key] = value + for key, value in info_plist_extra.items(): + pl[key] = self.render(value) + with open(self.location / "Contents" / "Info.plist", "wb") as f: + plistlib.dump(pl, f) + + def _command(self) -> str: + lines = ["#!/bin/sh"] + if self.render_key("terminal"): + # FIXME: Terminal launching will miss the arguments; + # there's no easy way to pass them! + lines.extend( + [ + 'if [ "${__CFBundleIdentifier:-}" != "com.apple.Terminal" ]; then', + ' open -b com.apple.terminal "$0"', + " exit $?", + "fi", + ] + ) + + working_dir = self.render_key("working_dir") + if working_dir: + Path(os.path.expandvars(working_dir)).mkdir(parents=True, exist_ok=True) + lines.append(f'cd "{working_dir}"') + + precommand = self.render_key("precommand") + if precommand: + lines.append(precommand) + + if self.metadata["activate"]: + conda_exe = self.menu.conda_exe + if self.menu._is_micromamba(conda_exe): + activate = "shell activate" + else: + activate = "shell.bash activate" + lines.append(f'eval "$("{conda_exe}" {activate} "{self.menu.prefix}")"') + + lines.append(" ".join(UnixLex.quote_args(self.render_key("command")))) + + return "\n".join(lines) + + def _write_appkit_launcher(self, launcher_path: os.PathLike | None = None) -> os.PathLike: + if launcher_path is None: + launcher_path = self._default_appkit_launcher_path() + shutil.copy(self._find_appkit_launcher(), launcher_path) + os.chmod(launcher_path, 0o755) + return launcher_path + + def _write_launcher(self, launcher_path: os.PathLike | None = None) -> os.PathLike: + if launcher_path is None: + launcher_path = self._default_launcher_path() + shutil.copy(self._find_launcher(), launcher_path) + os.chmod(launcher_path, 0o755) + return launcher_path + + def _write_script(self, script_path: os.PathLike | None = None) -> os.PathLike: + if script_path is None: + script_path = self._default_launcher_path(suffix="-script") + with open(script_path, "w") as f: + f.write(self._command()) + os.chmod(script_path, 0o755) + return script_path + + def _write_event_handler(self, script_path: os.PathLike | None = None) -> os.PathLike: + if not self._needs_appkit_launcher: + return + event_handler_logic = self.render_key("event_handler") + if event_handler_logic is None: + return + if script_path is None: + script_path = self.location / "Contents" / "Resources" / "handle-event" + with open(script_path, "w") as f: + f.write(f"#!/bin/bash\n{event_handler_logic}\n") + os.chmod(script_path, 0o755) + return script_path + + def _paths(self) -> tuple[os.PathLike]: + return (self.location,) + + def _find_appkit_launcher(self) -> Path: + launcher_name = f"appkit_launcher_{platform.machine()}" + for datapath in _menuinst_data.__path__: + launcher_path = Path(datapath) / launcher_name + if launcher_path.is_file() and os.access(launcher_path, os.X_OK): + return launcher_path + raise ValueError(f"Could not find executable launcher for {platform.machine()}") + + def _find_launcher(self) -> Path: + launcher_name = f"osx_launcher_{platform.machine()}" + for datapath in _menuinst_data.__path__: + launcher_path = Path(datapath) / launcher_name + if launcher_path.is_file() and os.access(launcher_path, os.X_OK): + return launcher_path + raise ValueError(f"Could not find executable launcher for {platform.machine()}") + + def _default_appkit_launcher_path(self, suffix: str = "") -> Path: + name = self.render_key("name", slug=True) + return self.location / "Contents" / "MacOS" / f"{name}{suffix}" + + def _default_launcher_path(self, suffix: str = "") -> Path: + name = self.render_key("name", slug=True) + if self._needs_appkit_launcher: + return self._nested_location / "Contents" / "MacOS" / f"{name}{suffix}" + return self.location / "Contents" / "MacOS" / f"{name}{suffix}" + + def _maybe_register_with_launchservices(self, register=True): + if not self._needs_appkit_launcher: + return + if register: + # register the URL scheme with `lsregister` + _lsregister("-R", str(self.location)) + else: + _lsregister("-R", "-u", "-all", str(self.location)) + + def _sign_with_entitlements(self): + "Self-sign shortcut to apply required entitlements" + entitlement_keys = self.render_key("entitlements") + if not entitlement_keys: + return + slugname = self.render_key("name", slug=True) + plist = {key: True for key in entitlement_keys} + entitlements_path = self.location / "Contents" / "Entitlements.plist" + with open(entitlements_path, "wb") as f: + plistlib.dump(plist, f) + logged_run( + [ + # hardcode to system location to avoid accidental clobber in PATH + "/usr/bin/codesign", + "--verbose", + "--sign", + "-", + "--prefix", + f"com.{slugname}", + "--options", + "runtime", + "--force", + "--deep", + "--entitlements", + entitlements_path, + self.location, + ], + check=True, + ) + + @property + def _needs_appkit_launcher(self) -> bool: + """ + In macOS, file type and URL protocol associations are handled by the + Apple Events system. When the user opens on a file or URL, the system + will send an Apple Event to the application that was registered as a handler. + Some apps might not have the needed listener to process the event. In that case, + we provide a generic one. This is decided by the presence of "event_handler". + If that key is absent or null, we assume the app has its own listener. + + See: + - https://developer.apple.com/library/archive/documentation/Carbon/Conceptual/LaunchServicesConcepts/LSCConcepts/LSCConcepts.html + - The source code at /src/appkit-launcher in this repository + """ # noqa + return bool(self.metadata.get("event_handler")) + + +def _lsregister(*args, check=True, **kwargs): + exe = ( + "/System/Library/Frameworks/CoreServices.framework" + "/Frameworks/LaunchServices.framework/Support/lsregister" + ) + return logged_run([exe, *args], check=check, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win.py new file mode 100644 index 0000000000000000000000000000000000000000..b15ab29b309b9a16c2ff0eac9139bd6e2e59bba1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win.py @@ -0,0 +1,548 @@ +""" """ + +from __future__ import annotations + +import json +import os +import shutil +import warnings +from logging import getLogger +from pathlib import Path +from subprocess import CompletedProcess +from tempfile import NamedTemporaryFile +from typing import Any + +from ..utils import WinLex, logged_run, unlink +from .base import Menu, MenuItem +from .win_utils.knownfolders import folder_path as windows_folder_path +from .win_utils.knownfolders import windows_terminal_settings_files +from .win_utils.registry import ( + notify_shell_changes, + register_file_extension, + register_url_protocol, + unregister_file_extension, + unregister_url_protocol, +) + +log = getLogger(__name__) + + +class WindowsMenu(Menu): + def create(self) -> tuple[Path]: + log.debug("Creating %s", self.start_menu_location) + self.start_menu_location.mkdir(parents=True, exist_ok=True) + if self.quick_launch_location: + self.quick_launch_location.mkdir(parents=True, exist_ok=True) + if self.desktop_location: + self.desktop_location.mkdir(parents=True, exist_ok=True) + return (self.start_menu_location,) + + def remove(self) -> tuple[Path]: + # Only remove if the Start Menu directory is empty in case applications share a folder. + menu_location = Path(self.start_menu_location) + if menu_location.exists(): + try: + # Check directory contents. If empty, it will raise StopIteration + # and only in that case we delete the directory. + next(menu_location.iterdir()) + except StopIteration: + log.debug("Removing %s", self.start_menu_location) + shutil.rmtree(self.start_menu_location, ignore_errors=True) + return (self.start_menu_location,) + return tuple() + + @property + def start_menu_location(self) -> Path: + """ + On Windows we can create shortcuts in several places: + + - Start Menu + - Desktop + - Quick launch (only for user installs) + + In this property we only report the path to the Start menu. + For other menus, check their respective properties. + """ + return Path(windows_folder_path(self.mode, False, "start")) / self.render(self.name) + + @property + def quick_launch_location(self) -> Path: + if self.mode == "system": + # TODO: Check if this is true? + warnings.warn("Quick launch menus are not available for system level installs") + return + return Path(windows_folder_path(self.mode, False, "quicklaunch")) + + @property + def desktop_location(self) -> Path: + return Path(windows_folder_path(self.mode, False, "desktop")) + + @property + def terminal_profile_locations(self) -> list[Path]: + """Location of the Windows terminal profiles. + + The parent directory is used to check if Terminal is installed + because the settings file is generated when Terminal is opened, + not when it is installed. + """ + if self.mode == "system": + log.warning("Terminal profiles are not available for system level installs") + return [] + return windows_terminal_settings_files(self.mode) + + @property + def placeholders(self) -> dict[str, str]: + placeholders = super().placeholders + placeholders.update( + { + "SCRIPTS_DIR": str(self.prefix / "Scripts"), + "PYTHON": str(self.prefix / "python.exe"), + "PYTHONW": str(self.prefix / "pythonw.exe"), + "BASE_PYTHON": str(self.base_prefix / "python.exe"), + "BASE_PYTHONW": str(self.base_prefix / "pythonw.exe"), + "BIN_DIR": str(self.prefix / "Library" / "bin"), + "SP_DIR": str(self._site_packages()), + "ICON_EXT": "ico", + } + ) + return placeholders + + def _conda_exe_path_candidates(self) -> tuple[Path]: + return ( + self.base_prefix / "_conda.exe", + Path(os.environ.get("CONDA_EXE", r"C:\oops\a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "conda.bat", + self.base_prefix / "bin" / "conda.bat", + Path(os.environ.get("MAMBA_EXE", r"C:\oops\a_file_that_does_not_exist")), + self.base_prefix / "condabin" / "micromamba.exe", + self.base_prefix / "bin" / "micromamba.exe", + ) + + def render(self, value: Any, slug: bool = False, extra: dict[str, str] | None = None) -> Any: + """ + We extend the render method here to replace forward slashes with backslashes. + We ONLY do it if the string does not start with /, because it might + be just a windows-style command-line flag (e.g. cmd /K something). + + This will not escape strings such as `/flag:something`, common + in compiler stuff but we can assume such windows specific + constructs will have their platform override, which is always an option. + + This is just a convenience for things like icon paths or Unix-like paths + in the command key. + """ + value = super().render(value, slug=slug, extra=extra) + if hasattr(value, "replace") and "/" in value and value[0] != "/": + value = value.replace("/", "\\") + return value + + def _site_packages(self, prefix: Path | None = None) -> Path: + if prefix is None: + prefix = self.prefix + return self.prefix / "Lib" / "site-packages" + + def _paths(self) -> tuple[Path]: + return (self.start_menu_location,) + + +class WindowsMenuItem(MenuItem): + @property + def location(self) -> Path: + """ + Path to the .lnk file placed in the Start Menu + On Windows, menuinst can create up to three shortcuts (start menu, desktop, quick launch) + This property only lists the one for start menu + """ + return self.menu.start_menu_location / self._shortcut_filename() + + def create(self) -> tuple[Path, ...]: + from .win_utils.winshortcut import create_shortcut + + self._precreate() + paths = self._paths() + + for path in paths: + if not path.suffix == ".lnk": + continue + + target_path, *arguments = self._process_command() + working_dir = self.render_key("working_dir") + if working_dir: + Path(os.path.expandvars(working_dir)).mkdir(parents=True, exist_ok=True) + # There are two possible interpretations of HOME on Windows: + # `%USERPROFILE%` and `%HOMEDRIVE%%HOMEPATH%`. + # Follow os.path.expanduser logic here, but keep the variables + # so that Windows can resolve them at runtime in case the drives change. + elif "USERPROFILE" in os.environ: + working_dir = "%USERPROFILE%" + else: + working_dir = "%HOMEDRIVE%%HOMEPATH%" + + icon = self.render_key("icon") or "" + + # winshortcut is a windows-only C extension! create_shortcut has this API + # Notice args must be passed as positional, no keywords allowed! + # winshortcut.create_shortcut(path, description, filename, arguments="", + # workdir=None, iconpath=None, iconindex=0, app_id="") + if Path(path).exists(): + log.warning("Overwriting existing link at %s.", path) + create_shortcut( + target_path, + self._shortcut_filename(ext=""), + str(path), + " ".join(arguments), + working_dir, + icon, + 0, + self._app_user_model_id(), + ) + + for location in self.menu.terminal_profile_locations: + self._add_remove_windows_terminal_profile(location, remove=False) + changed_extensions = self._register_file_extensions() + changed_protocols = self._register_url_protocols() + if changed_extensions or changed_protocols: + notify_shell_changes() + + return paths + + def remove(self) -> tuple[Path, ...]: + changed_extensions = self._unregister_file_extensions() + changed_protocols = self._unregister_url_protocols() + if changed_extensions or changed_protocols: + notify_shell_changes() + + for location in self.menu.terminal_profile_locations: + self._add_remove_windows_terminal_profile(location, remove=True) + + paths = tuple(path for path in self._paths() if Path(path).is_file()) + for path in paths: + log.debug("Removing %s", path) + unlink(path) + + return paths + + def _paths(self) -> tuple[Path, ...]: + paths = [self.location] + extra_dirs = [] + if self.metadata["desktop"]: + extra_dirs.append(self.menu.desktop_location) + if self.metadata["quicklaunch"] and self.menu.quick_launch_location: + warnings.warn("Quick launch menus are deprecated.") + extra_dirs.append(self.menu.quick_launch_location) + + if extra_dirs: + paths += [directory / self._shortcut_filename() for directory in extra_dirs] + + if self.metadata["activate"]: + # This is the accessory launcher script for cmd + paths.append(self._path_for_script()) + + return tuple(paths) + + def _shortcut_filename(self, ext: str = "lnk"): + ext = f".{ext}" if ext else "" + return f"{self.render_key('name', extra={})}{ext}" + + def _path_for_script(self) -> Path: + return Path(self.menu.placeholders["MENU_DIR"]) / self._shortcut_filename("bat") + + def _precreate(self): + precreate_code = self.render_key("precreate") + if not precreate_code: + return + with NamedTemporaryFile(delete=False, mode="w") as tmp: + tmp.write(precreate_code) + system32 = Path(os.environ.get("SystemRoot", "C:\\Windows")) / "system32" + cmd = [ + str(system32 / "WindowsPowerShell" / "v1.0" / "powershell.exe"), + f"\"start '{tmp.name}' -WindowStyle hidden\"", + ] + logged_run(cmd, check=True) + os.unlink(tmp.name) + + def _command(self) -> str: + lines = [ + "@ECHO OFF", + ":: Script generated by conda/menuinst", + ] + precommand = self.render_key("precommand") + if precommand: + lines.append(precommand) + if self.metadata["activate"]: + if self.menu._is_micromamba(self.menu.conda_exe): + activator = f'{self.menu.conda_exe} shell activate "{self.menu.prefix}"' + activation_lines = [ + f'@FOR /F "usebackq tokens=*" %%i IN (`{activator}`) do set "ACTIVATOR=%%i"', + "@CALL %ACTIVATOR%", + ] + else: + # conda >= 25.3.0 does not use .bat files to activate environments anymore. + # Instead, it produces .env files that are consumed inside + # conda/shell/condabin/_conda_activate.bat. There is no direct activator for this + # filetype, so menuinst has to parse the file and add the activator to the + # activation script directly. + activator_cmd = [ + str(self.menu.conda_exe), + "shell.cmd.exe", + "activate", + str(self.menu.prefix), + ] + activator_run = logged_run(activator_cmd, check=True, log=False) + activation_file = Path(activator_run.stdout.strip()) + filetype = activation_file.suffix + if filetype == ".bat": + activator = ( + f'{self.menu.conda_exe} shell.cmd.exe activate "{self.menu.prefix}"' + ) + activation_lines = [ + f'@FOR /F "usebackq tokens=*" %%i IN (`{activator}`) do set "ACTIVATOR=%%i"', # noqa + "@CALL %ACTIVATOR%", + ] + elif filetype == ".env": + activation_lines = [] + for line in activation_file.read_text().splitlines(): + keyword, value = line.strip().split("=", 1) + if keyword == "_CONDA_SCRIPT": + activation_lines.append(f"@CALL {value}") + else: + activation_lines.append(f'@SET "{keyword}={value}"') + else: + raise NotImplementedError( + f"Menuinst cannot parse activation scripts of type '{filetype}': '{activation_file}'" # noqa + ) + activation_file.unlink() + lines += [ + "@SETLOCAL ENABLEDELAYEDEXPANSION", + *activation_lines, + ":: This below is the user command", + ] + + lines.append(" ".join(WinLex.quote_args(self.render_key("command")))) + + return "\r\n".join(lines) + + def _write_script(self, script_path: os.PathLike | None = None) -> Path: + """ + This method generates the batch script that will be called by the shortcut + """ + if script_path is None: + script_path = self._path_for_script() + else: + script_path = Path(script_path) + + script_path.parent.mkdir(parents=True, exist_ok=True) + with open(script_path, "w") as f: + f.write(self._command()) + + return script_path + + def _process_command(self, with_arg1: bool = False) -> tuple[str]: + if self.metadata["activate"]: + script = self._write_script() + if self.metadata["terminal"]: + command = ["cmd", "/D", "/K", f'"{script}"'] + if with_arg1: + command.append("%1") + else: + system32 = Path(os.environ.get("SystemRoot", "C:\\Windows")) / "system32" + arg1 = "%1 " if with_arg1 else "" + # This is an UGLY hack to start the script in a hidden window + # We use CMD to call PowerShell to call the BAT file + # This flashes faster than Powershell -> BAT! Don't ask me why. + command = [ + f'"{system32 / "cmd.exe"}"', + "/D", + "/C", + "START", + "/MIN", + '""', + f'"{system32 / "WindowsPowerShell" / "v1.0" / "powershell.exe"}"', + "-WindowStyle", + "hidden", + f"\"start '{script}' {arg1}-WindowStyle hidden\"", + ] + return command + + command = self.render_key("command") + if with_arg1 and all("%1" not in arg for arg in command): + command.append("%1") + return WinLex.quote_args(command) + + def _add_remove_windows_terminal_profile(self, location: Path, remove: bool = False): + """Add/remove the Windows Terminal profile. + + Windows Terminal is using the name of the profile to create a GUID, + so the name will be used as the unique identifier to find existing profiles. + + If the Terminal app has never been opened, the settings file may not exist yet. + Writing a minimal profile file will not break the application - Terminal will + automatically generate the missing options and profiles without overwriting + the profiles menuinst has created. + """ + if not self.metadata.get("terminal_profile") or not location.parent.exists(): + return + name = self.render_key("terminal_profile") + + settings = json.loads(location.read_text()) if location.exists() else {} + + index = -1 + for p, profile in enumerate(settings.get("profiles", {}).get("list", [])): + if profile.get("name") == name: + index = p + break + + if remove: + if index < 0: + return + del settings["profiles"]["list"][index] + else: + profile_data = { + "commandline": " ".join(WinLex.quote_args(self.render_key("command"))), + "name": name, + } + if self.metadata.get("icon"): + profile_data["icon"] = self.render_key("icon") + if self.metadata.get("working_dir"): + profile_data["startingDirectory"] = self.render_key("working_dir") + if index < 0: + if "profiles" not in settings: + settings["profiles"] = {} + if "list" not in settings["profiles"]: + settings["profiles"]["list"] = [] + settings["profiles"]["list"].append(profile_data) + else: + log.warning(f"Overwriting terminal profile for {name}.") + settings["profiles"]["list"][index] = profile_data + location.write_text(json.dumps(settings, indent=4)) + + def _ftype_identifier(self, extension): + identifier = self.render_key("name", slug=True) + return f"{identifier}.AssocFile{extension}" + + def _register_file_extensions_cmd(self): + """ + This function uses CMD's `assoc` and `ftype` commands. + """ + extensions = self.metadata["file_extensions"] + if not extensions: + return + command = " ".join(self._process_command()) + exts = list(dict.fromkeys([ext.lower() for ext in extensions])) + for ext in exts: + identifier = self._ftype_identifier(ext) + self._cmd_ftype(identifier, command) + self._cmd_assoc(ext, associate_to=identifier) + + def _unregister_file_extensions_cmd(self): + """ + This function uses CMD's `assoc` and `ftype` commands. + """ + extensions = self.metadata["file_extensions"] + if not extensions: + return + exts = list(dict.fromkeys([ext.lower() for ext in extensions])) + for ext in exts: + identifier = self._ftype_identifier(ext) + self._cmd_ftype(identifier) # remove + # TODO: Do we need to clean up the `assoc` mappings too? + + @staticmethod + def _cmd_assoc( + extension: str, associate_to: str | None = None, query: bool = False, remove: bool = False + ) -> CompletedProcess: + "https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/assoc" + if sum([associate_to, query, remove]) != 1: + raise ValueError("Only one of {associate_to, query, remove} must be set.") + if not extension.startswith("."): + raise ValueError("extension must startwith '.'") + if associate_to: + arg = f"{extension}={associate_to}" + elif query: + arg = extension + elif remove: + arg = f"{extension}=" + return logged_run(["cmd", "/D", "/C", f"assoc {arg}"], check=True) + + @staticmethod + def _cmd_ftype( + identifier, command: str | None = None, query: bool = False, remove: bool = False + ) -> CompletedProcess: + "https://learn.microsoft.com/en-us/windows-server/administration/windows-commands/ftype" + if sum([command, query, remove]) != 1: + raise ValueError("Only one of {command, query, remove} must be set.") + if command: + arg = f"{identifier}={command}" + elif query: + arg = identifier + elif remove: + arg = f"{identifier}=" + return logged_run(["cmd", "/D", "/C", f"assoc {arg}"], check=True) + + def _register_file_extensions(self) -> bool: + """WIP""" + extensions = self.metadata["file_extensions"] + if not extensions: + return False + + command = " ".join(self._process_command(with_arg1=True)) + icon = self.render_key("icon") + exts = list(dict.fromkeys([ext.lower() for ext in extensions])) + for ext in exts: + identifier = self._ftype_identifier(ext) + register_file_extension( + ext, + identifier, + command, + icon=icon, + app_name=self.render_key("name"), + app_user_model_id=self._app_user_model_id(), + mode=self.menu.mode, + ) + return True + + def _unregister_file_extensions(self) -> bool: + extensions = self.metadata["file_extensions"] + if not extensions: + return False + + exts = list(dict.fromkeys([ext.lower() for ext in extensions])) + for ext in exts: + identifier = self._ftype_identifier(ext) + unregister_file_extension(ext, identifier, mode=self.menu.mode) + return True + + def _register_url_protocols(self) -> bool: + "See https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85)" # noqa + protocols = self.metadata["url_protocols"] + if not protocols: + return False + command = " ".join(self._process_command(with_arg1=True)) + icon = self.render_key("icon") + for protocol in protocols: + identifier = self._ftype_identifier(protocol) + register_url_protocol( + protocol, + command, + identifier, + icon=icon, + app_name=self.render_key("name"), + app_user_model_id=self._app_user_model_id(), + mode=self.menu.mode, + ) + return True + + def _unregister_url_protocols(self) -> bool: + protocols = self.metadata["url_protocols"] + if not protocols: + return False + for protocol in protocols: + identifier = self._ftype_identifier(protocol) + unregister_url_protocol(protocol, identifier, mode=self.menu.mode) + return True + + def _app_user_model_id(self): + aumi = self.render_key("app_user_model_id") + if not aumi: + return f"Menuinst.{self.render_key('name', slug=True).replace('.', '')}"[:128] + return aumi diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__init__.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13549f881edb0d0973f44cc7706e49d974a87ed4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/knownfolders.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/knownfolders.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..038eaa94c748660cd259c7fd43419c2ad7dc3745 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/knownfolders.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/registry.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/registry.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93909171c48f0c179f0e22d7889a3f3c56ddd221 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/registry.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/win_elevate.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/win_elevate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..372e78cc15b37dce905f7556c0fc06f132929acd Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/__pycache__/win_elevate.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/knownfolders.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/knownfolders.py new file mode 100644 index 0000000000000000000000000000000000000000..992f24bbb7d0a1e209ce29a757894451e3512e79 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/knownfolders.py @@ -0,0 +1,349 @@ +""" +This code obtained from +https://gist.github.com/mkropat/7550097 + +The MIT License (MIT) + +Copyright (c) 2014 Michael Kropat + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +""" + +from __future__ import annotations + +import ctypes +import os +from ctypes import windll, wintypes +from logging import getLogger +from pathlib import Path +from typing import List +from uuid import UUID + +logger = getLogger(__name__) + + +class GUID(ctypes.Structure): # [1] + _fields_ = [ + ("Data1", wintypes.DWORD), + ("Data2", wintypes.WORD), + ("Data3", wintypes.WORD), + ("Data4", wintypes.BYTE * 8), + ] + + def __init__(self, uuid_): + ctypes.Structure.__init__(self) + self.Data1, self.Data2, self.Data3, self.Data4[0], self.Data4[1], rest = uuid_.fields + for i in range(2, 8): + self.Data4[i] = rest >> (8 - i - 1) * 8 & 0xFF + + +class FOLDERID: # [2] + AccountPictures = UUID("{008ca0b1-55b4-4c56-b8a8-4de4b299d3be}") + AdminTools = UUID("{724EF170-A42D-4FEF-9F26-B60E846FBA4F}") + ApplicationShortcuts = UUID("{A3918781-E5F2-4890-B3D9-A7E54332328C}") + CameraRoll = UUID("{AB5FB87B-7CE2-4F83-915D-550846C9537B}") + CDBurning = UUID("{9E52AB10-F80D-49DF-ACB8-4330F5687855}") + CommonAdminTools = UUID("{D0384E7D-BAC3-4797-8F14-CBA229B392B5}") + CommonOEMLinks = UUID("{C1BAE2D0-10DF-4334-BEDD-7AA20B227A9D}") + CommonPrograms = UUID("{0139D44E-6AFE-49F2-8690-3DAFCAE6FFB8}") + CommonStartMenu = UUID("{A4115719-D62E-491D-AA7C-E74B8BE3B067}") + CommonStartup = UUID("{82A5EA35-D9CD-47C5-9629-E15D2F714E6E}") + CommonTemplates = UUID("{B94237E7-57AC-4347-9151-B08C6C32D1F7}") + Contacts = UUID("{56784854-C6CB-462b-8169-88E350ACB882}") + Cookies = UUID("{2B0F765D-C0E9-4171-908E-08A611B84FF6}") + Desktop = UUID("{B4BFCC3A-DB2C-424C-B029-7FE99A87C641}") + DeviceMetadataStore = UUID("{5CE4A5E9-E4EB-479D-B89F-130C02886155}") + Documents = UUID("{FDD39AD0-238F-46AF-ADB4-6C85480369C7}") + DocumentsLibrary = UUID("{7B0DB17D-9CD2-4A93-9733-46CC89022E7C}") + Downloads = UUID("{374DE290-123F-4565-9164-39C4925E467B}") + Favorites = UUID("{1777F761-68AD-4D8A-87BD-30B759FA33DD}") + Fonts = UUID("{FD228CB7-AE11-4AE3-864C-16F3910AB8FE}") + GameTasks = UUID("{054FAE61-4DD8-4787-80B6-090220C4B700}") + History = UUID("{D9DC8A3B-B784-432E-A781-5A1130A75963}") + ImplicitAppShortcuts = UUID("{BCB5256F-79F6-4CEE-B725-DC34E402FD46}") + InternetCache = UUID("{352481E8-33BE-4251-BA85-6007CAEDCF9D}") + Libraries = UUID("{1B3EA5DC-B587-4786-B4EF-BD1DC332AEAE}") + Links = UUID("{bfb9d5e0-c6a9-404c-b2b2-ae6db6af4968}") + LocalAppData = UUID("{F1B32785-6FBA-4FCF-9D55-7B8E7F157091}") + LocalAppDataLow = UUID("{A520A1A4-1780-4FF6-BD18-167343C5AF16}") + LocalizedResourcesDir = UUID("{2A00375E-224C-49DE-B8D1-440DF7EF3DDC}") + Music = UUID("{4BD8D571-6D19-48D3-BE97-422220080E43}") + MusicLibrary = UUID("{2112AB0A-C86A-4FFE-A368-0DE96E47012E}") + NetHood = UUID("{C5ABBF53-E17F-4121-8900-86626FC2C973}") + OriginalImages = UUID("{2C36C0AA-5812-4b87-BFD0-4CD0DFB19B39}") + PhotoAlbums = UUID("{69D2CF90-FC33-4FB7-9A0C-EBB0F0FCB43C}") + PicturesLibrary = UUID("{A990AE9F-A03B-4E80-94BC-9912D7504104}") + Pictures = UUID("{33E28130-4E1E-4676-835A-98395C3BC3BB}") + Playlists = UUID("{DE92C1C7-837F-4F69-A3BB-86E631204A23}") + PrintHood = UUID("{9274BD8D-CFD1-41C3-B35E-B13F55A758F4}") + Profile = UUID("{5E6C858F-0E22-4760-9AFE-EA3317B67173}") + ProgramData = UUID("{62AB5D82-FDC1-4DC3-A9DD-070D1D495D97}") + ProgramFiles = UUID("{905e63b6-c1bf-494e-b29c-65b732d3d21a}") + ProgramFilesX64 = UUID("{6D809377-6AF0-444b-8957-A3773F02200E}") + ProgramFilesX86 = UUID("{7C5A40EF-A0FB-4BFC-874A-C0F2E0B9FA8E}") + ProgramFilesCommon = UUID("{F7F1ED05-9F6D-47A2-AAAE-29D317C6F066}") + ProgramFilesCommonX64 = UUID("{6365D5A7-0F0D-45E5-87F6-0DA56B6A4F7D}") + ProgramFilesCommonX86 = UUID("{DE974D24-D9C6-4D3E-BF91-F4455120B917}") + Programs = UUID("{A77F5D77-2E2B-44C3-A6A2-ABA601054A51}") + Public = UUID("{DFDF76A2-C82A-4D63-906A-5644AC457385}") + PublicDesktop = UUID("{C4AA340D-F20F-4863-AFEF-F87EF2E6BA25}") + PublicDocuments = UUID("{ED4824AF-DCE4-45A8-81E2-FC7965083634}") + PublicDownloads = UUID("{3D644C9B-1FB8-4f30-9B45-F670235F79C0}") + PublicGameTasks = UUID("{DEBF2536-E1A8-4c59-B6A2-414586476AEA}") + PublicLibraries = UUID("{48DAF80B-E6CF-4F4E-B800-0E69D84EE384}") + PublicMusic = UUID("{3214FAB5-9757-4298-BB61-92A9DEAA44FF}") + PublicPictures = UUID("{B6EBFB86-6907-413C-9AF7-4FC2ABF07CC5}") + PublicRingtones = UUID("{E555AB60-153B-4D17-9F04-A5FE99FC15EC}") + PublicUserTiles = UUID("{0482af6c-08f1-4c34-8c90-e17ec98b1e17}") + PublicVideos = UUID("{2400183A-6185-49FB-A2D8-4A392A602BA3}") + QuickLaunch = UUID("{52a4f021-7b75-48a9-9f6b-4b87a210bc8f}") + Recent = UUID("{AE50C081-EBD2-438A-8655-8A092E34987A}") + RecordedTVLibrary = UUID("{1A6FDBA2-F42D-4358-A798-B74D745926C5}") + ResourceDir = UUID("{8AD10C31-2ADB-4296-A8F7-E4701232C972}") + Ringtones = UUID("{C870044B-F49E-4126-A9C3-B52A1FF411E8}") + RoamingAppData = UUID("{3EB685DB-65F9-4CF6-A03A-E3EF65729F3D}") + RoamedTileImages = UUID("{AAA8D5A5-F1D6-4259-BAA8-78E7EF60835E}") + RoamingTiles = UUID("{00BCFC5A-ED94-4e48-96A1-3F6217F21990}") + SampleMusic = UUID("{B250C668-F57D-4EE1-A63C-290EE7D1AA1F}") + SamplePictures = UUID("{C4900540-2379-4C75-844B-64E6FAF8716B}") + SamplePlaylists = UUID("{15CA69B3-30EE-49C1-ACE1-6B5EC372AFB5}") + SampleVideos = UUID("{859EAD94-2E85-48AD-A71A-0969CB56A6CD}") + SavedGames = UUID("{4C5C32FF-BB9D-43b0-B5B4-2D72E54EAAA4}") + SavedSearches = UUID("{7d1d3a04-debb-4115-95cf-2f29da2920da}") + Screenshots = UUID("{b7bede81-df94-4682-a7d8-57a52620b86f}") + SearchHistory = UUID("{0D4C3DB6-03A3-462F-A0E6-08924C41B5D4}") + SearchTemplates = UUID("{7E636BFE-DFA9-4D5E-B456-D7B39851D8A9}") + SendTo = UUID("{8983036C-27C0-404B-8F08-102D10DCFD74}") + SidebarDefaultParts = UUID("{7B396E54-9EC5-4300-BE0A-2482EBAE1A26}") + SidebarParts = UUID("{A75D362E-50FC-4fb7-AC2C-A8BEAA314493}") + SkyDrive = UUID("{A52BBA46-E9E1-435f-B3D9-28DAA648C0F6}") + SkyDriveCameraRoll = UUID("{767E6811-49CB-4273-87C2-20F355E1085B}") + SkyDriveDocuments = UUID("{24D89E24-2F19-4534-9DDE-6A6671FBB8FE}") + SkyDrivePictures = UUID("{339719B5-8C47-4894-94C2-D8F77ADD44A6}") + StartMenu = UUID("{625B53C3-AB48-4EC1-BA1F-A1EF4146FC19}") + Startup = UUID("{B97D20BB-F46A-4C97-BA10-5E3608430854}") + System = UUID("{1AC14E77-02E7-4E5D-B744-2EB1AE5198B7}") + SystemX86 = UUID("{D65231B0-B2F1-4857-A4CE-A8E7C6EA7D27}") + Templates = UUID("{A63293E8-664E-48DB-A079-DF759E0509F7}") + UserPinned = UUID("{9E3995AB-1F9C-4F13-B827-48B24B6C7174}") + UserProfiles = UUID("{0762D272-C50A-4BB0-A382-697DCD729B80}") + UserProgramFiles = UUID("{5CD7AEE2-2219-4A67-B85D-6C9CE15660CB}") + UserProgramFilesCommon = UUID("{BCBD3057-CA5C-4622-B42D-BC56DB0AE516}") + Videos = UUID("{18989B1D-99B5-455B-841C-AB7C74E4DDFC}") + VideosLibrary = UUID("{491E922F-5643-4AF4-A7EB-4E7A138D8174}") + Windows = UUID("{F38BF404-1D43-42F2-9305-67DE0B28FC23}") + + +class UserHandle: # [3] + current = wintypes.HANDLE(0) + common = wintypes.HANDLE(-1) + + +_CoTaskMemFree = windll.ole32.CoTaskMemFree # [4] +_CoTaskMemFree.restype = None +_CoTaskMemFree.argtypes = [ctypes.c_void_p] + +_SHGetKnownFolderPath = windll.shell32.SHGetKnownFolderPath # [5] [3] +_SHGetKnownFolderPath.argtypes = [ + ctypes.POINTER(GUID), + wintypes.DWORD, + wintypes.HANDLE, + ctypes.POINTER(ctypes.c_wchar_p), +] + +""" +# Please keep this code around in-case we need to debug tricky installations +# http://stackoverflow.com/a/15016751/3257826 - needs pywin32 +import pythoncom +from win32com.shell import shell, shellcon +from win32com import storagecon +import os +kfm = pythoncom.CoCreateInstance(shell.CLSID_KnownFolderManager, None, + pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IKnownFolderManager) +dir(kfm) +folders = kfm.GetFolderIds() +for folder in folders: + print(folder) +try: + docs_folder = kfm.GetFolder(shell.FOLDERID_Documents) + docs_path = docs_folder.GetPath() + print(docs_path) +except: + pass +""" + + +class PathNotFoundException(Exception): + pass + + +class PathNotVerifiableException(Exception): + pass + + +def get_path(folderid, user_handle=UserHandle.common): + fid = GUID(folderid) + pPath = ctypes.c_wchar_p() + pPathUnverified = ctypes.c_wchar_p() + S_OK = 0 + KF_FLAG_DONT_VERIFY = 0x00004000 + result = _SHGetKnownFolderPath( + ctypes.byref(fid), KF_FLAG_DONT_VERIFY, user_handle, ctypes.byref(pPathUnverified) + ) + exception = None + if result != S_OK: + exception = PathNotFoundException() + else: + result = _SHGetKnownFolderPath(ctypes.byref(fid), 0, user_handle, ctypes.byref(pPath)) + if result != S_OK: + exception = PathNotVerifiableException() + pPath = pPathUnverified + else: + _CoTaskMemFree(pPathUnverified) + + path = pPath.value + _CoTaskMemFree(pPath) + return (path, exception) + + +def get_folder_path(folder_id, user=None): + if not user: + user = UserHandle.current + # We may want to support modifying the 'Default' user here too for SCCM-based installations. + # New users created on the machine have their folders created by copying those of 'Default'. + return get_path(folder_id, user) + + +# [1] http://msdn.microsoft.com/en-us/library/windows/desktop/aa373931.aspx +# [2] http://msdn.microsoft.com/en-us/library/windows/desktop/dd378457.aspx +# [3] http://msdn.microsoft.com/en-us/library/windows/desktop/bb762188.aspx +# [4] http://msdn.microsoft.com/en-us/library/windows/desktop/ms680722.aspx +# [5] http://www.themacaque.com/?p=954 + +# jaimergp: The code below was copied from menuinst.win32, 1.4.19 +# module: menuinst/win32.py - +# https://github.com/conda/menuinst/blob/e17afafd/menuinst/win32.py#L40-L102 +# ---- +# When running as 'nt authority/system' as sometimes people do via SCCM, +# various folders do not exist, such as QuickLaunch. This doesn't matter +# as we'll use the "system" key finally and check for the "quicklaunch" +# subkey before adding any Quick Launch menu items. + +# It can happen that some of the dirs[] entires refer to folders that do not +# exist, in which case, the 2nd entry of the value tuple is a sub-class of +# Exception. + +dirs_src = { + "system": { + "desktop": get_folder_path(FOLDERID.PublicDesktop), + "start": get_folder_path(FOLDERID.CommonPrograms), + "documents": get_folder_path(FOLDERID.PublicDocuments), + "profile": get_folder_path(FOLDERID.Profile), + }, + "user": { + "desktop": get_folder_path(FOLDERID.Desktop), + "start": get_folder_path(FOLDERID.Programs), + "quicklaunch": get_folder_path(FOLDERID.QuickLaunch), + "documents": get_folder_path(FOLDERID.Documents), + "profile": get_folder_path(FOLDERID.Profile), + "localappdata": get_folder_path(FOLDERID.LocalAppData), + }, +} + + +def folder_path(preferred_mode, check_other_mode, key) -> str | None: + """This function implements all heuristics and workarounds for messed up + KNOWNFOLDERID registry values. It's also verbose (OutputDebugStringW) + about whether fallbacks worked or whether they would have worked if + check_other_mode had been allowed. + """ + other_mode = "system" if preferred_mode == "user" else "user" + path, exception = dirs_src[preferred_mode][key] + if not exception: + return path + logger.info( + "WARNING: menuinst key: '%s'\n" + " path: '%s'\n" + " .. excepted with: '%s' in knownfolders.py, implementing workarounds .." + % (key, path, type(exception).__name__) + ) + # Since I have seen 'user', 'documents' set as '\\vmware-host\Shared Folders\Documents' + # when there's no such server, we check 'user', 'profile' + '\Documents' before maybe + # trying the other_mode (though I have chickened out on that idea). + if preferred_mode == "user" and key == "documents": + user_profile, exception = dirs_src["user"]["profile"] + if not exception: + path = os.path.join(user_profile, "Documents") + if os.access(path, os.W_OK): + logger.info(" .. worked-around to: '%s'" % (path)) + return path + path, exception = dirs_src[other_mode][key] + # Do not fall back to something we cannot write to. + if exception: + if check_other_mode: + logger.info( + " .. despite 'check_other_mode'\n" + " and 'other_mode' 'path' of '%s'\n" + " it excepted with: '%s' in knownfolders.py" + % (path, type(exception).__name__) + ) + else: + logger.info( + " .. 'check_other_mode' is False,\n" + " and 'other_mode' 'path' is '%s'\n" + " but it excepted anyway with: '%s' in knownfolders.py" + % (path, type(exception).__name__) + ) + return None + if not check_other_mode: + logger.info( + " .. due to lack of 'check_other_mode' not picking\n" + " non-excepting path of '%s'\n in knownfolders.py" % (path) + ) + return None + return path + + +def windows_terminal_settings_files(mode: str) -> List[Path]: + """Return all possible locations of the settings.json files for the Windows Terminal. + + See the Microsoft documentation for details: + https://learn.microsoft.com/en-us/windows/terminal/install#settings-json-file + """ + if mode != "user": + return [] + localappdata = folder_path(mode, False, "localappdata") + packages = Path(localappdata) / "Packages" + profile_locations = [ + # Stable + *[ + Path(terminal, "LocalState", "settings.json") + for terminal in packages.glob("Microsoft.WindowsTerminal_*") + ], + # Preview + *[ + Path(terminal, "LocalState", "settings.json") + for terminal in packages.glob("Microsoft.WindowsTerminalPreview_*") + ], + ] + # Unpackaged (Scoop, Chocolatey, etc.) + unpackaged_path = Path(localappdata, "Microsoft", "Windows Terminal", "settings.json") + if unpackaged_path.parent.exists(): + profile_locations.append(unpackaged_path) + return profile_locations diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/registry.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/registry.py new file mode 100644 index 0000000000000000000000000000000000000000..12858097531cb27d01def47ce97e48ee83c74591 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/registry.py @@ -0,0 +1,215 @@ +r""" +Utilities for Windows Registry manipulation + +Notes: + +winreg.SetValue -> sets _keys_ with default ("") values +winreg.SetValueEx -> sets values with named contents + +This is important when the argument has backslashes. +SetValue will process the backslashes into a path of keys +SetValueEx will create a value with name "path\with\keys" + + +Mnemonic: SetValueEx for "excalars" (scalars, named values) +""" + +import ctypes +import winreg +from logging import getLogger + +from ...utils import logged_run + +log = getLogger(__name__) + + +def _reg_exe(*args, check=True): + return logged_run(["reg.exe", *args, "/f"], check=check) + + +def register_file_extension( + extension, + identifier, + command, + icon=None, + app_name=None, + friendly_type_name=None, + app_user_model_id=None, + mode="user", +): + """ + We want to achieve this. Entries ending in / denote keys; no trailing / means named value. + If the item has a value attached to it, it's written after the : symbol. + + HKEY_*/ # current user or local machine + Software/ + Classes/ + ./ + OpenWithProgids/ + + ... + /: "a description of the file being handled" + DefaultIcon/: "path to the app icon" + FriendlyAppName/: "Name of the program" + AppUserModelID: "AUMI string" + shell/ + open/: "Name of the program" + icon: "path to the app icon" + FriendlyAppName: "name of the program" + command/: "the command to be executed when opening a file with this extension" + """ + if mode == "system": + key = "HKEY_LOCAL_MACHINE/Software/Classes" # HKLM + else: + key = "HKEY_CURRENT_USER/Software/Classes" # HKCU + + # First we associate an extension with a handler (presence of key is enough) + regvalue(f"{key}/{extension}/OpenWithProgids/{identifier}", "") + + # Now we register the handler + regvalue(f"{key}/{identifier}/@", f"{extension} {identifier} file") + + # Set the 'open' command + regvalue(f"{key}/{identifier}/shell/open/command/@", command) + if app_name: + regvalue(f"{key}/{identifier}/shell/open/@", app_name) + regvalue(f"{key}/{identifier}/FriendlyAppName/@", app_name) + regvalue(f"{key}/{identifier}/shell/open/FriendlyAppName", app_name) + + if app_user_model_id: + regvalue(f"{key}/{identifier}/AppUserModelID", app_user_model_id) + + if icon: + # NOTE: This doesn't change the icon next in the Open With menu + # This defaults to whatever the command executable is shipping + regvalue(f"{key}/{identifier}/DefaultIcon/@", icon) + regvalue(f"{key}/{identifier}/shell/open/Icon", icon) + + if friendly_type_name: + # NOTE: Windows <10 requires the string in a PE file, but that's too + # much work. We can just put the raw string here even if the docs say + # otherwise. + regvalue(f"{key}/{identifier}/FriendlyTypeName", friendly_type_name) + + # TODO: We can add contextual menu items too + # via f"{handler_key}\shell\\command" + + +def unregister_file_extension(extension, identifier, mode="user"): + root, root_str = ( + (winreg.HKEY_LOCAL_MACHINE, "HKLM") + if mode == "system" + else (winreg.HKEY_CURRENT_USER, "HKCU") + ) + _reg_exe("delete", rf"{root_str}\Software\Classes\{identifier}", check=False) + + try: + with winreg.OpenKey( + root, rf"Software\Classes\{extension}\OpenWithProgids", 0, winreg.KEY_ALL_ACCESS + ) as key: + winreg.DeleteValue(key, identifier) + except FileNotFoundError: + log.debug("Handler '%s' is not associated with extension '%s'", identifier, extension) + except Exception as exc: + log.debug("Could not check key '%s' for deletion", extension, exc_info=exc) + return False + + +def register_url_protocol( + protocol, + command, + identifier=None, + icon=None, + app_name=None, + app_user_model_id=None, + mode="user", +): + if mode == "system": + key = f"HKEY_CLASSES_ROOT/{protocol}" + else: + key = f"HKEY_CURRENT_USER/Software/Classes/{protocol}" + regvalue(f"{key}/@", f"URL:{protocol.title()}") + regvalue(f"{key}/URL Protocol", "") + regvalue(f"{key}/shell/open/command/@", command) + if app_name: + regvalue(f"{key}/shell/open/@", app_name) + regvalue(f"{key}/FriendlyAppName/@", app_name) + regvalue(f"{key}/shell/open/FriendlyAppName", app_name) + if icon: + regvalue(f"{key}/DefaultIcon/@", icon) + regvalue(f"{key}/shell/open/Icon", icon) + if app_user_model_id: + regvalue(f"{key}/AppUserModelId", app_user_model_id) + if identifier: + # We add this one value for traceability; not required + regvalue(f"{key}/_menuinst", identifier) + + +def unregister_url_protocol(protocol, identifier=None, mode="user"): + if mode == "system": + key_tuple = winreg.HKEY_CLASSES_ROOT, protocol + key_str = rf"HKCR\{protocol}" + else: + key_tuple = winreg.HKEY_CURRENT_USER, rf"Software\Classes\{protocol}" + key_str = rf"HKCU\Software\Classes\{protocol}" + try: + with winreg.OpenKey(*key_tuple) as key: + value, _ = winreg.QueryValueEx(key, "_menuinst") + delete = identifier is None or value == identifier + except OSError as exc: + log.exception("Could not check key %s for deletion", protocol, exc_info=exc) + return + + if delete: + _reg_exe("delete", key_str, check=False) + + +def regvalue(key, value, value_type=winreg.REG_SZ, raise_on_errors=True): + """ + Convenience wrapper to set different types of registry values. + + For practical purposes we distinguish between three cases: + + - A key with no value (think of a directory with no contents). + Use value = "". + - A key with an unnamed value (think of a directory with a file 'index.html') + Use a key with '@' as the last component. + - A key with named values (think of non-index.html files in the directory) + + The first component of the key is the root, and must be one of the winreg.HKEY_* + variable _names_ (their actual value will be fetched from winreg). + + Key must be at least three components long (root key, *key, @ or named value). + """ + log.debug("Setting registry value %s = '%s'", key, value) + key = original_key = key.replace("\\", "/").strip("/") + root, *midkey, subkey, named_value = key.split("/") + rootkey = getattr(winreg, root) + access = winreg.KEY_SET_VALUE + try: + if named_value == "@": + if midkey: + winreg.CreateKey(rootkey, "\\".join(midkey)) # ensure it exists + with winreg.OpenKey(rootkey, "\\".join(midkey), access=access) as key: + winreg.SetValue(key, subkey, value_type, value) + else: + winreg.CreateKey(rootkey, "\\".join([*midkey, subkey])) # ensure it exists + with winreg.OpenKey(rootkey, "\\".join([*midkey, subkey]), access=access) as key: + winreg.SetValueEx(key, named_value, 0, value_type, value) + except OSError as exc: + if raise_on_errors: + raise + log.warning("Could not set %s to %s", original_key, value, exc_info=exc) + + +def notify_shell_changes(): + """ + Needed to propagate registry changes without having to reboot. + + https://discuss.python.org/t/is-there-a-library-to-change-windows-10-default-program-icon/5846/2 + """ + shell32 = ctypes.OleDLL("shell32") + shell32.SHChangeNotify.restype = None + event = 0x08000000 # SHCNE_ASSOCCHANGED + flags = 0x0000 # SHCNF_IDLIST + shell32.SHChangeNotify(event, flags, None, None) diff --git a/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/win_elevate.py b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/win_elevate.py new file mode 100644 index 0000000000000000000000000000000000000000..bda75b49109ad537d5f092ef17473512c67d01d1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/menuinst/platforms/win_utils/win_elevate.py @@ -0,0 +1,178 @@ +# -*- coding: utf-8; mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- +# vim: fileencoding=utf-8 tabstop=4 expandtab shiftwidth=4 +# +# Copied from http://stackoverflow.com/a/19719292/1170370 on 20160407 MCS +# +# (C) COPYRIGHT © Preston Landers 2010 +# Released under the same license as Python 2.6.5 + + +from __future__ import print_function + +import os +import sys +import traceback +from enum import IntEnum +from subprocess import list2cmdline + + +def isUserAdmin(): + if os.name != "nt": + raise RuntimeError("This function is only implemented on Windows.") + + import ctypes + + # Requires Windows XP SP2 or higher! + try: + return ctypes.windll.shell32.IsUserAnAdmin() + except: # noqa + traceback.print_exc() + print("Admin check failed, assuming not an admin.") + return False + + +# Taken from conda/common/_os/windows.py +if os.name == "nt": + + def ensure_binary(value): + try: + return value.encode("utf-8") + except AttributeError: # pragma: no cover + # AttributeError: '<>' object has no attribute 'encode' + # In this case assume already binary type and do nothing + return value + + from ctypes import ( + POINTER, + Structure, + WinError, + byref, + c_char_p, + c_int, + c_ulong, + c_void_p, + sizeof, + windll, + ) + from ctypes.wintypes import BOOL, DWORD, HANDLE, HINSTANCE, HKEY, HWND + + PHANDLE = POINTER(HANDLE) + PDWORD = POINTER(DWORD) + SEE_MASK_NOCLOSEPROCESS = 0x00000040 + INFINITE = -1 + + WaitForSingleObject = windll.kernel32.WaitForSingleObject + WaitForSingleObject.argtypes = (HANDLE, DWORD) + WaitForSingleObject.restype = DWORD + + GetExitCodeProcess = windll.kernel32.GetExitCodeProcess + GetExitCodeProcess.argtypes = (HANDLE, PDWORD) + GetExitCodeProcess.restype = BOOL + + class ShellExecuteInfo(Structure): + """ + https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/nf-shellapi-shellexecuteexa + https://docs.microsoft.com/en-us/windows/desktop/api/shellapi/ns-shellapi-_shellexecuteinfoa + """ + + _fields_ = [ + ("cbSize", DWORD), + ("fMask", c_ulong), + ("hwnd", HWND), + ("lpVerb", c_char_p), + ("lpFile", c_char_p), + ("lpParameters", c_char_p), + ("lpDirectory", c_char_p), + ("nShow", c_int), + ("hInstApp", HINSTANCE), + ("lpIDList", c_void_p), + ("lpClass", c_char_p), + ("hKeyClass", HKEY), + ("dwHotKey", DWORD), + ("hIcon", HANDLE), + ("hProcess", HANDLE), + ] + + def __init__(self, **kwargs): + Structure.__init__(self) + self.cbSize = sizeof(self) + for field_name, field_value in kwargs.items(): + if isinstance(field_value, str): + field_value = ensure_binary(field_value) + setattr(self, field_name, field_value) + + PShellExecuteInfo = POINTER(ShellExecuteInfo) + ShellExecuteEx = windll.Shell32.ShellExecuteExA + ShellExecuteEx.argtypes = (PShellExecuteInfo,) + ShellExecuteEx.restype = BOOL + + +class SW(IntEnum): + HIDE = 0 + MAXIMIZE = 3 + MINIMIZE = 6 + RESTORE = 9 + SHOW = 5 + SHOWDEFAULT = 10 + SHOWMAXIMIZED = 3 + SHOWMINIMIZED = 2 + SHOWMINNOACTIVE = 7 + SHOWNA = 8 + SHOWNOACTIVATE = 4 + SHOWNORMAL = 1 + + +def runAsAdmin(cmdLine=None, wait=True): + if os.name != "nt": + raise RuntimeError("This function is only implemented on Windows.") + + python_exe = sys.executable + + if cmdLine is None: + cmdLine = [python_exe] + sys.argv + elif not hasattr(cmdLine, "__iter__") or isinstance(cmdLine, str): + raise ValueError("cmdLine is not a sequence.") + + cmd = '"%s"' % (cmdLine[0],) + params = list2cmdline(cmdLine[1:]) + showCmd = SW.HIDE + lpVerb = "runas" # causes UAC elevation prompt. + + # ShellExecute() doesn't seem to allow us to fetch the PID or handle + # of the process, so we can't get anything useful from it. Therefore + # the more complex ShellExecuteEx() must be used. + + # procHandle = win32api.ShellExecute(0, lpVerb, cmd, params, cmdDir, showCmd) + execute_info = ShellExecuteInfo( + nShow=showCmd, + fMask=SEE_MASK_NOCLOSEPROCESS, + lpVerb=lpVerb, + lpFile=cmd, + lpParameters=params, + hwnd=None, + lpDirectory=None, + ) + + successful = ShellExecuteEx(byref(execute_info)) + + if not successful: + raise WinError() + + if wait: + procHandle = execute_info.hProcess + WaitForSingleObject(procHandle, INFINITE) + err = DWORD() + GetExitCodeProcess(procHandle, byref(err)) + rc = err.value + else: + rc = None + + return rc + + +if __name__ == "__main__": + userIsAdmin = isUserAdmin() + with open("output.txt", "a") as f: + print("userIsAdmin = %d" % (userIsAdmin), file=f) + if not userIsAdmin: + runAsAdmin([sys.executable] + sys.argv, wait=True) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c55302485e3fd570f55a255314318c274adc9098 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__init__.py @@ -0,0 +1,10 @@ +from . import axes_size as Size +from .axes_divider import Divider, SubplotDivider, make_axes_locatable +from .axes_grid import AxesGrid, Grid, ImageGrid + +from .parasite_axes import host_subplot, host_axes + +__all__ = ["Size", + "Divider", "SubplotDivider", "make_axes_locatable", + "AxesGrid", "Grid", "ImageGrid", + "host_subplot", "host_axes"] diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4bca07f7b8a1dd8f30a09e1fb0cd872a0fa1d888 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/anchored_artists.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/anchored_artists.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3d9330f887dc68ce91619da6b7c6130ffc47b948 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/anchored_artists.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_divider.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_divider.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a811ae921b4dc192f68563df7fde73be1e24a0a4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_divider.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_grid.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_grid.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3e1e3417e126dcc996e76bc7086fd547d8869fbf Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_grid.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_rgb.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_rgb.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..685b84262166ee9b4e760238a3062133cdacd22e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_rgb.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_size.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_size.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9df6ec9e4ed1fe92f82fffa84d98649a0476fb61 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/axes_size.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/inset_locator.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/inset_locator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5702a4f7e15adf015ade254a471213114061313b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/inset_locator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/mpl_axes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/mpl_axes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5e572de9ae793ad2f9a5a044a264f450b05c751 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/mpl_axes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/parasite_axes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/parasite_axes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14c4af5cb328a77e212c59edfa908b58cb9e990d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/__pycache__/parasite_axes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/anchored_artists.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/anchored_artists.py new file mode 100644 index 0000000000000000000000000000000000000000..214b15843ebfaf2e2ee26e100a2194dfe092382d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/anchored_artists.py @@ -0,0 +1,414 @@ +from matplotlib import transforms +from matplotlib.offsetbox import (AnchoredOffsetbox, AuxTransformBox, + DrawingArea, TextArea, VPacker) +from matplotlib.patches import (Rectangle, ArrowStyle, + FancyArrowPatch, PathPatch) +from matplotlib.text import TextPath + +__all__ = ['AnchoredDrawingArea', 'AnchoredAuxTransformBox', + 'AnchoredSizeBar', 'AnchoredDirectionArrows'] + + +class AnchoredDrawingArea(AnchoredOffsetbox): + def __init__(self, width, height, xdescent, ydescent, + loc, pad=0.4, borderpad=0.5, prop=None, frameon=True, + **kwargs): + """ + An anchored container with a fixed size and fillable `.DrawingArea`. + + Artists added to the *drawing_area* will have their coordinates + interpreted as pixels. Any transformations set on the artists will be + overridden. + + Parameters + ---------- + width, height : float + Width and height of the container, in pixels. + xdescent, ydescent : float + Descent of the container in the x- and y- direction, in pixels. + loc : str + Location of this artist. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + pad : float, default: 0.4 + Padding around the child objects, in fraction of the font size. + borderpad : float, default: 0.5 + Border padding, in fraction of the font size. + prop : `~matplotlib.font_manager.FontProperties`, optional + Font property used as a reference for paddings. + frameon : bool, default: True + If True, draw a box around this artist. + **kwargs + Keyword arguments forwarded to `.AnchoredOffsetbox`. + + Attributes + ---------- + drawing_area : `~matplotlib.offsetbox.DrawingArea` + A container for artists to display. + + Examples + -------- + To display blue and red circles of different sizes in the upper right + of an Axes *ax*: + + >>> ada = AnchoredDrawingArea(20, 20, 0, 0, + ... loc='upper right', frameon=False) + >>> ada.drawing_area.add_artist(Circle((10, 10), 10, fc="b")) + >>> ada.drawing_area.add_artist(Circle((30, 10), 5, fc="r")) + >>> ax.add_artist(ada) + """ + self.da = DrawingArea(width, height, xdescent, ydescent) + self.drawing_area = self.da + + super().__init__( + loc, pad=pad, borderpad=borderpad, child=self.da, prop=None, + frameon=frameon, **kwargs + ) + + +class AnchoredAuxTransformBox(AnchoredOffsetbox): + def __init__(self, transform, loc, + pad=0.4, borderpad=0.5, prop=None, frameon=True, **kwargs): + """ + An anchored container with transformed coordinates. + + Artists added to the *drawing_area* are scaled according to the + coordinates of the transformation used. The dimensions of this artist + will scale to contain the artists added. + + Parameters + ---------- + transform : `~matplotlib.transforms.Transform` + The transformation object for the coordinate system in use, i.e., + :attr:`matplotlib.axes.Axes.transData`. + loc : str + Location of this artist. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + pad : float, default: 0.4 + Padding around the child objects, in fraction of the font size. + borderpad : float, default: 0.5 + Border padding, in fraction of the font size. + prop : `~matplotlib.font_manager.FontProperties`, optional + Font property used as a reference for paddings. + frameon : bool, default: True + If True, draw a box around this artist. + **kwargs + Keyword arguments forwarded to `.AnchoredOffsetbox`. + + Attributes + ---------- + drawing_area : `~matplotlib.offsetbox.AuxTransformBox` + A container for artists to display. + + Examples + -------- + To display an ellipse in the upper left, with a width of 0.1 and + height of 0.4 in data coordinates: + + >>> box = AnchoredAuxTransformBox(ax.transData, loc='upper left') + >>> el = Ellipse((0, 0), width=0.1, height=0.4, angle=30) + >>> box.drawing_area.add_artist(el) + >>> ax.add_artist(box) + """ + self.drawing_area = AuxTransformBox(transform) + + super().__init__(loc, pad=pad, borderpad=borderpad, + child=self.drawing_area, prop=prop, frameon=frameon, + **kwargs) + + +class AnchoredSizeBar(AnchoredOffsetbox): + def __init__(self, transform, size, label, loc, + pad=0.1, borderpad=0.1, sep=2, + frameon=True, size_vertical=0, color='black', + label_top=False, fontproperties=None, fill_bar=None, + **kwargs): + """ + Draw a horizontal scale bar with a center-aligned label underneath. + + Parameters + ---------- + transform : `~matplotlib.transforms.Transform` + The transformation object for the coordinate system in use, i.e., + :attr:`matplotlib.axes.Axes.transData`. + size : float + Horizontal length of the size bar, given in coordinates of + *transform*. + label : str + Label to display. + loc : str + Location of the size bar. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + pad : float, default: 0.1 + Padding around the label and size bar, in fraction of the font + size. + borderpad : float, default: 0.1 + Border padding, in fraction of the font size. + sep : float, default: 2 + Separation between the label and the size bar, in points. + frameon : bool, default: True + If True, draw a box around the horizontal bar and label. + size_vertical : float, default: 0 + Vertical length of the size bar, given in coordinates of + *transform*. + color : str, default: 'black' + Color for the size bar and label. + label_top : bool, default: False + If True, the label will be over the size bar. + fontproperties : `~matplotlib.font_manager.FontProperties`, optional + Font properties for the label text. + fill_bar : bool, optional + If True and if *size_vertical* is nonzero, the size bar will + be filled in with the color specified by the size bar. + Defaults to True if *size_vertical* is greater than + zero and False otherwise. + **kwargs + Keyword arguments forwarded to `.AnchoredOffsetbox`. + + Attributes + ---------- + size_bar : `~matplotlib.offsetbox.AuxTransformBox` + Container for the size bar. + txt_label : `~matplotlib.offsetbox.TextArea` + Container for the label of the size bar. + + Notes + ----- + If *prop* is passed as a keyword argument, but *fontproperties* is + not, then *prop* is assumed to be the intended *fontproperties*. + Using both *prop* and *fontproperties* is not supported. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from mpl_toolkits.axes_grid1.anchored_artists import ( + ... AnchoredSizeBar) + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.random.random((10, 10))) + >>> bar = AnchoredSizeBar(ax.transData, 3, '3 data units', 4) + >>> ax.add_artist(bar) + >>> fig.show() + + Using all the optional parameters + + >>> import matplotlib.font_manager as fm + >>> fontprops = fm.FontProperties(size=14, family='monospace') + >>> bar = AnchoredSizeBar(ax.transData, 3, '3 units', 4, pad=0.5, + ... sep=5, borderpad=0.5, frameon=False, + ... size_vertical=0.5, color='white', + ... fontproperties=fontprops) + """ + if fill_bar is None: + fill_bar = size_vertical > 0 + + self.size_bar = AuxTransformBox(transform) + self.size_bar.add_artist(Rectangle((0, 0), size, size_vertical, + fill=fill_bar, facecolor=color, + edgecolor=color)) + + if fontproperties is None and 'prop' in kwargs: + fontproperties = kwargs.pop('prop') + + if fontproperties is None: + textprops = {'color': color} + else: + textprops = {'color': color, 'fontproperties': fontproperties} + + self.txt_label = TextArea(label, textprops=textprops) + + if label_top: + _box_children = [self.txt_label, self.size_bar] + else: + _box_children = [self.size_bar, self.txt_label] + + self._box = VPacker(children=_box_children, + align="center", + pad=0, sep=sep) + + super().__init__(loc, pad=pad, borderpad=borderpad, child=self._box, + prop=fontproperties, frameon=frameon, **kwargs) + + +class AnchoredDirectionArrows(AnchoredOffsetbox): + def __init__(self, transform, label_x, label_y, length=0.15, + fontsize=0.08, loc='upper left', angle=0, aspect_ratio=1, + pad=0.4, borderpad=0.4, frameon=False, color='w', alpha=1, + sep_x=0.01, sep_y=0, fontproperties=None, back_length=0.15, + head_width=10, head_length=15, tail_width=2, + text_props=None, arrow_props=None, + **kwargs): + """ + Draw two perpendicular arrows to indicate directions. + + Parameters + ---------- + transform : `~matplotlib.transforms.Transform` + The transformation object for the coordinate system in use, i.e., + :attr:`matplotlib.axes.Axes.transAxes`. + label_x, label_y : str + Label text for the x and y arrows + length : float, default: 0.15 + Length of the arrow, given in coordinates of *transform*. + fontsize : float, default: 0.08 + Size of label strings, given in coordinates of *transform*. + loc : str, default: 'upper left' + Location of the arrow. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + angle : float, default: 0 + The angle of the arrows in degrees. + aspect_ratio : float, default: 1 + The ratio of the length of arrow_x and arrow_y. + Negative numbers can be used to change the direction. + pad : float, default: 0.4 + Padding around the labels and arrows, in fraction of the font size. + borderpad : float, default: 0.4 + Border padding, in fraction of the font size. + frameon : bool, default: False + If True, draw a box around the arrows and labels. + color : str, default: 'white' + Color for the arrows and labels. + alpha : float, default: 1 + Alpha values of the arrows and labels + sep_x, sep_y : float, default: 0.01 and 0 respectively + Separation between the arrows and labels in coordinates of + *transform*. + fontproperties : `~matplotlib.font_manager.FontProperties`, optional + Font properties for the label text. + back_length : float, default: 0.15 + Fraction of the arrow behind the arrow crossing. + head_width : float, default: 10 + Width of arrow head, sent to `.ArrowStyle`. + head_length : float, default: 15 + Length of arrow head, sent to `.ArrowStyle`. + tail_width : float, default: 2 + Width of arrow tail, sent to `.ArrowStyle`. + text_props, arrow_props : dict + Properties of the text and arrows, passed to `.TextPath` and + `.FancyArrowPatch`. + **kwargs + Keyword arguments forwarded to `.AnchoredOffsetbox`. + + Attributes + ---------- + arrow_x, arrow_y : `~matplotlib.patches.FancyArrowPatch` + Arrow x and y + text_path_x, text_path_y : `~matplotlib.text.TextPath` + Path for arrow labels + p_x, p_y : `~matplotlib.patches.PathPatch` + Patch for arrow labels + box : `~matplotlib.offsetbox.AuxTransformBox` + Container for the arrows and labels. + + Notes + ----- + If *prop* is passed as a keyword argument, but *fontproperties* is + not, then *prop* is assumed to be the intended *fontproperties*. + Using both *prop* and *fontproperties* is not supported. + + Examples + -------- + >>> import matplotlib.pyplot as plt + >>> import numpy as np + >>> from mpl_toolkits.axes_grid1.anchored_artists import ( + ... AnchoredDirectionArrows) + >>> fig, ax = plt.subplots() + >>> ax.imshow(np.random.random((10, 10))) + >>> arrows = AnchoredDirectionArrows(ax.transAxes, '111', '110') + >>> ax.add_artist(arrows) + >>> fig.show() + + Using several of the optional parameters, creating downward pointing + arrow and high contrast text labels. + + >>> import matplotlib.font_manager as fm + >>> fontprops = fm.FontProperties(family='monospace') + >>> arrows = AnchoredDirectionArrows(ax.transAxes, 'East', 'South', + ... loc='lower left', color='k', + ... aspect_ratio=-1, sep_x=0.02, + ... sep_y=-0.01, + ... text_props={'ec':'w', 'fc':'k'}, + ... fontproperties=fontprops) + """ + if arrow_props is None: + arrow_props = {} + + if text_props is None: + text_props = {} + + arrowstyle = ArrowStyle("Simple", + head_width=head_width, + head_length=head_length, + tail_width=tail_width) + + if fontproperties is None and 'prop' in kwargs: + fontproperties = kwargs.pop('prop') + + if 'color' not in arrow_props: + arrow_props['color'] = color + + if 'alpha' not in arrow_props: + arrow_props['alpha'] = alpha + + if 'color' not in text_props: + text_props['color'] = color + + if 'alpha' not in text_props: + text_props['alpha'] = alpha + + t_start = transform + t_end = t_start + transforms.Affine2D().rotate_deg(angle) + + self.box = AuxTransformBox(t_end) + + length_x = length + length_y = length*aspect_ratio + + self.arrow_x = FancyArrowPatch( + (0, back_length*length_y), + (length_x, back_length*length_y), + arrowstyle=arrowstyle, + shrinkA=0.0, + shrinkB=0.0, + **arrow_props) + + self.arrow_y = FancyArrowPatch( + (back_length*length_x, 0), + (back_length*length_x, length_y), + arrowstyle=arrowstyle, + shrinkA=0.0, + shrinkB=0.0, + **arrow_props) + + self.box.add_artist(self.arrow_x) + self.box.add_artist(self.arrow_y) + + text_path_x = TextPath(( + length_x+sep_x, back_length*length_y+sep_y), label_x, + size=fontsize, prop=fontproperties) + self.p_x = PathPatch(text_path_x, transform=t_start, **text_props) + self.box.add_artist(self.p_x) + + text_path_y = TextPath(( + length_x*back_length+sep_x, length_y*(1-back_length)+sep_y), + label_y, size=fontsize, prop=fontproperties) + self.p_y = PathPatch(text_path_y, **text_props) + self.box.add_artist(self.p_y) + + super().__init__(loc, pad=pad, borderpad=borderpad, child=self.box, + frameon=frameon, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_divider.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_divider.py new file mode 100644 index 0000000000000000000000000000000000000000..50365f482b725d3be435ddd14d9729d30b343124 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_divider.py @@ -0,0 +1,618 @@ +""" +Helper classes to adjust the positions of multiple axes at drawing time. +""" + +import functools + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api +from matplotlib.gridspec import SubplotSpec +import matplotlib.transforms as mtransforms +from . import axes_size as Size + + +class Divider: + """ + An Axes positioning class. + + The divider is initialized with lists of horizontal and vertical sizes + (:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given + rectangular area will be divided. + + The `new_locator` method then creates a callable object + that can be used as the *axes_locator* of the axes. + """ + + def __init__(self, fig, pos, horizontal, vertical, + aspect=None, anchor="C"): + """ + Parameters + ---------- + fig : Figure + pos : tuple of 4 floats + Position of the rectangle that will be divided. + horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size` + Sizes for horizontal division. + vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size` + Sizes for vertical division. + aspect : bool, optional + Whether overall rectangular area is reduced so that the relative + part of the horizontal and vertical scales have the same scale. + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \ +'NW', 'W'}, default: 'C' + Placement of the reduced rectangle, when *aspect* is True. + """ + + self._fig = fig + self._pos = pos + self._horizontal = horizontal + self._vertical = vertical + self._anchor = anchor + self.set_anchor(anchor) + self._aspect = aspect + self._xrefindex = 0 + self._yrefindex = 0 + self._locator = None + + def get_horizontal_sizes(self, renderer): + return np.array([s.get_size(renderer) for s in self.get_horizontal()]) + + def get_vertical_sizes(self, renderer): + return np.array([s.get_size(renderer) for s in self.get_vertical()]) + + def set_position(self, pos): + """ + Set the position of the rectangle. + + Parameters + ---------- + pos : tuple of 4 floats + position of the rectangle that will be divided + """ + self._pos = pos + + def get_position(self): + """Return the position of the rectangle.""" + return self._pos + + def set_anchor(self, anchor): + """ + Parameters + ---------- + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \ +'NW', 'W'} + Either an (*x*, *y*) pair of relative coordinates (0 is left or + bottom, 1 is right or top), 'C' (center), or a cardinal direction + ('SW', southwest, is bottom left, etc.). + + See Also + -------- + .Axes.set_anchor + """ + if isinstance(anchor, str): + _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor) + elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2: + raise TypeError("anchor must be str or 2-tuple") + self._anchor = anchor + + def get_anchor(self): + """Return the anchor.""" + return self._anchor + + def get_subplotspec(self): + return None + + def set_horizontal(self, h): + """ + Parameters + ---------- + h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size` + sizes for horizontal division + """ + self._horizontal = h + + def get_horizontal(self): + """Return horizontal sizes.""" + return self._horizontal + + def set_vertical(self, v): + """ + Parameters + ---------- + v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size` + sizes for vertical division + """ + self._vertical = v + + def get_vertical(self): + """Return vertical sizes.""" + return self._vertical + + def set_aspect(self, aspect=False): + """ + Parameters + ---------- + aspect : bool + """ + self._aspect = aspect + + def get_aspect(self): + """Return aspect.""" + return self._aspect + + def set_locator(self, _locator): + self._locator = _locator + + def get_locator(self): + return self._locator + + def get_position_runtime(self, ax, renderer): + if self._locator is None: + return self.get_position() + else: + return self._locator(ax, renderer).bounds + + @staticmethod + def _calc_k(sizes, total): + # sizes is a (n, 2) array of (rel_size, abs_size); this method finds + # the k factor such that sum(rel_size * k + abs_size) == total. + rel_sum, abs_sum = sizes.sum(0) + return (total - abs_sum) / rel_sum if rel_sum else 0 + + @staticmethod + def _calc_offsets(sizes, k): + # Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return + # the resulting cumulative offset positions. + return np.cumsum([0, *(sizes @ [k, 1])]) + + def new_locator(self, nx, ny, nx1=None, ny1=None): + """ + Return an axes locator callable for the specified cell. + + Parameters + ---------- + nx, nx1 : int + Integers specifying the column-position of the + cell. When *nx1* is None, a single *nx*-th column is + specified. Otherwise, location of columns spanning between *nx* + to *nx1* (but excluding *nx1*-th column) is specified. + ny, ny1 : int + Same as *nx* and *nx1*, but for row positions. + """ + if nx1 is None: + nx1 = nx + 1 + if ny1 is None: + ny1 = ny + 1 + # append_size("left") adds a new size at the beginning of the + # horizontal size lists; this shift transforms e.g. + # new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To + # take that into account, instead of recording nx, we record + # nx-self._xrefindex, where _xrefindex is shifted by 1 by each + # append_size("left"), and re-add self._xrefindex back to nx in + # _locate, when the actual axes position is computed. Ditto for y. + xref = self._xrefindex + yref = self._yrefindex + locator = functools.partial( + self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref) + locator.get_subplotspec = self.get_subplotspec + return locator + + def _locate(self, nx, ny, nx1, ny1, axes, renderer): + """ + Implementation of ``divider.new_locator().__call__``. + + The axes locator callable returned by ``new_locator()`` is created as + a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1* + specifying the requested cell. + """ + nx += self._xrefindex + nx1 += self._xrefindex + ny += self._yrefindex + ny1 += self._yrefindex + + fig_w, fig_h = self._fig.bbox.size / self._fig.dpi + x, y, w, h = self.get_position_runtime(axes, renderer) + + hsizes = self.get_horizontal_sizes(renderer) + vsizes = self.get_vertical_sizes(renderer) + k_h = self._calc_k(hsizes, fig_w * w) + k_v = self._calc_k(vsizes, fig_h * h) + + if self.get_aspect(): + k = min(k_h, k_v) + ox = self._calc_offsets(hsizes, k) + oy = self._calc_offsets(vsizes, k) + + ww = (ox[-1] - ox[0]) / fig_w + hh = (oy[-1] - oy[0]) / fig_h + pb = mtransforms.Bbox.from_bounds(x, y, w, h) + pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh) + x0, y0 = pb1.anchored(self.get_anchor(), pb).p0 + + else: + ox = self._calc_offsets(hsizes, k_h) + oy = self._calc_offsets(vsizes, k_v) + x0, y0 = x, y + + if nx1 is None: + nx1 = -1 + if ny1 is None: + ny1 = -1 + + x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w + y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h + + return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) + + def append_size(self, position, size): + _api.check_in_list(["left", "right", "bottom", "top"], + position=position) + if position == "left": + self._horizontal.insert(0, size) + self._xrefindex += 1 + elif position == "right": + self._horizontal.append(size) + elif position == "bottom": + self._vertical.insert(0, size) + self._yrefindex += 1 + else: # 'top' + self._vertical.append(size) + + def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None): + """ + Add auto-adjustable padding around *use_axes* to take their decorations + (title, labels, ticks, ticklabels) into account during layout. + + Parameters + ---------- + use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes` + The Axes whose decorations are taken into account. + pad : float, default: 0.1 + Additional padding in inches. + adjust_dirs : list of {"left", "right", "bottom", "top"}, optional + The sides where padding is added; defaults to all four sides. + """ + if adjust_dirs is None: + adjust_dirs = ["left", "right", "bottom", "top"] + for d in adjust_dirs: + self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad) + + +class SubplotDivider(Divider): + """ + The Divider class whose rectangle area is specified as a subplot geometry. + """ + + def __init__(self, fig, *args, horizontal=None, vertical=None, + aspect=None, anchor='C'): + """ + Parameters + ---------- + fig : `~matplotlib.figure.Figure` + + *args : tuple (*nrows*, *ncols*, *index*) or int + The array of subplots in the figure has dimensions ``(nrows, + ncols)``, and *index* is the index of the subplot being created. + *index* starts at 1 in the upper left corner and increases to the + right. + + If *nrows*, *ncols*, and *index* are all single digit numbers, then + *args* can be passed as a single 3-digit number (e.g. 234 for + (2, 3, 4)). + horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional + Sizes for horizontal division. + vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional + Sizes for vertical division. + aspect : bool, optional + Whether overall rectangular area is reduced so that the relative + part of the horizontal and vertical scales have the same scale. + anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \ +'NW', 'W'}, default: 'C' + Placement of the reduced rectangle, when *aspect* is True. + """ + self.figure = fig + super().__init__(fig, [0, 0, 1, 1], + horizontal=horizontal or [], vertical=vertical or [], + aspect=aspect, anchor=anchor) + self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args)) + + def get_position(self): + """Return the bounds of the subplot box.""" + return self.get_subplotspec().get_position(self.figure).bounds + + def get_subplotspec(self): + """Get the SubplotSpec instance.""" + return self._subplotspec + + def set_subplotspec(self, subplotspec): + """Set the SubplotSpec instance.""" + self._subplotspec = subplotspec + self.set_position(subplotspec.get_position(self.figure)) + + +class AxesDivider(Divider): + """ + Divider based on the preexisting axes. + """ + + def __init__(self, axes, xref=None, yref=None): + """ + Parameters + ---------- + axes : :class:`~matplotlib.axes.Axes` + xref + yref + """ + self._axes = axes + if xref is None: + self._xref = Size.AxesX(axes) + else: + self._xref = xref + if yref is None: + self._yref = Size.AxesY(axes) + else: + self._yref = yref + + super().__init__(fig=axes.get_figure(), pos=None, + horizontal=[self._xref], vertical=[self._yref], + aspect=None, anchor="C") + + def _get_new_axes(self, *, axes_class=None, **kwargs): + axes = self._axes + if axes_class is None: + axes_class = type(axes) + return axes_class(axes.get_figure(), axes.get_position(original=True), + **kwargs) + + def new_horizontal(self, size, pad=None, pack_start=False, **kwargs): + """ + Helper method for ``append_axes("left")`` and ``append_axes("right")``. + + See the documentation of `append_axes` for more details. + + :meta private: + """ + if pad is None: + pad = mpl.rcParams["figure.subplot.wspace"] * self._xref + pos = "left" if pack_start else "right" + if pad: + if not isinstance(pad, Size._Base): + pad = Size.from_any(pad, fraction_ref=self._xref) + self.append_size(pos, pad) + if not isinstance(size, Size._Base): + size = Size.from_any(size, fraction_ref=self._xref) + self.append_size(pos, size) + locator = self.new_locator( + nx=0 if pack_start else len(self._horizontal) - 1, + ny=self._yrefindex) + ax = self._get_new_axes(**kwargs) + ax.set_axes_locator(locator) + return ax + + def new_vertical(self, size, pad=None, pack_start=False, **kwargs): + """ + Helper method for ``append_axes("top")`` and ``append_axes("bottom")``. + + See the documentation of `append_axes` for more details. + + :meta private: + """ + if pad is None: + pad = mpl.rcParams["figure.subplot.hspace"] * self._yref + pos = "bottom" if pack_start else "top" + if pad: + if not isinstance(pad, Size._Base): + pad = Size.from_any(pad, fraction_ref=self._yref) + self.append_size(pos, pad) + if not isinstance(size, Size._Base): + size = Size.from_any(size, fraction_ref=self._yref) + self.append_size(pos, size) + locator = self.new_locator( + nx=self._xrefindex, + ny=0 if pack_start else len(self._vertical) - 1) + ax = self._get_new_axes(**kwargs) + ax.set_axes_locator(locator) + return ax + + def append_axes(self, position, size, pad=None, *, axes_class=None, + **kwargs): + """ + Add a new axes on a given side of the main axes. + + Parameters + ---------- + position : {"left", "right", "bottom", "top"} + Where the new axes is positioned relative to the main axes. + size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str + The axes width or height. float or str arguments are interpreted + as ``axes_size.from_any(size, AxesX())`` for left or + right axes, and likewise with ``AxesY`` for bottom or top axes. + pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str + Padding between the axes. float or str arguments are interpreted + as for *size*. Defaults to :rc:`figure.subplot.wspace` times the + main Axes width (left or right axes) or :rc:`figure.subplot.hspace` + times the main Axes height (bottom or top axes). + axes_class : subclass type of `~.axes.Axes`, optional + The type of the new axes. Defaults to the type of the main axes. + **kwargs + All extra keywords arguments are passed to the created axes. + """ + create_axes, pack_start = _api.check_getitem({ + "left": (self.new_horizontal, True), + "right": (self.new_horizontal, False), + "bottom": (self.new_vertical, True), + "top": (self.new_vertical, False), + }, position=position) + ax = create_axes( + size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs) + self._fig.add_axes(ax) + return ax + + def get_aspect(self): + if self._aspect is None: + aspect = self._axes.get_aspect() + if aspect == "auto": + return False + else: + return True + else: + return self._aspect + + def get_position(self): + if self._pos is None: + bbox = self._axes.get_position(original=True) + return bbox.bounds + else: + return self._pos + + def get_anchor(self): + if self._anchor is None: + return self._axes.get_anchor() + else: + return self._anchor + + def get_subplotspec(self): + return self._axes.get_subplotspec() + + +# Helper for HBoxDivider/VBoxDivider. +# The variable names are written for a horizontal layout, but the calculations +# work identically for vertical layouts. +def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor): + + total_width = fig_w * w + max_height = fig_h * h + + # Determine the k factors. + n = len(equal_heights) + eq_rels, eq_abss = equal_heights.T + sm_rels, sm_abss = summed_widths.T + A = np.diag([*eq_rels, 0]) + A[:n, -1] = -1 + A[-1, :-1] = sm_rels + B = [*(-eq_abss), total_width - sm_abss.sum()] + # A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that + # eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height + # sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width + # (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.) + *karray, height = np.linalg.solve(A, B) + if height > max_height: # Additionally, upper-bound the height. + karray = (max_height - eq_abss) / eq_rels + + # Compute the offsets corresponding to these factors. + ox = np.cumsum([0, *(sm_rels * karray + sm_abss)]) + ww = (ox[-1] - ox[0]) / fig_w + h0_rel, h0_abs = equal_heights[0] + hh = (karray[0]*h0_rel + h0_abs) / fig_h + pb = mtransforms.Bbox.from_bounds(x, y, w, h) + pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh) + x0, y0 = pb1.anchored(anchor, pb).p0 + + return x0, y0, ox, hh + + +class HBoxDivider(SubplotDivider): + """ + A `.SubplotDivider` for laying out axes horizontally, while ensuring that + they have equal heights. + + Examples + -------- + .. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py + """ + + def new_locator(self, nx, nx1=None): + """ + Create an axes locator callable for the specified cell. + + Parameters + ---------- + nx, nx1 : int + Integers specifying the column-position of the + cell. When *nx1* is None, a single *nx*-th column is + specified. Otherwise, location of columns spanning between *nx* + to *nx1* (but excluding *nx1*-th column) is specified. + """ + return super().new_locator(nx, 0, nx1, 0) + + def _locate(self, nx, ny, nx1, ny1, axes, renderer): + # docstring inherited + nx += self._xrefindex + nx1 += self._xrefindex + fig_w, fig_h = self._fig.bbox.size / self._fig.dpi + x, y, w, h = self.get_position_runtime(axes, renderer) + summed_ws = self.get_horizontal_sizes(renderer) + equal_hs = self.get_vertical_sizes(renderer) + x0, y0, ox, hh = _locate( + x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor()) + if nx1 is None: + nx1 = -1 + x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w + y1, h1 = y0, hh + return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) + + +class VBoxDivider(SubplotDivider): + """ + A `.SubplotDivider` for laying out axes vertically, while ensuring that + they have equal widths. + """ + + def new_locator(self, ny, ny1=None): + """ + Create an axes locator callable for the specified cell. + + Parameters + ---------- + ny, ny1 : int + Integers specifying the row-position of the + cell. When *ny1* is None, a single *ny*-th row is + specified. Otherwise, location of rows spanning between *ny* + to *ny1* (but excluding *ny1*-th row) is specified. + """ + return super().new_locator(0, ny, 0, ny1) + + def _locate(self, nx, ny, nx1, ny1, axes, renderer): + # docstring inherited + ny += self._yrefindex + ny1 += self._yrefindex + fig_w, fig_h = self._fig.bbox.size / self._fig.dpi + x, y, w, h = self.get_position_runtime(axes, renderer) + summed_hs = self.get_vertical_sizes(renderer) + equal_ws = self.get_horizontal_sizes(renderer) + y0, x0, oy, ww = _locate( + y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor()) + if ny1 is None: + ny1 = -1 + x1, w1 = x0, ww + y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h + return mtransforms.Bbox.from_bounds(x1, y1, w1, h1) + + +def make_axes_locatable(axes): + divider = AxesDivider(axes) + locator = divider.new_locator(nx=0, ny=0) + axes.set_axes_locator(locator) + + return divider + + +def make_axes_area_auto_adjustable( + ax, use_axes=None, pad=0.1, adjust_dirs=None): + """ + Add auto-adjustable padding around *ax* to take its decorations (title, + labels, ticks, ticklabels) into account during layout, using + `.Divider.add_auto_adjustable_area`. + + By default, padding is determined from the decorations of *ax*. + Pass *use_axes* to consider the decorations of other Axes instead. + """ + if adjust_dirs is None: + adjust_dirs = ["left", "right", "bottom", "top"] + divider = make_axes_locatable(ax) + if use_axes is None: + use_axes = ax + divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad, + adjust_dirs=adjust_dirs) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_grid.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_grid.py new file mode 100644 index 0000000000000000000000000000000000000000..20abf18ea79c32ccdfe678d81ad975e83fe4bc0b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_grid.py @@ -0,0 +1,563 @@ +from numbers import Number +import functools +from types import MethodType + +import numpy as np + +from matplotlib import _api, cbook +from matplotlib.gridspec import SubplotSpec + +from .axes_divider import Size, SubplotDivider, Divider +from .mpl_axes import Axes, SimpleAxisArtist + + +class CbarAxesBase: + def __init__(self, *args, orientation, **kwargs): + self.orientation = orientation + super().__init__(*args, **kwargs) + + def colorbar(self, mappable, **kwargs): + return self.get_figure(root=False).colorbar( + mappable, cax=self, location=self.orientation, **kwargs) + + +_cbaraxes_class_factory = cbook._make_class_factory(CbarAxesBase, "Cbar{}") + + +class Grid: + """ + A grid of Axes. + + In Matplotlib, the Axes location (and size) is specified in normalized + figure coordinates. This may not be ideal for images that needs to be + displayed with a given aspect ratio; for example, it is difficult to + display multiple images of a same size with some fixed padding between + them. AxesGrid can be used in such case. + + Attributes + ---------- + axes_all : list of Axes + A flat list of Axes. Note that you can also access this directly + from the grid. The following is equivalent :: + + grid[i] == grid.axes_all[i] + len(grid) == len(grid.axes_all) + + axes_column : list of list of Axes + A 2D list of Axes where the first index is the column. This results + in the usage pattern ``grid.axes_column[col][row]``. + axes_row : list of list of Axes + A 2D list of Axes where the first index is the row. This results + in the usage pattern ``grid.axes_row[row][col]``. + axes_llc : Axes + The Axes in the lower left corner. + ngrids : int + Number of Axes in the grid. + """ + + _defaultAxesClass = Axes + + def __init__(self, fig, + rect, + nrows_ncols, + ngrids=None, + direction="row", + axes_pad=0.02, + *, + share_all=False, + share_x=True, + share_y=True, + label_mode="L", + axes_class=None, + aspect=False, + ): + """ + Parameters + ---------- + fig : `.Figure` + The parent figure. + rect : (float, float, float, float), (int, int, int), int, or \ + `~.SubplotSpec` + The axes position, as a ``(left, bottom, width, height)`` tuple, + as a three-digit subplot position code (e.g., ``(1, 2, 1)`` or + ``121``), or as a `~.SubplotSpec`. + nrows_ncols : (int, int) + Number of rows and columns in the grid. + ngrids : int or None, default: None + If not None, only the first *ngrids* axes in the grid are created. + direction : {"row", "column"}, default: "row" + Whether axes are created in row-major ("row by row") or + column-major order ("column by column"). This also affects the + order in which axes are accessed using indexing (``grid[index]``). + axes_pad : float or (float, float), default: 0.02 + Padding or (horizontal padding, vertical padding) between axes, in + inches. + share_all : bool, default: False + Whether all axes share their x- and y-axis. Overrides *share_x* + and *share_y*. + share_x : bool, default: True + Whether all axes of a column share their x-axis. + share_y : bool, default: True + Whether all axes of a row share their y-axis. + label_mode : {"L", "1", "all", "keep"}, default: "L" + Determines which axes will get tick labels: + + - "L": All axes on the left column get vertical tick labels; + all axes on the bottom row get horizontal tick labels. + - "1": Only the bottom left axes is labelled. + - "all": All axes are labelled. + - "keep": Do not do anything. + + axes_class : subclass of `matplotlib.axes.Axes`, default: `.mpl_axes.Axes` + The type of Axes to create. + aspect : bool, default: False + Whether the axes aspect ratio follows the aspect ratio of the data + limits. + """ + self._nrows, self._ncols = nrows_ncols + + if ngrids is None: + ngrids = self._nrows * self._ncols + else: + if not 0 < ngrids <= self._nrows * self._ncols: + raise ValueError( + "ngrids must be positive and not larger than nrows*ncols") + + self.ngrids = ngrids + + self._horiz_pad_size, self._vert_pad_size = map( + Size.Fixed, np.broadcast_to(axes_pad, 2)) + + _api.check_in_list(["column", "row"], direction=direction) + self._direction = direction + + if axes_class is None: + axes_class = self._defaultAxesClass + elif isinstance(axes_class, (list, tuple)): + cls, kwargs = axes_class + axes_class = functools.partial(cls, **kwargs) + + kw = dict(horizontal=[], vertical=[], aspect=aspect) + if isinstance(rect, (Number, SubplotSpec)): + self._divider = SubplotDivider(fig, rect, **kw) + elif len(rect) == 3: + self._divider = SubplotDivider(fig, *rect, **kw) + elif len(rect) == 4: + self._divider = Divider(fig, rect, **kw) + else: + raise TypeError("Incorrect rect format") + + rect = self._divider.get_position() + + axes_array = np.full((self._nrows, self._ncols), None, dtype=object) + for i in range(self.ngrids): + col, row = self._get_col_row(i) + if share_all: + sharex = sharey = axes_array[0, 0] + else: + sharex = axes_array[0, col] if share_x else None + sharey = axes_array[row, 0] if share_y else None + axes_array[row, col] = axes_class( + fig, rect, sharex=sharex, sharey=sharey) + self.axes_all = axes_array.ravel( + order="C" if self._direction == "row" else "F").tolist() + self.axes_column = axes_array.T.tolist() + self.axes_row = axes_array.tolist() + self.axes_llc = self.axes_column[0][-1] + + self._init_locators() + + for ax in self.axes_all: + fig.add_axes(ax) + + self.set_label_mode(label_mode) + + def _init_locators(self): + self._divider.set_horizontal( + [Size.Scaled(1), self._horiz_pad_size] * (self._ncols-1) + [Size.Scaled(1)]) + self._divider.set_vertical( + [Size.Scaled(1), self._vert_pad_size] * (self._nrows-1) + [Size.Scaled(1)]) + for i in range(self.ngrids): + col, row = self._get_col_row(i) + self.axes_all[i].set_axes_locator( + self._divider.new_locator(nx=2 * col, ny=2 * (self._nrows - 1 - row))) + + def _get_col_row(self, n): + if self._direction == "column": + col, row = divmod(n, self._nrows) + else: + row, col = divmod(n, self._ncols) + + return col, row + + # Good to propagate __len__ if we have __getitem__ + def __len__(self): + return len(self.axes_all) + + def __getitem__(self, i): + return self.axes_all[i] + + def get_geometry(self): + """ + Return the number of rows and columns of the grid as (nrows, ncols). + """ + return self._nrows, self._ncols + + def set_axes_pad(self, axes_pad): + """ + Set the padding between the axes. + + Parameters + ---------- + axes_pad : (float, float) + The padding (horizontal pad, vertical pad) in inches. + """ + self._horiz_pad_size.fixed_size = axes_pad[0] + self._vert_pad_size.fixed_size = axes_pad[1] + + def get_axes_pad(self): + """ + Return the axes padding. + + Returns + ------- + hpad, vpad + Padding (horizontal pad, vertical pad) in inches. + """ + return (self._horiz_pad_size.fixed_size, + self._vert_pad_size.fixed_size) + + def set_aspect(self, aspect): + """Set the aspect of the SubplotDivider.""" + self._divider.set_aspect(aspect) + + def get_aspect(self): + """Return the aspect of the SubplotDivider.""" + return self._divider.get_aspect() + + def set_label_mode(self, mode): + """ + Define which axes have tick labels. + + Parameters + ---------- + mode : {"L", "1", "all", "keep"} + The label mode: + + - "L": All axes on the left column get vertical tick labels; + all axes on the bottom row get horizontal tick labels. + - "1": Only the bottom left axes is labelled. + - "all": All axes are labelled. + - "keep": Do not do anything. + """ + _api.check_in_list(["all", "L", "1", "keep"], mode=mode) + is_last_row, is_first_col = ( + np.mgrid[:self._nrows, :self._ncols] == [[[self._nrows - 1]], [[0]]]) + if mode == "all": + bottom = left = np.full((self._nrows, self._ncols), True) + elif mode == "L": + bottom = is_last_row + left = is_first_col + elif mode == "1": + bottom = left = is_last_row & is_first_col + else: + return + for i in range(self._nrows): + for j in range(self._ncols): + ax = self.axes_row[i][j] + if isinstance(ax.axis, MethodType): + bottom_axis = SimpleAxisArtist(ax.xaxis, 1, ax.spines["bottom"]) + left_axis = SimpleAxisArtist(ax.yaxis, 1, ax.spines["left"]) + else: + bottom_axis = ax.axis["bottom"] + left_axis = ax.axis["left"] + bottom_axis.toggle(ticklabels=bottom[i, j], label=bottom[i, j]) + left_axis.toggle(ticklabels=left[i, j], label=left[i, j]) + + def get_divider(self): + return self._divider + + def set_axes_locator(self, locator): + self._divider.set_locator(locator) + + def get_axes_locator(self): + return self._divider.get_locator() + + +class ImageGrid(Grid): + """ + A grid of Axes for Image display. + + This class is a specialization of `~.axes_grid1.axes_grid.Grid` for displaying a + grid of images. In particular, it forces all axes in a column to share their x-axis + and all axes in a row to share their y-axis. It further provides helpers to add + colorbars to some or all axes. + """ + + def __init__(self, fig, + rect, + nrows_ncols, + ngrids=None, + direction="row", + axes_pad=0.02, + *, + share_all=False, + aspect=True, + label_mode="L", + cbar_mode=None, + cbar_location="right", + cbar_pad=None, + cbar_size="5%", + cbar_set_cax=True, + axes_class=None, + ): + """ + Parameters + ---------- + fig : `.Figure` + The parent figure. + rect : (float, float, float, float) or int + The axes position, as a ``(left, bottom, width, height)`` tuple or + as a three-digit subplot position code (e.g., "121"). + nrows_ncols : (int, int) + Number of rows and columns in the grid. + ngrids : int or None, default: None + If not None, only the first *ngrids* axes in the grid are created. + direction : {"row", "column"}, default: "row" + Whether axes are created in row-major ("row by row") or + column-major order ("column by column"). This also affects the + order in which axes are accessed using indexing (``grid[index]``). + axes_pad : float or (float, float), default: 0.02in + Padding or (horizontal padding, vertical padding) between axes, in + inches. + share_all : bool, default: False + Whether all axes share their x- and y-axis. Note that in any case, + all axes in a column share their x-axis and all axes in a row share + their y-axis. + aspect : bool, default: True + Whether the axes aspect ratio follows the aspect ratio of the data + limits. + label_mode : {"L", "1", "all"}, default: "L" + Determines which axes will get tick labels: + + - "L": All axes on the left column get vertical tick labels; + all axes on the bottom row get horizontal tick labels. + - "1": Only the bottom left axes is labelled. + - "all": all axes are labelled. + + cbar_mode : {"each", "single", "edge", None}, default: None + Whether to create a colorbar for "each" axes, a "single" colorbar + for the entire grid, colorbars only for axes on the "edge" + determined by *cbar_location*, or no colorbars. The colorbars are + stored in the :attr:`cbar_axes` attribute. + cbar_location : {"left", "right", "bottom", "top"}, default: "right" + cbar_pad : float, default: None + Padding between the image axes and the colorbar axes. + + .. versionchanged:: 3.10 + ``cbar_mode="single"`` no longer adds *axes_pad* between the axes + and the colorbar if the *cbar_location* is "left" or "bottom". + + cbar_size : size specification (see `.Size.from_any`), default: "5%" + Colorbar size. + cbar_set_cax : bool, default: True + If True, each axes in the grid has a *cax* attribute that is bound + to associated *cbar_axes*. + axes_class : subclass of `matplotlib.axes.Axes`, default: None + """ + _api.check_in_list(["each", "single", "edge", None], + cbar_mode=cbar_mode) + _api.check_in_list(["left", "right", "bottom", "top"], + cbar_location=cbar_location) + self._colorbar_mode = cbar_mode + self._colorbar_location = cbar_location + self._colorbar_pad = cbar_pad + self._colorbar_size = cbar_size + # The colorbar axes are created in _init_locators(). + + super().__init__( + fig, rect, nrows_ncols, ngrids, + direction=direction, axes_pad=axes_pad, + share_all=share_all, share_x=True, share_y=True, aspect=aspect, + label_mode=label_mode, axes_class=axes_class) + + for ax in self.cbar_axes: + fig.add_axes(ax) + + if cbar_set_cax: + if self._colorbar_mode == "single": + for ax in self.axes_all: + ax.cax = self.cbar_axes[0] + elif self._colorbar_mode == "edge": + for index, ax in enumerate(self.axes_all): + col, row = self._get_col_row(index) + if self._colorbar_location in ("left", "right"): + ax.cax = self.cbar_axes[row] + else: + ax.cax = self.cbar_axes[col] + else: + for ax, cax in zip(self.axes_all, self.cbar_axes): + ax.cax = cax + + def _init_locators(self): + # Slightly abusing this method to inject colorbar creation into init. + + if self._colorbar_pad is None: + # horizontal or vertical arrangement? + if self._colorbar_location in ("left", "right"): + self._colorbar_pad = self._horiz_pad_size.fixed_size + else: + self._colorbar_pad = self._vert_pad_size.fixed_size + self.cbar_axes = [ + _cbaraxes_class_factory(self._defaultAxesClass)( + self.axes_all[0].get_figure(root=False), self._divider.get_position(), + orientation=self._colorbar_location) + for _ in range(self.ngrids)] + + cb_mode = self._colorbar_mode + cb_location = self._colorbar_location + + h = [] + v = [] + + h_ax_pos = [] + h_cb_pos = [] + if cb_mode == "single" and cb_location in ("left", "bottom"): + if cb_location == "left": + sz = self._nrows * Size.AxesX(self.axes_llc) + h.append(Size.from_any(self._colorbar_size, sz)) + h.append(Size.from_any(self._colorbar_pad, sz)) + locator = self._divider.new_locator(nx=0, ny=0, ny1=-1) + elif cb_location == "bottom": + sz = self._ncols * Size.AxesY(self.axes_llc) + v.append(Size.from_any(self._colorbar_size, sz)) + v.append(Size.from_any(self._colorbar_pad, sz)) + locator = self._divider.new_locator(nx=0, nx1=-1, ny=0) + for i in range(self.ngrids): + self.cbar_axes[i].set_visible(False) + self.cbar_axes[0].set_axes_locator(locator) + self.cbar_axes[0].set_visible(True) + + for col, ax in enumerate(self.axes_row[0]): + if col != 0: + h.append(self._horiz_pad_size) + + if ax: + sz = Size.AxesX(ax, aspect="axes", ref_ax=self.axes_all[0]) + else: + sz = Size.AxesX(self.axes_all[0], + aspect="axes", ref_ax=self.axes_all[0]) + + if (cb_location == "left" + and (cb_mode == "each" + or (cb_mode == "edge" and col == 0))): + h_cb_pos.append(len(h)) + h.append(Size.from_any(self._colorbar_size, sz)) + h.append(Size.from_any(self._colorbar_pad, sz)) + + h_ax_pos.append(len(h)) + h.append(sz) + + if (cb_location == "right" + and (cb_mode == "each" + or (cb_mode == "edge" and col == self._ncols - 1))): + h.append(Size.from_any(self._colorbar_pad, sz)) + h_cb_pos.append(len(h)) + h.append(Size.from_any(self._colorbar_size, sz)) + + v_ax_pos = [] + v_cb_pos = [] + for row, ax in enumerate(self.axes_column[0][::-1]): + if row != 0: + v.append(self._vert_pad_size) + + if ax: + sz = Size.AxesY(ax, aspect="axes", ref_ax=self.axes_all[0]) + else: + sz = Size.AxesY(self.axes_all[0], + aspect="axes", ref_ax=self.axes_all[0]) + + if (cb_location == "bottom" + and (cb_mode == "each" + or (cb_mode == "edge" and row == 0))): + v_cb_pos.append(len(v)) + v.append(Size.from_any(self._colorbar_size, sz)) + v.append(Size.from_any(self._colorbar_pad, sz)) + + v_ax_pos.append(len(v)) + v.append(sz) + + if (cb_location == "top" + and (cb_mode == "each" + or (cb_mode == "edge" and row == self._nrows - 1))): + v.append(Size.from_any(self._colorbar_pad, sz)) + v_cb_pos.append(len(v)) + v.append(Size.from_any(self._colorbar_size, sz)) + + for i in range(self.ngrids): + col, row = self._get_col_row(i) + locator = self._divider.new_locator(nx=h_ax_pos[col], + ny=v_ax_pos[self._nrows-1-row]) + self.axes_all[i].set_axes_locator(locator) + + if cb_mode == "each": + if cb_location in ("right", "left"): + locator = self._divider.new_locator( + nx=h_cb_pos[col], ny=v_ax_pos[self._nrows - 1 - row]) + + elif cb_location in ("top", "bottom"): + locator = self._divider.new_locator( + nx=h_ax_pos[col], ny=v_cb_pos[self._nrows - 1 - row]) + + self.cbar_axes[i].set_axes_locator(locator) + elif cb_mode == "edge": + if (cb_location == "left" and col == 0 + or cb_location == "right" and col == self._ncols - 1): + locator = self._divider.new_locator( + nx=h_cb_pos[0], ny=v_ax_pos[self._nrows - 1 - row]) + self.cbar_axes[row].set_axes_locator(locator) + elif (cb_location == "bottom" and row == self._nrows - 1 + or cb_location == "top" and row == 0): + locator = self._divider.new_locator(nx=h_ax_pos[col], + ny=v_cb_pos[0]) + self.cbar_axes[col].set_axes_locator(locator) + + if cb_mode == "single": + if cb_location == "right": + sz = self._nrows * Size.AxesX(self.axes_llc) + h.append(Size.from_any(self._colorbar_pad, sz)) + h.append(Size.from_any(self._colorbar_size, sz)) + locator = self._divider.new_locator(nx=-2, ny=0, ny1=-1) + elif cb_location == "top": + sz = self._ncols * Size.AxesY(self.axes_llc) + v.append(Size.from_any(self._colorbar_pad, sz)) + v.append(Size.from_any(self._colorbar_size, sz)) + locator = self._divider.new_locator(nx=0, nx1=-1, ny=-2) + if cb_location in ("right", "top"): + for i in range(self.ngrids): + self.cbar_axes[i].set_visible(False) + self.cbar_axes[0].set_axes_locator(locator) + self.cbar_axes[0].set_visible(True) + elif cb_mode == "each": + for i in range(self.ngrids): + self.cbar_axes[i].set_visible(True) + elif cb_mode == "edge": + if cb_location in ("right", "left"): + count = self._nrows + else: + count = self._ncols + for i in range(count): + self.cbar_axes[i].set_visible(True) + for j in range(i + 1, self.ngrids): + self.cbar_axes[j].set_visible(False) + else: + for i in range(self.ngrids): + self.cbar_axes[i].set_visible(False) + self.cbar_axes[i].set_position([1., 1., 0.001, 0.001], + which="active") + + self._divider.set_horizontal(h) + self._divider.set_vertical(v) + + +AxesGrid = ImageGrid diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py new file mode 100644 index 0000000000000000000000000000000000000000..52fd707e87043eb17929a84c53da2741722ce002 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py @@ -0,0 +1,157 @@ +from types import MethodType + +import numpy as np + +from .axes_divider import make_axes_locatable, Size +from .mpl_axes import Axes, SimpleAxisArtist + + +def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs): + """ + Parameters + ---------- + ax : `~matplotlib.axes.Axes` + Axes instance to create the RGB Axes in. + pad : float, optional + Fraction of the Axes height to pad. + axes_class : `matplotlib.axes.Axes` or None, optional + Axes class to use for the R, G, and B Axes. If None, use + the same class as *ax*. + **kwargs + Forwarded to *axes_class* init for the R, G, and B Axes. + """ + + divider = make_axes_locatable(ax) + + pad_size = pad * Size.AxesY(ax) + + xsize = ((1-2*pad)/3) * Size.AxesX(ax) + ysize = ((1-2*pad)/3) * Size.AxesY(ax) + + divider.set_horizontal([Size.AxesX(ax), pad_size, xsize]) + divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize]) + + ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1)) + + ax_rgb = [] + if axes_class is None: + axes_class = type(ax) + + for ny in [4, 2, 0]: + ax1 = axes_class(ax.get_figure(), ax.get_position(original=True), + sharex=ax, sharey=ax, **kwargs) + locator = divider.new_locator(nx=2, ny=ny) + ax1.set_axes_locator(locator) + for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels(): + t.set_visible(False) + try: + for axis in ax1.axis.values(): + axis.major_ticklabels.set_visible(False) + except AttributeError: + pass + + ax_rgb.append(ax1) + + fig = ax.get_figure() + for ax1 in ax_rgb: + fig.add_axes(ax1) + + return ax_rgb + + +class RGBAxes: + """ + 4-panel `~.Axes.imshow` (RGB, R, G, B). + + Layout:: + + ┌───────────────┬─────� + │ │ R │ + │ ├─────┤ + │ RGB │ G │ + │ ├─────┤ + │ │ B │ + └───────────────┴─────┘ + + Subclasses can override the ``_defaultAxesClass`` attribute. + By default RGBAxes uses `.mpl_axes.Axes`. + + Attributes + ---------- + RGB : ``_defaultAxesClass`` + The Axes object for the three-channel `~.Axes.imshow`. + R : ``_defaultAxesClass`` + The Axes object for the red channel `~.Axes.imshow`. + G : ``_defaultAxesClass`` + The Axes object for the green channel `~.Axes.imshow`. + B : ``_defaultAxesClass`` + The Axes object for the blue channel `~.Axes.imshow`. + """ + + _defaultAxesClass = Axes + + def __init__(self, *args, pad=0, **kwargs): + """ + Parameters + ---------- + pad : float, default: 0 + Fraction of the Axes height to put as padding. + axes_class : `~matplotlib.axes.Axes` + Axes class to use. If not provided, ``_defaultAxesClass`` is used. + *args + Forwarded to *axes_class* init for the RGB Axes + **kwargs + Forwarded to *axes_class* init for the RGB, R, G, and B Axes + """ + axes_class = kwargs.pop("axes_class", self._defaultAxesClass) + self.RGB = ax = axes_class(*args, **kwargs) + ax.get_figure().add_axes(ax) + self.R, self.G, self.B = make_rgb_axes( + ax, pad=pad, axes_class=axes_class, **kwargs) + # Set the line color and ticks for the axes. + for ax1 in [self.RGB, self.R, self.G, self.B]: + if isinstance(ax1.axis, MethodType): + ad = Axes.AxisDict(self) + ad.update( + bottom=SimpleAxisArtist(ax1.xaxis, 1, ax1.spines["bottom"]), + top=SimpleAxisArtist(ax1.xaxis, 2, ax1.spines["top"]), + left=SimpleAxisArtist(ax1.yaxis, 1, ax1.spines["left"]), + right=SimpleAxisArtist(ax1.yaxis, 2, ax1.spines["right"])) + else: + ad = ax1.axis + ad[:].line.set_color("w") + ad[:].major_ticks.set_markeredgecolor("w") + + def imshow_rgb(self, r, g, b, **kwargs): + """ + Create the four images {rgb, r, g, b}. + + Parameters + ---------- + r, g, b : array-like + The red, green, and blue arrays. + **kwargs + Forwarded to `~.Axes.imshow` calls for the four images. + + Returns + ------- + rgb : `~matplotlib.image.AxesImage` + r : `~matplotlib.image.AxesImage` + g : `~matplotlib.image.AxesImage` + b : `~matplotlib.image.AxesImage` + """ + if not (r.shape == g.shape == b.shape): + raise ValueError( + f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match') + RGB = np.dstack([r, g, b]) + R = np.zeros_like(RGB) + R[:, :, 0] = r + G = np.zeros_like(RGB) + G[:, :, 1] = g + B = np.zeros_like(RGB) + B[:, :, 2] = b + im_rgb = self.RGB.imshow(RGB, **kwargs) + im_r = self.R.imshow(R, **kwargs) + im_g = self.G.imshow(G, **kwargs) + im_b = self.B.imshow(B, **kwargs) + return im_rgb, im_r, im_g, im_b diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_size.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_size.py new file mode 100644 index 0000000000000000000000000000000000000000..86e5f70d9824392a8c49bce9a18aaf45cf6f0232 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/axes_size.py @@ -0,0 +1,271 @@ +""" +Provides classes of simple units that will be used with `.AxesDivider` +class (or others) to determine the size of each Axes. The unit +classes define `get_size` method that returns a tuple of two floats, +meaning relative and absolute sizes, respectively. + +Note that this class is nothing more than a simple tuple of two +floats. Take a look at the Divider class to see how these two +values are used. + +Once created, the unit classes can be modified by simple arithmetic +operations: addition /subtraction with another unit type or a real number and scaling +(multiplication or division) by a real number. +""" + +from numbers import Real + +from matplotlib import _api +from matplotlib.axes import Axes + + +class _Base: + def __rmul__(self, other): + return self * other + + def __mul__(self, other): + if not isinstance(other, Real): + return NotImplemented + return Fraction(other, self) + + def __div__(self, other): + return (1 / other) * self + + def __add__(self, other): + if isinstance(other, _Base): + return Add(self, other) + else: + return Add(self, Fixed(other)) + + def __neg__(self): + return -1 * self + + def __radd__(self, other): + # other cannot be a _Base instance, because A + B would trigger + # A.__add__(B) first. + return Add(self, Fixed(other)) + + def __sub__(self, other): + return self + (-other) + + def get_size(self, renderer): + """ + Return two-float tuple with relative and absolute sizes. + """ + raise NotImplementedError("Subclasses must implement") + + +class Add(_Base): + """ + Sum of two sizes. + """ + + def __init__(self, a, b): + self._a = a + self._b = b + + def get_size(self, renderer): + a_rel_size, a_abs_size = self._a.get_size(renderer) + b_rel_size, b_abs_size = self._b.get_size(renderer) + return a_rel_size + b_rel_size, a_abs_size + b_abs_size + + +class Fixed(_Base): + """ + Simple fixed size with absolute part = *fixed_size* and relative part = 0. + """ + + def __init__(self, fixed_size): + _api.check_isinstance(Real, fixed_size=fixed_size) + self.fixed_size = fixed_size + + def get_size(self, renderer): + rel_size = 0. + abs_size = self.fixed_size + return rel_size, abs_size + + +class Scaled(_Base): + """ + Simple scaled(?) size with absolute part = 0 and + relative part = *scalable_size*. + """ + + def __init__(self, scalable_size): + self._scalable_size = scalable_size + + def get_size(self, renderer): + rel_size = self._scalable_size + abs_size = 0. + return rel_size, abs_size + +Scalable = Scaled + + +def _get_axes_aspect(ax): + aspect = ax.get_aspect() + if aspect == "auto": + aspect = 1. + return aspect + + +class AxesX(_Base): + """ + Scaled size whose relative part corresponds to the data width + of the *axes* multiplied by the *aspect*. + """ + + def __init__(self, axes, aspect=1., ref_ax=None): + self._axes = axes + self._aspect = aspect + if aspect == "axes" and ref_ax is None: + raise ValueError("ref_ax must be set when aspect='axes'") + self._ref_ax = ref_ax + + def get_size(self, renderer): + l1, l2 = self._axes.get_xlim() + if self._aspect == "axes": + ref_aspect = _get_axes_aspect(self._ref_ax) + aspect = ref_aspect / _get_axes_aspect(self._axes) + else: + aspect = self._aspect + + rel_size = abs(l2-l1)*aspect + abs_size = 0. + return rel_size, abs_size + + +class AxesY(_Base): + """ + Scaled size whose relative part corresponds to the data height + of the *axes* multiplied by the *aspect*. + """ + + def __init__(self, axes, aspect=1., ref_ax=None): + self._axes = axes + self._aspect = aspect + if aspect == "axes" and ref_ax is None: + raise ValueError("ref_ax must be set when aspect='axes'") + self._ref_ax = ref_ax + + def get_size(self, renderer): + l1, l2 = self._axes.get_ylim() + + if self._aspect == "axes": + ref_aspect = _get_axes_aspect(self._ref_ax) + aspect = _get_axes_aspect(self._axes) + else: + aspect = self._aspect + + rel_size = abs(l2-l1)*aspect + abs_size = 0. + return rel_size, abs_size + + +class MaxExtent(_Base): + """ + Size whose absolute part is either the largest width or the largest height + of the given *artist_list*. + """ + + def __init__(self, artist_list, w_or_h): + self._artist_list = artist_list + _api.check_in_list(["width", "height"], w_or_h=w_or_h) + self._w_or_h = w_or_h + + def add_artist(self, a): + self._artist_list.append(a) + + def get_size(self, renderer): + rel_size = 0. + extent_list = [ + getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi + for a in self._artist_list] + abs_size = max(extent_list, default=0) + return rel_size, abs_size + + +class MaxWidth(MaxExtent): + """ + Size whose absolute part is the largest width of the given *artist_list*. + """ + + def __init__(self, artist_list): + super().__init__(artist_list, "width") + + +class MaxHeight(MaxExtent): + """ + Size whose absolute part is the largest height of the given *artist_list*. + """ + + def __init__(self, artist_list): + super().__init__(artist_list, "height") + + +class Fraction(_Base): + """ + An instance whose size is a *fraction* of the *ref_size*. + + >>> s = Fraction(0.3, AxesX(ax)) + """ + + def __init__(self, fraction, ref_size): + _api.check_isinstance(Real, fraction=fraction) + self._fraction_ref = ref_size + self._fraction = fraction + + def get_size(self, renderer): + if self._fraction_ref is None: + return self._fraction, 0. + else: + r, a = self._fraction_ref.get_size(renderer) + rel_size = r*self._fraction + abs_size = a*self._fraction + return rel_size, abs_size + + +def from_any(size, fraction_ref=None): + """ + Create a Fixed unit when the first argument is a float, or a + Fraction unit if that is a string that ends with %. The second + argument is only meaningful when Fraction unit is created. + + >>> from mpl_toolkits.axes_grid1.axes_size import from_any + >>> a = from_any(1.2) # => Fixed(1.2) + >>> from_any("50%", a) # => Fraction(0.5, a) + """ + if isinstance(size, Real): + return Fixed(size) + elif isinstance(size, str): + if size[-1] == "%": + return Fraction(float(size[:-1]) / 100, fraction_ref) + raise ValueError("Unknown format") + + +class _AxesDecorationsSize(_Base): + """ + Fixed size, corresponding to the size of decorations on a given Axes side. + """ + + _get_size_map = { + "left": lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin, + "right": lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax, + "bottom": lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin, + "top": lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax, + } + + def __init__(self, ax, direction): + _api.check_in_list(self._get_size_map, direction=direction) + self._direction = direction + self._ax_list = [ax] if isinstance(ax, Axes) else ax + + def get_size(self, renderer): + sz = max([ + self._get_size_map[self._direction]( + ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox) + for ax in self._ax_list]) + dpi = renderer.points_to_pixels(72) + abs_size = sz / dpi + rel_size = 0 + return rel_size, abs_size diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/inset_locator.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/inset_locator.py new file mode 100644 index 0000000000000000000000000000000000000000..52fe6efc061856bd33939c31efe404f619faf033 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/inset_locator.py @@ -0,0 +1,519 @@ +""" +A collection of functions and objects for creating or placing inset axes. +""" + +from matplotlib import _api, _docstring +from matplotlib.offsetbox import AnchoredOffsetbox +from matplotlib.patches import Patch, Rectangle +from matplotlib.path import Path +from matplotlib.transforms import Bbox +from matplotlib.transforms import IdentityTransform, TransformedBbox + +from . import axes_size as Size +from .parasite_axes import HostAxes + + +class AnchoredLocatorBase(AnchoredOffsetbox): + def __init__(self, bbox_to_anchor, offsetbox, loc, + borderpad=0.5, bbox_transform=None): + super().__init__( + loc, pad=0., child=None, borderpad=borderpad, + bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform + ) + + def draw(self, renderer): + raise RuntimeError("No draw method should be called") + + def __call__(self, ax, renderer): + fig = ax.get_figure(root=False) + if renderer is None: + renderer = fig._get_renderer() + self.axes = ax + bbox = self.get_window_extent(renderer) + px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer) + bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height) + tr = fig.transSubfigure.inverted() + return TransformedBbox(bbox_canvas, tr) + + +class AnchoredSizeLocator(AnchoredLocatorBase): + def __init__(self, bbox_to_anchor, x_size, y_size, loc, + borderpad=0.5, bbox_transform=None): + super().__init__( + bbox_to_anchor, None, loc, + borderpad=borderpad, bbox_transform=bbox_transform + ) + + self.x_size = Size.from_any(x_size) + self.y_size = Size.from_any(y_size) + + def get_bbox(self, renderer): + bbox = self.get_bbox_to_anchor() + dpi = renderer.points_to_pixels(72.) + + r, a = self.x_size.get_size(renderer) + width = bbox.width * r + a * dpi + r, a = self.y_size.get_size(renderer) + height = bbox.height * r + a * dpi + + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + pad = self.pad * fontsize + + return Bbox.from_bounds(0, 0, width, height).padded(pad) + + +class AnchoredZoomLocator(AnchoredLocatorBase): + def __init__(self, parent_axes, zoom, loc, + borderpad=0.5, + bbox_to_anchor=None, + bbox_transform=None): + self.parent_axes = parent_axes + self.zoom = zoom + if bbox_to_anchor is None: + bbox_to_anchor = parent_axes.bbox + super().__init__( + bbox_to_anchor, None, loc, borderpad=borderpad, + bbox_transform=bbox_transform) + + def get_bbox(self, renderer): + bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim) + fontsize = renderer.points_to_pixels(self.prop.get_size_in_points()) + pad = self.pad * fontsize + return ( + Bbox.from_bounds( + 0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom)) + .padded(pad)) + + +class BboxPatch(Patch): + @_docstring.interpd + def __init__(self, bbox, **kwargs): + """ + Patch showing the shape bounded by a Bbox. + + Parameters + ---------- + bbox : `~matplotlib.transforms.Bbox` + Bbox to use for the extents of this patch. + + **kwargs + Patch properties. Valid arguments include: + + %(Patch:kwdoc)s + """ + if "transform" in kwargs: + raise ValueError("transform should not be set") + + kwargs["transform"] = IdentityTransform() + super().__init__(**kwargs) + self.bbox = bbox + + def get_path(self): + # docstring inherited + x0, y0, x1, y1 = self.bbox.extents + return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) + + +class BboxConnector(Patch): + @staticmethod + def get_bbox_edge_pos(bbox, loc): + """ + Return the ``(x, y)`` coordinates of corner *loc* of *bbox*; parameters + behave as documented for the `.BboxConnector` constructor. + """ + x0, y0, x1, y1 = bbox.extents + if loc == 1: + return x1, y1 + elif loc == 2: + return x0, y1 + elif loc == 3: + return x0, y0 + elif loc == 4: + return x1, y0 + + @staticmethod + def connect_bbox(bbox1, bbox2, loc1, loc2=None): + """ + Construct a `.Path` connecting corner *loc1* of *bbox1* to corner + *loc2* of *bbox2*, where parameters behave as documented as for the + `.BboxConnector` constructor. + """ + if isinstance(bbox1, Rectangle): + bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform()) + if isinstance(bbox2, Rectangle): + bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform()) + if loc2 is None: + loc2 = loc1 + x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1) + x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2) + return Path([[x1, y1], [x2, y2]]) + + @_docstring.interpd + def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs): + """ + Connect two bboxes with a straight line. + + Parameters + ---------- + bbox1, bbox2 : `~matplotlib.transforms.Bbox` + Bounding boxes to connect. + + loc1, loc2 : {1, 2, 3, 4} + Corner of *bbox1* and *bbox2* to draw the line. Valid values are:: + + 'upper right' : 1, + 'upper left' : 2, + 'lower left' : 3, + 'lower right' : 4 + + *loc2* is optional and defaults to *loc1*. + + **kwargs + Patch properties for the line drawn. Valid arguments include: + + %(Patch:kwdoc)s + """ + if "transform" in kwargs: + raise ValueError("transform should not be set") + + kwargs["transform"] = IdentityTransform() + kwargs.setdefault( + "fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs))) + super().__init__(**kwargs) + self.bbox1 = bbox1 + self.bbox2 = bbox2 + self.loc1 = loc1 + self.loc2 = loc2 + + def get_path(self): + # docstring inherited + return self.connect_bbox(self.bbox1, self.bbox2, + self.loc1, self.loc2) + + +class BboxConnectorPatch(BboxConnector): + @_docstring.interpd + def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs): + """ + Connect two bboxes with a quadrilateral. + + The quadrilateral is specified by two lines that start and end at + corners of the bboxes. The four sides of the quadrilateral are defined + by the two lines given, the line between the two corners specified in + *bbox1* and the line between the two corners specified in *bbox2*. + + Parameters + ---------- + bbox1, bbox2 : `~matplotlib.transforms.Bbox` + Bounding boxes to connect. + + loc1a, loc2a, loc1b, loc2b : {1, 2, 3, 4} + The first line connects corners *loc1a* of *bbox1* and *loc2a* of + *bbox2*; the second line connects corners *loc1b* of *bbox1* and + *loc2b* of *bbox2*. Valid values are:: + + 'upper right' : 1, + 'upper left' : 2, + 'lower left' : 3, + 'lower right' : 4 + + **kwargs + Patch properties for the line drawn: + + %(Patch:kwdoc)s + """ + if "transform" in kwargs: + raise ValueError("transform should not be set") + super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs) + self.loc1b = loc1b + self.loc2b = loc2b + + def get_path(self): + # docstring inherited + path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2) + path2 = self.connect_bbox(self.bbox2, self.bbox1, + self.loc2b, self.loc1b) + path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]] + return Path(path_merged) + + +def _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator): + """Helper function to add an inset axes and disable navigation in it.""" + if axes_class is None: + axes_class = HostAxes + if axes_kwargs is None: + axes_kwargs = {} + fig = parent_axes.get_figure(root=False) + inset_axes = axes_class( + fig, parent_axes.get_position(), + **{"navigate": False, **axes_kwargs, "axes_locator": axes_locator}) + return fig.add_axes(inset_axes) + + +@_docstring.interpd +def inset_axes(parent_axes, width, height, loc='upper right', + bbox_to_anchor=None, bbox_transform=None, + axes_class=None, axes_kwargs=None, + borderpad=0.5): + """ + Create an inset axes with a given width and height. + + Both sizes used can be specified either in inches or percentage. + For example,:: + + inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left') + + creates in inset axes in the lower left corner of *parent_axes* which spans + over 30%% in height and 40%% in width of the *parent_axes*. Since the usage + of `.inset_axes` may become slightly tricky when exceeding such standard + cases, it is recommended to read :doc:`the examples + `. + + Notes + ----- + The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted + differently from that of legend. The value of bbox_to_anchor + (or the return value of its get_points method; the default is + *parent_axes.bbox*) is transformed by the bbox_transform (the default + is Identity transform) and then interpreted as points in the pixel + coordinate (which is dpi dependent). + + Thus, following three calls are identical and creates an inset axes + with respect to the *parent_axes*:: + + axins = inset_axes(parent_axes, "30%%", "40%%") + axins = inset_axes(parent_axes, "30%%", "40%%", + bbox_to_anchor=parent_axes.bbox) + axins = inset_axes(parent_axes, "30%%", "40%%", + bbox_to_anchor=(0, 0, 1, 1), + bbox_transform=parent_axes.transAxes) + + Parameters + ---------- + parent_axes : `matplotlib.axes.Axes` + Axes to place the inset axes. + + width, height : float or str + Size of the inset axes to create. If a float is provided, it is + the size in inches, e.g. *width=1.3*. If a string is provided, it is + the size in relative units, e.g. *width='40%%'*. By default, i.e. if + neither *bbox_to_anchor* nor *bbox_transform* are specified, those + are relative to the parent_axes. Otherwise, they are to be understood + relative to the bounding box provided via *bbox_to_anchor*. + + loc : str, default: 'upper right' + Location to place the inset axes. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + + bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional + Bbox that the inset axes will be anchored to. If None, + a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set + to *parent_axes.transAxes* or *parent_axes.figure.transFigure*. + Otherwise, *parent_axes.bbox* is used. If a tuple, can be either + [left, bottom, width, height], or [left, bottom]. + If the kwargs *width* and/or *height* are specified in relative units, + the 2-tuple [left, bottom] cannot be used. Note that, + unless *bbox_transform* is set, the units of the bounding box + are interpreted in the pixel coordinate. When using *bbox_to_anchor* + with tuple, it almost always makes sense to also specify + a *bbox_transform*. This might often be the axes transform + *parent_axes.transAxes*. + + bbox_transform : `~matplotlib.transforms.Transform`, optional + Transformation for the bbox that contains the inset axes. + If None, a `.transforms.IdentityTransform` is used. The value + of *bbox_to_anchor* (or the return value of its get_points method) + is transformed by the *bbox_transform* and then interpreted + as points in the pixel coordinate (which is dpi dependent). + You may provide *bbox_to_anchor* in some normalized coordinate, + and give an appropriate transform (e.g., *parent_axes.transAxes*). + + axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes` + The type of the newly created inset axes. + + axes_kwargs : dict, optional + Keyword arguments to pass to the constructor of the inset axes. + Valid arguments include: + + %(Axes:kwdoc)s + + borderpad : float, default: 0.5 + Padding between inset axes and the bbox_to_anchor. + The units are axes font size, i.e. for a default font size of 10 points + *borderpad = 0.5* is equivalent to a padding of 5 points. + + Returns + ------- + inset_axes : *axes_class* + Inset axes object created. + """ + + if (bbox_transform in [parent_axes.transAxes, + parent_axes.get_figure(root=False).transFigure] + and bbox_to_anchor is None): + _api.warn_external("Using the axes or figure transform requires a " + "bounding box in the respective coordinates. " + "Using bbox_to_anchor=(0, 0, 1, 1) now.") + bbox_to_anchor = (0, 0, 1, 1) + if bbox_to_anchor is None: + bbox_to_anchor = parent_axes.bbox + if (isinstance(bbox_to_anchor, tuple) and + (isinstance(width, str) or isinstance(height, str))): + if len(bbox_to_anchor) != 4: + raise ValueError("Using relative units for width or height " + "requires to provide a 4-tuple or a " + "`Bbox` instance to `bbox_to_anchor.") + return _add_inset_axes( + parent_axes, axes_class, axes_kwargs, + AnchoredSizeLocator( + bbox_to_anchor, width, height, loc=loc, + bbox_transform=bbox_transform, borderpad=borderpad)) + + +@_docstring.interpd +def zoomed_inset_axes(parent_axes, zoom, loc='upper right', + bbox_to_anchor=None, bbox_transform=None, + axes_class=None, axes_kwargs=None, + borderpad=0.5): + """ + Create an anchored inset axes by scaling a parent axes. For usage, also see + :doc:`the examples `. + + Parameters + ---------- + parent_axes : `~matplotlib.axes.Axes` + Axes to place the inset axes. + + zoom : float + Scaling factor of the data axes. *zoom* > 1 will enlarge the + coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the + coordinates (i.e., "zoomed out"). + + loc : str, default: 'upper right' + Location to place the inset axes. Valid locations are + 'upper left', 'upper center', 'upper right', + 'center left', 'center', 'center right', + 'lower left', 'lower center', 'lower right'. + For backward compatibility, numeric values are accepted as well. + See the parameter *loc* of `.Legend` for details. + + bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional + Bbox that the inset axes will be anchored to. If None, + *parent_axes.bbox* is used. If a tuple, can be either + [left, bottom, width, height], or [left, bottom]. + If the kwargs *width* and/or *height* are specified in relative units, + the 2-tuple [left, bottom] cannot be used. Note that + the units of the bounding box are determined through the transform + in use. When using *bbox_to_anchor* it almost always makes sense to + also specify a *bbox_transform*. This might often be the axes transform + *parent_axes.transAxes*. + + bbox_transform : `~matplotlib.transforms.Transform`, optional + Transformation for the bbox that contains the inset axes. + If None, a `.transforms.IdentityTransform` is used (i.e. pixel + coordinates). This is useful when not providing any argument to + *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes + sense to also specify a *bbox_transform*. This might often be the + axes transform *parent_axes.transAxes*. Inversely, when specifying + the axes- or figure-transform here, be aware that not specifying + *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are + in display (pixel) coordinates. + + axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes` + The type of the newly created inset axes. + + axes_kwargs : dict, optional + Keyword arguments to pass to the constructor of the inset axes. + Valid arguments include: + + %(Axes:kwdoc)s + + borderpad : float, default: 0.5 + Padding between inset axes and the bbox_to_anchor. + The units are axes font size, i.e. for a default font size of 10 points + *borderpad = 0.5* is equivalent to a padding of 5 points. + + Returns + ------- + inset_axes : *axes_class* + Inset axes object created. + """ + + return _add_inset_axes( + parent_axes, axes_class, axes_kwargs, + AnchoredZoomLocator( + parent_axes, zoom=zoom, loc=loc, + bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform, + borderpad=borderpad)) + + +class _TransformedBboxWithCallback(TransformedBbox): + """ + Variant of `.TransformBbox` which calls *callback* before returning points. + + Used by `.mark_inset` to unstale the parent axes' viewlim as needed. + """ + + def __init__(self, *args, callback, **kwargs): + super().__init__(*args, **kwargs) + self._callback = callback + + def get_points(self): + self._callback() + return super().get_points() + + +@_docstring.interpd +def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs): + """ + Draw a box to mark the location of an area represented by an inset axes. + + This function draws a box in *parent_axes* at the bounding box of + *inset_axes*, and shows a connection with the inset axes by drawing lines + at the corners, giving a "zoomed in" effect. + + Parameters + ---------- + parent_axes : `~matplotlib.axes.Axes` + Axes which contains the area of the inset axes. + + inset_axes : `~matplotlib.axes.Axes` + The inset axes. + + loc1, loc2 : {1, 2, 3, 4} + Corners to use for connecting the inset axes and the area in the + parent axes. + + **kwargs + Patch properties for the lines and box drawn: + + %(Patch:kwdoc)s + + Returns + ------- + pp : `~matplotlib.patches.Patch` + The patch drawn to represent the area of the inset axes. + + p1, p2 : `~matplotlib.patches.Patch` + The patches connecting two corners of the inset axes and its area. + """ + rect = _TransformedBboxWithCallback( + inset_axes.viewLim, parent_axes.transData, + callback=parent_axes._unstale_viewLim) + + kwargs.setdefault("fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs))) + pp = BboxPatch(rect, **kwargs) + parent_axes.add_patch(pp) + + p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs) + inset_axes.add_patch(p1) + p1.set_clip_on(False) + p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs) + inset_axes.add_patch(p2) + p2.set_clip_on(False) + + return pp, p1, p2 diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..51c8748758cb6da3052f0e8b05ceba427d77a3f6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py @@ -0,0 +1,128 @@ +import matplotlib.axes as maxes +from matplotlib.artist import Artist +from matplotlib.axis import XAxis, YAxis + + +class SimpleChainedObjects: + def __init__(self, objects): + self._objects = objects + + def __getattr__(self, k): + _a = SimpleChainedObjects([getattr(a, k) for a in self._objects]) + return _a + + def __call__(self, *args, **kwargs): + for m in self._objects: + m(*args, **kwargs) + + +class Axes(maxes.Axes): + + class AxisDict(dict): + def __init__(self, axes): + self.axes = axes + super().__init__() + + def __getitem__(self, k): + if isinstance(k, tuple): + r = SimpleChainedObjects( + # super() within a list comprehension needs explicit args. + [super(Axes.AxisDict, self).__getitem__(k1) for k1 in k]) + return r + elif isinstance(k, slice): + if k.start is None and k.stop is None and k.step is None: + return SimpleChainedObjects(list(self.values())) + else: + raise ValueError("Unsupported slice") + else: + return dict.__getitem__(self, k) + + def __call__(self, *v, **kwargs): + return maxes.Axes.axis(self.axes, *v, **kwargs) + + @property + def axis(self): + return self._axislines + + def clear(self): + # docstring inherited + super().clear() + # Init axis artists. + self._axislines = self.AxisDict(self) + self._axislines.update( + bottom=SimpleAxisArtist(self.xaxis, 1, self.spines["bottom"]), + top=SimpleAxisArtist(self.xaxis, 2, self.spines["top"]), + left=SimpleAxisArtist(self.yaxis, 1, self.spines["left"]), + right=SimpleAxisArtist(self.yaxis, 2, self.spines["right"])) + + +class SimpleAxisArtist(Artist): + def __init__(self, axis, axisnum, spine): + self._axis = axis + self._axisnum = axisnum + self.line = spine + + if isinstance(axis, XAxis): + self._axis_direction = ["bottom", "top"][axisnum-1] + elif isinstance(axis, YAxis): + self._axis_direction = ["left", "right"][axisnum-1] + else: + raise ValueError( + f"axis must be instance of XAxis or YAxis, but got {axis}") + super().__init__() + + @property + def major_ticks(self): + tickline = "tick%dline" % self._axisnum + return SimpleChainedObjects([getattr(tick, tickline) + for tick in self._axis.get_major_ticks()]) + + @property + def major_ticklabels(self): + label = "label%d" % self._axisnum + return SimpleChainedObjects([getattr(tick, label) + for tick in self._axis.get_major_ticks()]) + + @property + def label(self): + return self._axis.label + + def set_visible(self, b): + self.toggle(all=b) + self.line.set_visible(b) + self._axis.set_visible(True) + super().set_visible(b) + + def set_label(self, txt): + self._axis.set_label_text(txt) + + def toggle(self, all=None, ticks=None, ticklabels=None, label=None): + + if all: + _ticks, _ticklabels, _label = True, True, True + elif all is not None: + _ticks, _ticklabels, _label = False, False, False + else: + _ticks, _ticklabels, _label = None, None, None + + if ticks is not None: + _ticks = ticks + if ticklabels is not None: + _ticklabels = ticklabels + if label is not None: + _label = label + + if _ticks is not None: + tickparam = {f"tick{self._axisnum}On": _ticks} + self._axis.set_tick_params(**tickparam) + if _ticklabels is not None: + tickparam = {f"label{self._axisnum}On": _ticklabels} + self._axis.set_tick_params(**tickparam) + + if _label is not None: + pos = self._axis.get_label_position() + if (pos == self._axis_direction) and not _label: + self._axis.label.set_visible(False) + elif _label: + self._axis.label.set_visible(True) + self._axis.set_label_position(self._axis_direction) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..f7bc2df6d7e01141254114065316a70df5f35e33 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py @@ -0,0 +1,257 @@ +from matplotlib import _api, cbook +import matplotlib.artist as martist +import matplotlib.transforms as mtransforms +from matplotlib.transforms import Bbox +from .mpl_axes import Axes + + +class ParasiteAxesBase: + + def __init__(self, parent_axes, aux_transform=None, + *, viewlim_mode=None, **kwargs): + self._parent_axes = parent_axes + self.transAux = aux_transform + self.set_viewlim_mode(viewlim_mode) + kwargs["frameon"] = False + super().__init__(parent_axes.get_figure(root=False), + parent_axes._position, **kwargs) + + def clear(self): + super().clear() + martist.setp(self.get_children(), visible=False) + self._get_lines = self._parent_axes._get_lines + self._parent_axes.callbacks._connect_picklable( + "xlim_changed", self._sync_lims) + self._parent_axes.callbacks._connect_picklable( + "ylim_changed", self._sync_lims) + + def pick(self, mouseevent): + # This most likely goes to Artist.pick (depending on axes_class given + # to the factory), which only handles pick events registered on the + # axes associated with each child: + super().pick(mouseevent) + # But parasite axes are additionally given pick events from their host + # axes (cf. HostAxesBase.pick), which we handle here: + for a in self.get_children(): + if (hasattr(mouseevent.inaxes, "parasites") + and self in mouseevent.inaxes.parasites): + a.pick(mouseevent) + + # aux_transform support + + def _set_lim_and_transforms(self): + if self.transAux is not None: + self.transAxes = self._parent_axes.transAxes + self.transData = self.transAux + self._parent_axes.transData + self._xaxis_transform = mtransforms.blended_transform_factory( + self.transData, self.transAxes) + self._yaxis_transform = mtransforms.blended_transform_factory( + self.transAxes, self.transData) + else: + super()._set_lim_and_transforms() + + def set_viewlim_mode(self, mode): + _api.check_in_list([None, "equal", "transform"], mode=mode) + self._viewlim_mode = mode + + def get_viewlim_mode(self): + return self._viewlim_mode + + def _sync_lims(self, parent): + viewlim = parent.viewLim.frozen() + mode = self.get_viewlim_mode() + if mode is None: + pass + elif mode == "equal": + self.viewLim.set(viewlim) + elif mode == "transform": + self.viewLim.set(viewlim.transformed(self.transAux.inverted())) + else: + _api.check_in_list([None, "equal", "transform"], mode=mode) + + # end of aux_transform support + + +parasite_axes_class_factory = cbook._make_class_factory( + ParasiteAxesBase, "{}Parasite") +ParasiteAxes = parasite_axes_class_factory(Axes) + + +class HostAxesBase: + def __init__(self, *args, **kwargs): + self.parasites = [] + super().__init__(*args, **kwargs) + + def get_aux_axes( + self, tr=None, viewlim_mode="equal", axes_class=None, **kwargs): + """ + Add a parasite axes to this host. + + Despite this method's name, this should actually be thought of as an + ``add_parasite_axes`` method. + + .. versionchanged:: 3.7 + Defaults to same base axes class as host axes. + + Parameters + ---------- + tr : `~matplotlib.transforms.Transform` or None, default: None + If a `.Transform`, the following relation will hold: + ``parasite.transData = tr + host.transData``. + If None, the parasite's and the host's ``transData`` are unrelated. + viewlim_mode : {"equal", "transform", None}, default: "equal" + How the parasite's view limits are set: directly equal to the + parent axes ("equal"), equal after application of *tr* + ("transform"), or independently (None). + axes_class : subclass type of `~matplotlib.axes.Axes`, optional + The `~.axes.Axes` subclass that is instantiated. If None, the base + class of the host axes is used. + **kwargs + Other parameters are forwarded to the parasite axes constructor. + """ + if axes_class is None: + axes_class = self._base_axes_class + parasite_axes_class = parasite_axes_class_factory(axes_class) + ax2 = parasite_axes_class( + self, tr, viewlim_mode=viewlim_mode, **kwargs) + # note that ax2.transData == tr + ax1.transData + # Anything you draw in ax2 will match the ticks and grids of ax1. + self.parasites.append(ax2) + ax2._remove_method = self.parasites.remove + return ax2 + + def draw(self, renderer): + orig_children_len = len(self._children) + + locator = self.get_axes_locator() + if locator: + pos = locator(self, renderer) + self.set_position(pos, which="active") + self.apply_aspect(pos) + else: + self.apply_aspect() + + rect = self.get_position() + for ax in self.parasites: + ax.apply_aspect(rect) + self._children.extend(ax.get_children()) + + super().draw(renderer) + del self._children[orig_children_len:] + + def clear(self): + super().clear() + for ax in self.parasites: + ax.clear() + + def pick(self, mouseevent): + super().pick(mouseevent) + # Also pass pick events on to parasite axes and, in turn, their + # children (cf. ParasiteAxesBase.pick) + for a in self.parasites: + a.pick(mouseevent) + + def twinx(self, axes_class=None): + """ + Create a twin of Axes with a shared x-axis but independent y-axis. + + The y-axis of self will have ticks on the left and the returned axes + will have ticks on the right. + """ + ax = self._add_twin_axes(axes_class, sharex=self) + self.axis["right"].set_visible(False) + ax.axis["right"].set_visible(True) + ax.axis["left", "top", "bottom"].set_visible(False) + return ax + + def twiny(self, axes_class=None): + """ + Create a twin of Axes with a shared y-axis but independent x-axis. + + The x-axis of self will have ticks on the bottom and the returned axes + will have ticks on the top. + """ + ax = self._add_twin_axes(axes_class, sharey=self) + self.axis["top"].set_visible(False) + ax.axis["top"].set_visible(True) + ax.axis["left", "right", "bottom"].set_visible(False) + return ax + + def twin(self, aux_trans=None, axes_class=None): + """ + Create a twin of Axes with no shared axis. + + While self will have ticks on the left and bottom axis, the returned + axes will have ticks on the top and right axis. + """ + if aux_trans is None: + aux_trans = mtransforms.IdentityTransform() + ax = self._add_twin_axes( + axes_class, aux_transform=aux_trans, viewlim_mode="transform") + self.axis["top", "right"].set_visible(False) + ax.axis["top", "right"].set_visible(True) + ax.axis["left", "bottom"].set_visible(False) + return ax + + def _add_twin_axes(self, axes_class, **kwargs): + """ + Helper for `.twinx`/`.twiny`/`.twin`. + + *kwargs* are forwarded to the parasite axes constructor. + """ + if axes_class is None: + axes_class = self._base_axes_class + ax = parasite_axes_class_factory(axes_class)(self, **kwargs) + self.parasites.append(ax) + ax._remove_method = self._remove_any_twin + return ax + + def _remove_any_twin(self, ax): + self.parasites.remove(ax) + restore = ["top", "right"] + if ax._sharex: + restore.remove("top") + if ax._sharey: + restore.remove("right") + self.axis[tuple(restore)].set_visible(True) + self.axis[tuple(restore)].toggle(ticklabels=False, label=False) + + def get_tightbbox(self, renderer=None, *, call_axes_locator=True, + bbox_extra_artists=None): + bbs = [ + *[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator) + for ax in self.parasites], + super().get_tightbbox(renderer, + call_axes_locator=call_axes_locator, + bbox_extra_artists=bbox_extra_artists)] + return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0]) + + +host_axes_class_factory = host_subplot_class_factory = \ + cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class") +HostAxes = SubplotHost = host_axes_class_factory(Axes) + + +def host_axes(*args, axes_class=Axes, figure=None, **kwargs): + """ + Create axes that can act as a hosts to parasitic axes. + + Parameters + ---------- + figure : `~matplotlib.figure.Figure` + Figure to which the axes will be added. Defaults to the current figure + `.pyplot.gcf()`. + + *args, **kwargs + Will be passed on to the underlying `~.axes.Axes` object creation. + """ + import matplotlib.pyplot as plt + host_axes_class = host_axes_class_factory(axes_class) + if figure is None: + figure = plt.gcf() + ax = host_axes_class(figure, *args, **kwargs) + figure.add_axes(ax) + return ax + + +host_subplot = host_axes diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4d8ed16a6a24a8c15ab2956ef678a7f256cd80 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py @@ -0,0 +1,10 @@ +from pathlib import Path + + +# Check that the test directories exist +if not (Path(__file__).parent / "baseline_images").exists(): + raise OSError( + 'The baseline image directory does not exist. ' + 'This is most likely because the test data is not installed. ' + 'You may need to install matplotlib from source to get the ' + 'test data.') diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82deecacc40459c2cb27db0fa217e0bd5e0fb852 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/conftest.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/conftest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..51bd077ba90fb7b934bc6b7b3d3e26fa87202c05 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/conftest.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/test_axes_grid1.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/test_axes_grid1.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09fe6ef9050c5ae84f19fe6624ef0410e2e2689e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/__pycache__/test_axes_grid1.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/conftest.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..61c2de3e07bac4db323f8704961264d123e01544 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/conftest.py @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import (mpl_test_settings, # noqa + pytest_configure, pytest_unconfigure) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py new file mode 100644 index 0000000000000000000000000000000000000000..b045e8dc87569b0ea5653cf8b0c6307135b69c75 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axes_grid1/tests/test_axes_grid1.py @@ -0,0 +1,782 @@ +from itertools import product +import io +import platform + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.ticker as mticker +from matplotlib import cbook +from matplotlib.backend_bases import MouseEvent +from matplotlib.colors import LogNorm +from matplotlib.patches import Circle, Ellipse +from matplotlib.transforms import Bbox, TransformedBbox +from matplotlib.testing.decorators import ( + check_figures_equal, image_comparison, remove_ticks_and_titles) + +from mpl_toolkits.axes_grid1 import ( + axes_size as Size, + host_subplot, make_axes_locatable, + Grid, AxesGrid, ImageGrid) +from mpl_toolkits.axes_grid1.anchored_artists import ( + AnchoredAuxTransformBox, AnchoredDrawingArea, + AnchoredDirectionArrows, AnchoredSizeBar) +from mpl_toolkits.axes_grid1.axes_divider import ( + Divider, HBoxDivider, make_axes_area_auto_adjustable, SubplotDivider, + VBoxDivider) +from mpl_toolkits.axes_grid1.axes_rgb import RGBAxes +from mpl_toolkits.axes_grid1.inset_locator import ( + zoomed_inset_axes, mark_inset, inset_axes, BboxConnectorPatch) +import mpl_toolkits.axes_grid1.mpl_axes +import pytest + +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal + + +def test_divider_append_axes(): + fig, ax = plt.subplots() + divider = make_axes_locatable(ax) + axs = { + "main": ax, + "top": divider.append_axes("top", 1.2, pad=0.1, sharex=ax), + "bottom": divider.append_axes("bottom", 1.2, pad=0.1, sharex=ax), + "left": divider.append_axes("left", 1.2, pad=0.1, sharey=ax), + "right": divider.append_axes("right", 1.2, pad=0.1, sharey=ax), + } + fig.canvas.draw() + bboxes = {k: axs[k].get_window_extent() for k in axs} + dpi = fig.dpi + assert bboxes["top"].height == pytest.approx(1.2 * dpi) + assert bboxes["bottom"].height == pytest.approx(1.2 * dpi) + assert bboxes["left"].width == pytest.approx(1.2 * dpi) + assert bboxes["right"].width == pytest.approx(1.2 * dpi) + assert bboxes["top"].y0 - bboxes["main"].y1 == pytest.approx(0.1 * dpi) + assert bboxes["main"].y0 - bboxes["bottom"].y1 == pytest.approx(0.1 * dpi) + assert bboxes["main"].x0 - bboxes["left"].x1 == pytest.approx(0.1 * dpi) + assert bboxes["right"].x0 - bboxes["main"].x1 == pytest.approx(0.1 * dpi) + assert bboxes["left"].y0 == bboxes["main"].y0 == bboxes["right"].y0 + assert bboxes["left"].y1 == bboxes["main"].y1 == bboxes["right"].y1 + assert bboxes["top"].x0 == bboxes["main"].x0 == bboxes["bottom"].x0 + assert bboxes["top"].x1 == bboxes["main"].x1 == bboxes["bottom"].x1 + + +# Update style when regenerating the test image +@image_comparison(['twin_axes_empty_and_removed'], extensions=["png"], tol=1, + style=('classic', '_classic_test_patch')) +def test_twin_axes_empty_and_removed(): + # Purely cosmetic font changes (avoid overlap) + mpl.rcParams.update( + {"font.size": 8, "xtick.labelsize": 8, "ytick.labelsize": 8}) + generators = ["twinx", "twiny", "twin"] + modifiers = ["", "host invisible", "twin removed", "twin invisible", + "twin removed\nhost invisible"] + # Unmodified host subplot at the beginning for reference + h = host_subplot(len(modifiers)+1, len(generators), 2) + h.text(0.5, 0.5, "host_subplot", + horizontalalignment="center", verticalalignment="center") + # Host subplots with various modifications (twin*, visibility) applied + for i, (mod, gen) in enumerate(product(modifiers, generators), + len(generators) + 1): + h = host_subplot(len(modifiers)+1, len(generators), i) + t = getattr(h, gen)() + if "twin invisible" in mod: + t.axis[:].set_visible(False) + if "twin removed" in mod: + t.remove() + if "host invisible" in mod: + h.axis[:].set_visible(False) + h.text(0.5, 0.5, gen + ("\n" + mod if mod else ""), + horizontalalignment="center", verticalalignment="center") + plt.subplots_adjust(wspace=0.5, hspace=1) + + +def test_twin_axes_both_with_units(): + host = host_subplot(111) + with pytest.warns(mpl.MatplotlibDeprecationWarning): + host.plot_date([0, 1, 2], [0, 1, 2], xdate=False, ydate=True) + twin = host.twinx() + twin.plot(["a", "b", "c"]) + assert host.get_yticklabels()[0].get_text() == "00:00:00" + assert twin.get_yticklabels()[0].get_text() == "a" + + +def test_axesgrid_colorbar_log_smoketest(): + fig = plt.figure() + grid = AxesGrid(fig, 111, # modified to be only subplot + nrows_ncols=(1, 1), + ngrids=1, + label_mode="L", + cbar_location="top", + cbar_mode="single", + ) + + Z = 10000 * np.random.rand(10, 10) + im = grid[0].imshow(Z, interpolation="nearest", norm=LogNorm()) + + grid.cbar_axes[0].colorbar(im) + + +def test_inset_colorbar_tight_layout_smoketest(): + fig, ax = plt.subplots(1, 1) + pts = ax.scatter([0, 1], [0, 1], c=[1, 5]) + + cax = inset_axes(ax, width="3%", height="70%") + plt.colorbar(pts, cax=cax) + + with pytest.warns(UserWarning, match="This figure includes Axes"): + # Will warn, but not raise an error + plt.tight_layout() + + +@image_comparison(['inset_locator.png'], style='default', remove_text=True) +def test_inset_locator(): + fig, ax = plt.subplots(figsize=[5, 4]) + + # prepare the demo image + # Z is a 15x15 array + Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") + extent = (-3, 4, -4, 3) + Z2 = np.zeros((150, 150)) + ny, nx = Z.shape + Z2[30:30+ny, 30:30+nx] = Z + + ax.imshow(Z2, extent=extent, interpolation="nearest", + origin="lower") + + axins = zoomed_inset_axes(ax, zoom=6, loc='upper right') + axins.imshow(Z2, extent=extent, interpolation="nearest", + origin="lower") + axins.yaxis.get_major_locator().set_params(nbins=7) + axins.xaxis.get_major_locator().set_params(nbins=7) + # sub region of the original image + x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9 + axins.set_xlim(x1, x2) + axins.set_ylim(y1, y2) + + plt.xticks(visible=False) + plt.yticks(visible=False) + + # draw a bbox of the region of the inset axes in the parent axes and + # connecting lines between the bbox and the inset axes area + mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") + + asb = AnchoredSizeBar(ax.transData, + 0.5, + '0.5', + loc='lower center', + pad=0.1, borderpad=0.5, sep=5, + frameon=False) + ax.add_artist(asb) + + +@image_comparison(['inset_axes.png'], style='default', remove_text=True) +def test_inset_axes(): + fig, ax = plt.subplots(figsize=[5, 4]) + + # prepare the demo image + # Z is a 15x15 array + Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") + extent = (-3, 4, -4, 3) + Z2 = np.zeros((150, 150)) + ny, nx = Z.shape + Z2[30:30+ny, 30:30+nx] = Z + + ax.imshow(Z2, extent=extent, interpolation="nearest", + origin="lower") + + # creating our inset axes with a bbox_transform parameter + axins = inset_axes(ax, width=1., height=1., bbox_to_anchor=(1, 1), + bbox_transform=ax.transAxes) + + axins.imshow(Z2, extent=extent, interpolation="nearest", + origin="lower") + axins.yaxis.get_major_locator().set_params(nbins=7) + axins.xaxis.get_major_locator().set_params(nbins=7) + # sub region of the original image + x1, x2, y1, y2 = -1.5, -0.9, -2.5, -1.9 + axins.set_xlim(x1, x2) + axins.set_ylim(y1, y2) + + plt.xticks(visible=False) + plt.yticks(visible=False) + + # draw a bbox of the region of the inset axes in the parent axes and + # connecting lines between the bbox and the inset axes area + mark_inset(ax, axins, loc1=2, loc2=4, fc="none", ec="0.5") + + asb = AnchoredSizeBar(ax.transData, + 0.5, + '0.5', + loc='lower center', + pad=0.1, borderpad=0.5, sep=5, + frameon=False) + ax.add_artist(asb) + + +def test_inset_axes_complete(): + dpi = 100 + figsize = (6, 5) + fig, ax = plt.subplots(figsize=figsize, dpi=dpi) + fig.subplots_adjust(.1, .1, .9, .9) + + ins = inset_axes(ax, width=2., height=2., borderpad=0) + fig.canvas.draw() + assert_array_almost_equal( + ins.get_position().extents, + [(0.9*figsize[0]-2.)/figsize[0], (0.9*figsize[1]-2.)/figsize[1], + 0.9, 0.9]) + + ins = inset_axes(ax, width="40%", height="30%", borderpad=0) + fig.canvas.draw() + assert_array_almost_equal( + ins.get_position().extents, [.9-.8*.4, .9-.8*.3, 0.9, 0.9]) + + ins = inset_axes(ax, width=1., height=1.2, bbox_to_anchor=(200, 100), + loc=3, borderpad=0) + fig.canvas.draw() + assert_array_almost_equal( + ins.get_position().extents, + [200/dpi/figsize[0], 100/dpi/figsize[1], + (200/dpi+1)/figsize[0], (100/dpi+1.2)/figsize[1]]) + + ins1 = inset_axes(ax, width="35%", height="60%", loc=3, borderpad=1) + ins2 = inset_axes(ax, width="100%", height="100%", + bbox_to_anchor=(0, 0, .35, .60), + bbox_transform=ax.transAxes, loc=3, borderpad=1) + fig.canvas.draw() + assert_array_equal(ins1.get_position().extents, + ins2.get_position().extents) + + with pytest.raises(ValueError): + ins = inset_axes(ax, width="40%", height="30%", + bbox_to_anchor=(0.4, 0.5)) + + with pytest.warns(UserWarning): + ins = inset_axes(ax, width="40%", height="30%", + bbox_transform=ax.transAxes) + + +def test_inset_axes_tight(): + # gh-26287 found that inset_axes raised with bbox_inches=tight + fig, ax = plt.subplots() + inset_axes(ax, width=1.3, height=0.9) + + f = io.BytesIO() + fig.savefig(f, bbox_inches="tight") + + +@image_comparison(['fill_facecolor.png'], remove_text=True, style='mpl20') +def test_fill_facecolor(): + fig, ax = plt.subplots(1, 5) + fig.set_size_inches(5, 5) + for i in range(1, 4): + ax[i].yaxis.set_visible(False) + ax[4].yaxis.tick_right() + bbox = Bbox.from_extents(0, 0.4, 1, 0.6) + + # fill with blue by setting 'fc' field + bbox1 = TransformedBbox(bbox, ax[0].transData) + bbox2 = TransformedBbox(bbox, ax[1].transData) + # set color to BboxConnectorPatch + p = BboxConnectorPatch( + bbox1, bbox2, loc1a=1, loc2a=2, loc1b=4, loc2b=3, + ec="r", fc="b") + p.set_clip_on(False) + ax[0].add_patch(p) + # set color to marked area + axins = zoomed_inset_axes(ax[0], 1, loc='upper right') + axins.set_xlim(0, 0.2) + axins.set_ylim(0, 0.2) + plt.gca().axes.xaxis.set_ticks([]) + plt.gca().axes.yaxis.set_ticks([]) + mark_inset(ax[0], axins, loc1=2, loc2=4, fc="b", ec="0.5") + + # fill with yellow by setting 'facecolor' field + bbox3 = TransformedBbox(bbox, ax[1].transData) + bbox4 = TransformedBbox(bbox, ax[2].transData) + # set color to BboxConnectorPatch + p = BboxConnectorPatch( + bbox3, bbox4, loc1a=1, loc2a=2, loc1b=4, loc2b=3, + ec="r", facecolor="y") + p.set_clip_on(False) + ax[1].add_patch(p) + # set color to marked area + axins = zoomed_inset_axes(ax[1], 1, loc='upper right') + axins.set_xlim(0, 0.2) + axins.set_ylim(0, 0.2) + plt.gca().axes.xaxis.set_ticks([]) + plt.gca().axes.yaxis.set_ticks([]) + mark_inset(ax[1], axins, loc1=2, loc2=4, facecolor="y", ec="0.5") + + # fill with green by setting 'color' field + bbox5 = TransformedBbox(bbox, ax[2].transData) + bbox6 = TransformedBbox(bbox, ax[3].transData) + # set color to BboxConnectorPatch + p = BboxConnectorPatch( + bbox5, bbox6, loc1a=1, loc2a=2, loc1b=4, loc2b=3, + ec="r", color="g") + p.set_clip_on(False) + ax[2].add_patch(p) + # set color to marked area + axins = zoomed_inset_axes(ax[2], 1, loc='upper right') + axins.set_xlim(0, 0.2) + axins.set_ylim(0, 0.2) + plt.gca().axes.xaxis.set_ticks([]) + plt.gca().axes.yaxis.set_ticks([]) + mark_inset(ax[2], axins, loc1=2, loc2=4, color="g", ec="0.5") + + # fill with green but color won't show if set fill to False + bbox7 = TransformedBbox(bbox, ax[3].transData) + bbox8 = TransformedBbox(bbox, ax[4].transData) + # BboxConnectorPatch won't show green + p = BboxConnectorPatch( + bbox7, bbox8, loc1a=1, loc2a=2, loc1b=4, loc2b=3, + ec="r", fc="g", fill=False) + p.set_clip_on(False) + ax[3].add_patch(p) + # marked area won't show green + axins = zoomed_inset_axes(ax[3], 1, loc='upper right') + axins.set_xlim(0, 0.2) + axins.set_ylim(0, 0.2) + axins.xaxis.set_ticks([]) + axins.yaxis.set_ticks([]) + mark_inset(ax[3], axins, loc1=2, loc2=4, fc="g", ec="0.5", fill=False) + + +# Update style when regenerating the test image +@image_comparison(['zoomed_axes.png', 'inverted_zoomed_axes.png'], + style=('classic', '_classic_test_patch'), + tol=0 if platform.machine() == 'x86_64' else 0.02) +def test_zooming_with_inverted_axes(): + fig, ax = plt.subplots() + ax.plot([1, 2, 3], [1, 2, 3]) + ax.axis([1, 3, 1, 3]) + inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right') + inset_ax.axis([1.1, 1.4, 1.1, 1.4]) + + fig, ax = plt.subplots() + ax.plot([1, 2, 3], [1, 2, 3]) + ax.axis([3, 1, 3, 1]) + inset_ax = zoomed_inset_axes(ax, zoom=2.5, loc='lower right') + inset_ax.axis([1.4, 1.1, 1.4, 1.1]) + + +# Update style when regenerating the test image +@image_comparison(['anchored_direction_arrows.png'], + tol=0 if platform.machine() == 'x86_64' else 0.01, + style=('classic', '_classic_test_patch')) +def test_anchored_direction_arrows(): + fig, ax = plt.subplots() + ax.imshow(np.zeros((10, 10)), interpolation='nearest') + + simple_arrow = AnchoredDirectionArrows(ax.transAxes, 'X', 'Y') + ax.add_artist(simple_arrow) + + +# Update style when regenerating the test image +@image_comparison(['anchored_direction_arrows_many_args.png'], + style=('classic', '_classic_test_patch')) +def test_anchored_direction_arrows_many_args(): + fig, ax = plt.subplots() + ax.imshow(np.ones((10, 10))) + + direction_arrows = AnchoredDirectionArrows( + ax.transAxes, 'A', 'B', loc='upper right', color='red', + aspect_ratio=-0.5, pad=0.6, borderpad=2, frameon=True, alpha=0.7, + sep_x=-0.06, sep_y=-0.08, back_length=0.1, head_width=9, + head_length=10, tail_width=5) + ax.add_artist(direction_arrows) + + +def test_axes_locatable_position(): + fig, ax = plt.subplots() + divider = make_axes_locatable(ax) + with mpl.rc_context({"figure.subplot.wspace": 0.02}): + cax = divider.append_axes('right', size='5%') + fig.canvas.draw() + assert np.isclose(cax.get_position(original=False).width, + 0.03621495327102808) + + +@image_comparison(['image_grid_each_left_label_mode_all.png'], style='mpl20', + savefig_kwarg={'bbox_inches': 'tight'}) +def test_image_grid_each_left_label_mode_all(): + imdata = np.arange(100).reshape((10, 10)) + + fig = plt.figure(1, (3, 3)) + grid = ImageGrid(fig, (1, 1, 1), nrows_ncols=(3, 2), axes_pad=(0.5, 0.3), + cbar_mode="each", cbar_location="left", cbar_size="15%", + label_mode="all") + # 3-tuple rect => SubplotDivider + assert isinstance(grid.get_divider(), SubplotDivider) + assert grid.get_axes_pad() == (0.5, 0.3) + assert grid.get_aspect() # True by default for ImageGrid + for ax, cax in zip(grid, grid.cbar_axes): + im = ax.imshow(imdata, interpolation='none') + cax.colorbar(im) + + +@image_comparison(['image_grid_single_bottom_label_mode_1.png'], style='mpl20', + savefig_kwarg={'bbox_inches': 'tight'}) +def test_image_grid_single_bottom(): + imdata = np.arange(100).reshape((10, 10)) + + fig = plt.figure(1, (2.5, 1.5)) + grid = ImageGrid(fig, (0, 0, 1, 1), nrows_ncols=(1, 3), + axes_pad=(0.2, 0.15), cbar_mode="single", cbar_pad=0.3, + cbar_location="bottom", cbar_size="10%", label_mode="1") + # 4-tuple rect => Divider, isinstance will give True for SubplotDivider + assert type(grid.get_divider()) is Divider + for i in range(3): + im = grid[i].imshow(imdata, interpolation='none') + grid.cbar_axes[0].colorbar(im) + + +def test_image_grid_label_mode_invalid(): + fig = plt.figure() + with pytest.raises(ValueError, match="'foo' is not a valid value for mode"): + ImageGrid(fig, (0, 0, 1, 1), (2, 1), label_mode="foo") + + +@image_comparison(['image_grid.png'], + remove_text=True, style='mpl20', + savefig_kwarg={'bbox_inches': 'tight'}) +def test_image_grid(): + # test that image grid works with bbox_inches=tight. + im = np.arange(100).reshape((10, 10)) + + fig = plt.figure(1, (4, 4)) + grid = ImageGrid(fig, 111, nrows_ncols=(2, 2), axes_pad=0.1) + assert grid.get_axes_pad() == (0.1, 0.1) + for i in range(4): + grid[i].imshow(im, interpolation='nearest') + + +def test_gettightbbox(): + fig, ax = plt.subplots(figsize=(8, 6)) + + l, = ax.plot([1, 2, 3], [0, 1, 0]) + + ax_zoom = zoomed_inset_axes(ax, 4) + ax_zoom.plot([1, 2, 3], [0, 1, 0]) + + mark_inset(ax, ax_zoom, loc1=1, loc2=3, fc="none", ec='0.3') + + remove_ticks_and_titles(fig) + bbox = fig.get_tightbbox(fig.canvas.get_renderer()) + np.testing.assert_array_almost_equal(bbox.extents, + [-17.7, -13.9, 7.2, 5.4]) + + +@pytest.mark.parametrize("click_on", ["big", "small"]) +@pytest.mark.parametrize("big_on_axes,small_on_axes", [ + ("gca", "gca"), + ("host", "host"), + ("host", "parasite"), + ("parasite", "host"), + ("parasite", "parasite") +]) +def test_picking_callbacks_overlap(big_on_axes, small_on_axes, click_on): + """Test pick events on normal, host or parasite axes.""" + # Two rectangles are drawn and "clicked on", a small one and a big one + # enclosing the small one. The axis on which they are drawn as well as the + # rectangle that is clicked on are varied. + # In each case we expect that both rectangles are picked if we click on the + # small one and only the big one is picked if we click on the big one. + # Also tests picking on normal axes ("gca") as a control. + big = plt.Rectangle((0.25, 0.25), 0.5, 0.5, picker=5) + small = plt.Rectangle((0.4, 0.4), 0.2, 0.2, facecolor="r", picker=5) + # Machinery for "receiving" events + received_events = [] + def on_pick(event): + received_events.append(event) + plt.gcf().canvas.mpl_connect('pick_event', on_pick) + # Shortcut + rectangles_on_axes = (big_on_axes, small_on_axes) + # Axes setup + axes = {"gca": None, "host": None, "parasite": None} + if "gca" in rectangles_on_axes: + axes["gca"] = plt.gca() + if "host" in rectangles_on_axes or "parasite" in rectangles_on_axes: + axes["host"] = host_subplot(111) + axes["parasite"] = axes["host"].twin() + # Add rectangles to axes + axes[big_on_axes].add_patch(big) + axes[small_on_axes].add_patch(small) + # Simulate picking with click mouse event + if click_on == "big": + click_axes = axes[big_on_axes] + axes_coords = (0.3, 0.3) + else: + click_axes = axes[small_on_axes] + axes_coords = (0.5, 0.5) + # In reality mouse events never happen on parasite axes, only host axes + if click_axes is axes["parasite"]: + click_axes = axes["host"] + (x, y) = click_axes.transAxes.transform(axes_coords) + m = MouseEvent("button_press_event", click_axes.get_figure(root=True).canvas, x, y, + button=1) + click_axes.pick(m) + # Checks + expected_n_events = 2 if click_on == "small" else 1 + assert len(received_events) == expected_n_events + event_rects = [event.artist for event in received_events] + assert big in event_rects + if click_on == "small": + assert small in event_rects + + +@image_comparison(['anchored_artists.png'], remove_text=True, style='mpl20') +def test_anchored_artists(): + fig, ax = plt.subplots(figsize=(3, 3)) + ada = AnchoredDrawingArea(40, 20, 0, 0, loc='upper right', pad=0., + frameon=False) + p1 = Circle((10, 10), 10) + ada.drawing_area.add_artist(p1) + p2 = Circle((30, 10), 5, fc="r") + ada.drawing_area.add_artist(p2) + ax.add_artist(ada) + + box = AnchoredAuxTransformBox(ax.transData, loc='upper left') + el = Ellipse((0, 0), width=0.1, height=0.4, angle=30, color='cyan') + box.drawing_area.add_artist(el) + ax.add_artist(box) + + # This block used to test the AnchoredEllipse class, but that was removed. The block + # remains, though it duplicates the above ellipse, so that the test image doesn't + # need to be regenerated. + box = AnchoredAuxTransformBox(ax.transData, loc='lower left', frameon=True, + pad=0.5, borderpad=0.4) + el = Ellipse((0, 0), width=0.1, height=0.25, angle=-60) + box.drawing_area.add_artist(el) + ax.add_artist(box) + + asb = AnchoredSizeBar(ax.transData, 0.2, r"0.2 units", loc='lower right', + pad=0.3, borderpad=0.4, sep=4, fill_bar=True, + frameon=False, label_top=True, prop={'size': 20}, + size_vertical=0.05, color='green') + ax.add_artist(asb) + + +def test_hbox_divider(): + arr1 = np.arange(20).reshape((4, 5)) + arr2 = np.arange(20).reshape((5, 4)) + + fig, (ax1, ax2) = plt.subplots(1, 2) + ax1.imshow(arr1) + ax2.imshow(arr2) + + pad = 0.5 # inches. + divider = HBoxDivider( + fig, 111, # Position of combined axes. + horizontal=[Size.AxesX(ax1), Size.Fixed(pad), Size.AxesX(ax2)], + vertical=[Size.AxesY(ax1), Size.Scaled(1), Size.AxesY(ax2)]) + ax1.set_axes_locator(divider.new_locator(0)) + ax2.set_axes_locator(divider.new_locator(2)) + + fig.canvas.draw() + p1 = ax1.get_position() + p2 = ax2.get_position() + assert p1.height == p2.height + assert p2.width / p1.width == pytest.approx((4 / 5) ** 2) + + +def test_vbox_divider(): + arr1 = np.arange(20).reshape((4, 5)) + arr2 = np.arange(20).reshape((5, 4)) + + fig, (ax1, ax2) = plt.subplots(1, 2) + ax1.imshow(arr1) + ax2.imshow(arr2) + + pad = 0.5 # inches. + divider = VBoxDivider( + fig, 111, # Position of combined axes. + horizontal=[Size.AxesX(ax1), Size.Scaled(1), Size.AxesX(ax2)], + vertical=[Size.AxesY(ax1), Size.Fixed(pad), Size.AxesY(ax2)]) + ax1.set_axes_locator(divider.new_locator(0)) + ax2.set_axes_locator(divider.new_locator(2)) + + fig.canvas.draw() + p1 = ax1.get_position() + p2 = ax2.get_position() + assert p1.width == p2.width + assert p1.height / p2.height == pytest.approx((4 / 5) ** 2) + + +def test_axes_class_tuple(): + fig = plt.figure() + axes_class = (mpl_toolkits.axes_grid1.mpl_axes.Axes, {}) + gr = AxesGrid(fig, 111, nrows_ncols=(1, 1), axes_class=axes_class) + + +def test_grid_axes_lists(): + """Test Grid axes_all, axes_row and axes_column relationship.""" + fig = plt.figure() + grid = Grid(fig, 111, (2, 3), direction="row") + assert_array_equal(grid, grid.axes_all) + assert_array_equal(grid.axes_row, np.transpose(grid.axes_column)) + assert_array_equal(grid, np.ravel(grid.axes_row), "row") + assert grid.get_geometry() == (2, 3) + grid = Grid(fig, 111, (2, 3), direction="column") + assert_array_equal(grid, np.ravel(grid.axes_column), "column") + + +@pytest.mark.parametrize('direction', ('row', 'column')) +def test_grid_axes_position(direction): + """Test positioning of the axes in Grid.""" + fig = plt.figure() + grid = Grid(fig, 111, (2, 2), direction=direction) + loc = [ax.get_axes_locator() for ax in np.ravel(grid.axes_row)] + # Test nx. + assert loc[1].args[0] > loc[0].args[0] + assert loc[0].args[0] == loc[2].args[0] + assert loc[3].args[0] == loc[1].args[0] + # Test ny. + assert loc[2].args[1] < loc[0].args[1] + assert loc[0].args[1] == loc[1].args[1] + assert loc[3].args[1] == loc[2].args[1] + + +@pytest.mark.parametrize('rect, ngrids, error, message', ( + ((1, 1), None, TypeError, "Incorrect rect format"), + (111, -1, ValueError, "ngrids must be positive"), + (111, 7, ValueError, "ngrids must be positive"), +)) +def test_grid_errors(rect, ngrids, error, message): + fig = plt.figure() + with pytest.raises(error, match=message): + Grid(fig, rect, (2, 3), ngrids=ngrids) + + +@pytest.mark.parametrize('anchor, error, message', ( + (None, TypeError, "anchor must be str"), + ("CC", ValueError, "'CC' is not a valid value for anchor"), + ((1, 1, 1), TypeError, "anchor must be str"), +)) +def test_divider_errors(anchor, error, message): + fig = plt.figure() + with pytest.raises(error, match=message): + Divider(fig, [0, 0, 1, 1], [Size.Fixed(1)], [Size.Fixed(1)], + anchor=anchor) + + +@check_figures_equal(extensions=["png"]) +def test_mark_inset_unstales_viewlim(fig_test, fig_ref): + inset, full = fig_test.subplots(1, 2) + full.plot([0, 5], [0, 5]) + inset.set(xlim=(1, 2), ylim=(1, 2)) + # Check that mark_inset unstales full's viewLim before drawing the marks. + mark_inset(full, inset, 1, 4) + + inset, full = fig_ref.subplots(1, 2) + full.plot([0, 5], [0, 5]) + inset.set(xlim=(1, 2), ylim=(1, 2)) + mark_inset(full, inset, 1, 4) + # Manually unstale the full's viewLim. + fig_ref.canvas.draw() + + +def test_auto_adjustable(): + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1]) + pad = 0.1 + make_axes_area_auto_adjustable(ax, pad=pad) + fig.canvas.draw() + tbb = ax.get_tightbbox() + assert tbb.x0 == pytest.approx(pad * fig.dpi) + assert tbb.x1 == pytest.approx(fig.bbox.width - pad * fig.dpi) + assert tbb.y0 == pytest.approx(pad * fig.dpi) + assert tbb.y1 == pytest.approx(fig.bbox.height - pad * fig.dpi) + + +# Update style when regenerating the test image +@image_comparison(['rgb_axes.png'], remove_text=True, + style=('classic', '_classic_test_patch')) +def test_rgb_axes(): + fig = plt.figure() + ax = RGBAxes(fig, (0.1, 0.1, 0.8, 0.8), pad=0.1) + rng = np.random.default_rng(19680801) + r = rng.random((5, 5)) + g = rng.random((5, 5)) + b = rng.random((5, 5)) + ax.imshow_rgb(r, g, b, interpolation='none') + + +# The original version of this test relied on mpl_toolkits's slightly different +# colorbar implementation; moving to matplotlib's own colorbar implementation +# caused the small image comparison error. +@image_comparison(['imagegrid_cbar_mode.png'], + remove_text=True, style='mpl20', tol=0.3) +def test_imagegrid_cbar_mode_edge(): + arr = np.arange(16).reshape((4, 4)) + + fig = plt.figure(figsize=(18, 9)) + + positions = (241, 242, 243, 244, 245, 246, 247, 248) + directions = ['row']*4 + ['column']*4 + cbar_locations = ['left', 'right', 'top', 'bottom']*2 + + for position, direction, location in zip( + positions, directions, cbar_locations): + grid = ImageGrid(fig, position, + nrows_ncols=(2, 2), + direction=direction, + cbar_location=location, + cbar_size='20%', + cbar_mode='edge') + ax1, ax2, ax3, ax4 = grid + + ax1.imshow(arr, cmap='nipy_spectral') + ax2.imshow(arr.T, cmap='hot') + ax3.imshow(np.hypot(arr, arr.T), cmap='jet') + ax4.imshow(np.arctan2(arr, arr.T), cmap='hsv') + + # In each row/column, the "first" colorbars must be overwritten by the + # "second" ones. To achieve this, clear out the axes first. + for ax in grid: + ax.cax.cla() + cb = ax.cax.colorbar(ax.images[0]) + + +def test_imagegrid(): + fig = plt.figure() + grid = ImageGrid(fig, 111, nrows_ncols=(1, 1)) + ax = grid[0] + im = ax.imshow([[1, 2]], norm=mpl.colors.LogNorm()) + cb = ax.cax.colorbar(im) + assert isinstance(cb.locator, mticker.LogLocator) + + +def test_removal(): + import matplotlib.pyplot as plt + import mpl_toolkits.axisartist as AA + fig = plt.figure() + ax = host_subplot(111, axes_class=AA.Axes, figure=fig) + col = ax.fill_between(range(5), 0, range(5)) + fig.canvas.draw() + col.remove() + fig.canvas.draw() + + +@image_comparison(['anchored_locator_base_call.png'], style="mpl20") +def test_anchored_locator_base_call(): + fig = plt.figure(figsize=(3, 3)) + fig1, fig2 = fig.subfigures(nrows=2, ncols=1) + + ax = fig1.subplots() + ax.set(aspect=1, xlim=(-15, 15), ylim=(-20, 5)) + ax.set(xticks=[], yticks=[]) + + Z = cbook.get_sample_data("axes_grid/bivariate_normal.npy") + extent = (-3, 4, -4, 3) + + axins = zoomed_inset_axes(ax, zoom=2, loc="upper left") + axins.set(xticks=[], yticks=[]) + + axins.imshow(Z, extent=extent, origin="lower") + + +def test_grid_with_axes_class_not_overriding_axis(): + Grid(plt.figure(), 111, (2, 2), axes_class=mpl.axes.Axes) + RGBAxes(plt.figure(), 111, axes_class=mpl.axes.Axes) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8d8c08ac226d105a5a54c5f21040cd25107ae6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__init__.py @@ -0,0 +1,14 @@ +from .axislines import Axes +from .axislines import ( # noqa: F401 + AxesZero, AxisArtistHelper, AxisArtistHelperRectlinear, + GridHelperBase, GridHelperRectlinear, Subplot, SubplotZero) +from .axis_artist import AxisArtist, GridlinesCollection # noqa: F401 +from .grid_helper_curvelinear import GridHelperCurveLinear # noqa: F401 +from .floating_axes import FloatingAxes, FloatingSubplot # noqa: F401 +from mpl_toolkits.axes_grid1.parasite_axes import ( + host_axes_class_factory, parasite_axes_class_factory) + + +ParasiteAxes = parasite_axes_class_factory(Axes) +HostAxes = host_axes_class_factory(Axes) +SubplotHost = HostAxes diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2a3481cb4baad679133203d0aa343988f3e430f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ea299ba6d731002f9dbe3cc78a663272d043233c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/angle_helper.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4502b8e8efcdf72e818b45b571b9d2facd237afa Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axes_divider.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axis_artist.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axis_artist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4b31288ef0e887d60b89973bc6d7eef78190300b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axis_artist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axisline_style.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axisline_style.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8dea3ddbb0efe6a6b9a3f911af40182d24368433 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axisline_style.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axislines.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axislines.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..02d735414948d592cd4d3e53746560e3e749fa76 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/axislines.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/floating_axes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/floating_axes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56c0605c0c6b473fd3db3b8a651c8e89b3cd12e6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/floating_axes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_finder.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_finder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1d9e8bd3a28f4bbeb036149aae3877f3d99cea7d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_finder.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_helper_curvelinear.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_helper_curvelinear.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1672e333cf8150bd7a34df675d316b2232d5998d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/grid_helper_curvelinear.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/parasite_axes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/parasite_axes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd64595c232bbe2aeb0dbe615f6ce206ed7272b8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/__pycache__/parasite_axes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/angle_helper.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/angle_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..1786cd70bcdb297de6c17374353cc2a49dfd0ae1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/angle_helper.py @@ -0,0 +1,394 @@ +import numpy as np +import math + +from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple + + +def select_step_degree(dv): + + degree_limits_ = [1.5, 3, 7, 13, 20, 40, 70, 120, 270, 520] + degree_steps_ = [1, 2, 5, 10, 15, 30, 45, 90, 180, 360] + degree_factors = [1.] * len(degree_steps_) + + minsec_limits_ = [1.5, 2.5, 3.5, 8, 11, 18, 25, 45] + minsec_steps_ = [1, 2, 3, 5, 10, 15, 20, 30] + + minute_limits_ = np.array(minsec_limits_) / 60 + minute_factors = [60.] * len(minute_limits_) + + second_limits_ = np.array(minsec_limits_) / 3600 + second_factors = [3600.] * len(second_limits_) + + degree_limits = [*second_limits_, *minute_limits_, *degree_limits_] + degree_steps = [*minsec_steps_, *minsec_steps_, *degree_steps_] + degree_factors = [*second_factors, *minute_factors, *degree_factors] + + n = np.searchsorted(degree_limits, dv) + step = degree_steps[n] + factor = degree_factors[n] + + return step, factor + + +def select_step_hour(dv): + + hour_limits_ = [1.5, 2.5, 3.5, 5, 7, 10, 15, 21, 36] + hour_steps_ = [1, 2, 3, 4, 6, 8, 12, 18, 24] + hour_factors = [1.] * len(hour_steps_) + + minsec_limits_ = [1.5, 2.5, 3.5, 4.5, 5.5, 8, 11, 14, 18, 25, 45] + minsec_steps_ = [1, 2, 3, 4, 5, 6, 10, 12, 15, 20, 30] + + minute_limits_ = np.array(minsec_limits_) / 60 + minute_factors = [60.] * len(minute_limits_) + + second_limits_ = np.array(minsec_limits_) / 3600 + second_factors = [3600.] * len(second_limits_) + + hour_limits = [*second_limits_, *minute_limits_, *hour_limits_] + hour_steps = [*minsec_steps_, *minsec_steps_, *hour_steps_] + hour_factors = [*second_factors, *minute_factors, *hour_factors] + + n = np.searchsorted(hour_limits, dv) + step = hour_steps[n] + factor = hour_factors[n] + + return step, factor + + +def select_step_sub(dv): + + # subarcsec or degree + tmp = 10.**(int(math.log10(dv))-1.) + + factor = 1./tmp + + if 1.5*tmp >= dv: + step = 1 + elif 3.*tmp >= dv: + step = 2 + elif 7.*tmp >= dv: + step = 5 + else: + step = 1 + factor = 0.1*factor + + return step, factor + + +def select_step(v1, v2, nv, hour=False, include_last=True, + threshold_factor=3600.): + + if v1 > v2: + v1, v2 = v2, v1 + + dv = (v2 - v1) / nv + + if hour: + _select_step = select_step_hour + cycle = 24. + else: + _select_step = select_step_degree + cycle = 360. + + # for degree + if dv > 1 / threshold_factor: + step, factor = _select_step(dv) + else: + step, factor = select_step_sub(dv*threshold_factor) + + factor = factor * threshold_factor + + levs = np.arange(np.floor(v1 * factor / step), + np.ceil(v2 * factor / step) + 0.5, + dtype=int) * step + + # n : number of valid levels. If there is a cycle, e.g., [0, 90, 180, + # 270, 360], the grid line needs to be extended from 0 to 360, so + # we need to return the whole array. However, the last level (360) + # needs to be ignored often. In this case, so we return n=4. + + n = len(levs) + + # we need to check the range of values + # for example, -90 to 90, 0 to 360, + + if factor == 1. and levs[-1] >= levs[0] + cycle: # check for cycle + nv = int(cycle / step) + if include_last: + levs = levs[0] + np.arange(0, nv+1, 1) * step + else: + levs = levs[0] + np.arange(0, nv, 1) * step + + n = len(levs) + + return np.array(levs), n, factor + + +def select_step24(v1, v2, nv, include_last=True, threshold_factor=3600): + v1, v2 = v1 / 15, v2 / 15 + levs, n, factor = select_step(v1, v2, nv, hour=True, + include_last=include_last, + threshold_factor=threshold_factor) + return levs * 15, n, factor + + +def select_step360(v1, v2, nv, include_last=True, threshold_factor=3600): + return select_step(v1, v2, nv, hour=False, + include_last=include_last, + threshold_factor=threshold_factor) + + +class LocatorBase: + def __init__(self, nbins, include_last=True): + self.nbins = nbins + self._include_last = include_last + + def set_params(self, nbins=None): + if nbins is not None: + self.nbins = int(nbins) + + +class LocatorHMS(LocatorBase): + def __call__(self, v1, v2): + return select_step24(v1, v2, self.nbins, self._include_last) + + +class LocatorHM(LocatorBase): + def __call__(self, v1, v2): + return select_step24(v1, v2, self.nbins, self._include_last, + threshold_factor=60) + + +class LocatorH(LocatorBase): + def __call__(self, v1, v2): + return select_step24(v1, v2, self.nbins, self._include_last, + threshold_factor=1) + + +class LocatorDMS(LocatorBase): + def __call__(self, v1, v2): + return select_step360(v1, v2, self.nbins, self._include_last) + + +class LocatorDM(LocatorBase): + def __call__(self, v1, v2): + return select_step360(v1, v2, self.nbins, self._include_last, + threshold_factor=60) + + +class LocatorD(LocatorBase): + def __call__(self, v1, v2): + return select_step360(v1, v2, self.nbins, self._include_last, + threshold_factor=1) + + +class FormatterDMS: + deg_mark = r"^{\circ}" + min_mark = r"^{\prime}" + sec_mark = r"^{\prime\prime}" + + fmt_d = "$%d" + deg_mark + "$" + fmt_ds = r"$%d.%s" + deg_mark + "$" + + # %s for sign + fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark + "$" + fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s" + min_mark + "$" + + fmt_d_m_partial = "$%s%d" + deg_mark + r"\,%02d" + min_mark + r"\," + fmt_s_partial = "%02d" + sec_mark + "$" + fmt_ss_partial = "%02d.%s" + sec_mark + "$" + + def _get_number_fraction(self, factor): + ## check for fractional numbers + number_fraction = None + # check for 60 + + for threshold in [1, 60, 3600]: + if factor <= threshold: + break + + d = factor // threshold + int_log_d = int(np.floor(np.log10(d))) + if 10**int_log_d == d and d != 1: + number_fraction = int_log_d + factor = factor // 10**int_log_d + return factor, number_fraction + + return factor, number_fraction + + def __call__(self, direction, factor, values): + if len(values) == 0: + return [] + + ss = np.sign(values) + signs = ["-" if v < 0 else "" for v in values] + + factor, number_fraction = self._get_number_fraction(factor) + + values = np.abs(values) + + if number_fraction is not None: + values, frac_part = divmod(values, 10 ** number_fraction) + frac_fmt = "%%0%dd" % (number_fraction,) + frac_str = [frac_fmt % (f1,) for f1 in frac_part] + + if factor == 1: + if number_fraction is None: + return [self.fmt_d % (s * int(v),) for s, v in zip(ss, values)] + else: + return [self.fmt_ds % (s * int(v), f1) + for s, v, f1 in zip(ss, values, frac_str)] + elif factor == 60: + deg_part, min_part = divmod(values, 60) + if number_fraction is None: + return [self.fmt_d_m % (s1, d1, m1) + for s1, d1, m1 in zip(signs, deg_part, min_part)] + else: + return [self.fmt_d_ms % (s, d1, m1, f1) + for s, d1, m1, f1 + in zip(signs, deg_part, min_part, frac_str)] + + elif factor == 3600: + if ss[-1] == -1: + inverse_order = True + values = values[::-1] + signs = signs[::-1] + else: + inverse_order = False + + l_hm_old = "" + r = [] + + deg_part, min_part_ = divmod(values, 3600) + min_part, sec_part = divmod(min_part_, 60) + + if number_fraction is None: + sec_str = [self.fmt_s_partial % (s1,) for s1 in sec_part] + else: + sec_str = [self.fmt_ss_partial % (s1, f1) + for s1, f1 in zip(sec_part, frac_str)] + + for s, d1, m1, s1 in zip(signs, deg_part, min_part, sec_str): + l_hm = self.fmt_d_m_partial % (s, d1, m1) + if l_hm != l_hm_old: + l_hm_old = l_hm + l = l_hm + s1 + else: + l = "$" + s + s1 + r.append(l) + + if inverse_order: + return r[::-1] + else: + return r + + else: # factor > 3600. + return [r"$%s^{\circ}$" % v for v in ss*values] + + +class FormatterHMS(FormatterDMS): + deg_mark = r"^\mathrm{h}" + min_mark = r"^\mathrm{m}" + sec_mark = r"^\mathrm{s}" + + fmt_d = "$%d" + deg_mark + "$" + fmt_ds = r"$%d.%s" + deg_mark + "$" + + # %s for sign + fmt_d_m = r"$%s%d" + deg_mark + r"\,%02d" + min_mark+"$" + fmt_d_ms = r"$%s%d" + deg_mark + r"\,%02d.%s" + min_mark+"$" + + fmt_d_m_partial = "$%s%d" + deg_mark + r"\,%02d" + min_mark + r"\," + fmt_s_partial = "%02d" + sec_mark + "$" + fmt_ss_partial = "%02d.%s" + sec_mark + "$" + + def __call__(self, direction, factor, values): # hour + return super().__call__(direction, factor, np.asarray(values) / 15) + + +class ExtremeFinderCycle(ExtremeFinderSimple): + # docstring inherited + + def __init__(self, nx, ny, + lon_cycle=360., lat_cycle=None, + lon_minmax=None, lat_minmax=(-90, 90)): + """ + This subclass handles the case where one or both coordinates should be + taken modulo 360, or be restricted to not exceed a specific range. + + Parameters + ---------- + nx, ny : int + The number of samples in each direction. + + lon_cycle, lat_cycle : 360 or None + If not None, values in the corresponding direction are taken modulo + *lon_cycle* or *lat_cycle*; in theory this can be any number but + the implementation actually assumes that it is 360 (if not None); + other values give nonsensical results. + + This is done by "unwrapping" the transformed grid coordinates so + that jumps are less than a half-cycle; then normalizing the span to + no more than a full cycle. + + For example, if values are in the union of the [0, 2] and + [358, 360] intervals (typically, angles measured modulo 360), the + values in the second interval are normalized to [-2, 0] instead so + that the values now cover [-2, 2]. If values are in a range of + [5, 1000], this gets normalized to [5, 365]. + + lon_minmax, lat_minmax : (float, float) or None + If not None, the computed bounding box is clipped to the given + range in the corresponding direction. + """ + self.nx, self.ny = nx, ny + self.lon_cycle, self.lat_cycle = lon_cycle, lat_cycle + self.lon_minmax = lon_minmax + self.lat_minmax = lat_minmax + + def __call__(self, transform_xy, x1, y1, x2, y2): + # docstring inherited + x, y = np.meshgrid( + np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)) + lon, lat = transform_xy(np.ravel(x), np.ravel(y)) + + # iron out jumps, but algorithm should be improved. + # This is just naive way of doing and my fail for some cases. + # Consider replacing this with numpy.unwrap + # We are ignoring invalid warnings. They are triggered when + # comparing arrays with NaNs using > We are already handling + # that correctly using np.nanmin and np.nanmax + with np.errstate(invalid='ignore'): + if self.lon_cycle is not None: + lon0 = np.nanmin(lon) + lon -= 360. * ((lon - lon0) > 180.) + if self.lat_cycle is not None: + lat0 = np.nanmin(lat) + lat -= 360. * ((lat - lat0) > 180.) + + lon_min, lon_max = np.nanmin(lon), np.nanmax(lon) + lat_min, lat_max = np.nanmin(lat), np.nanmax(lat) + + lon_min, lon_max, lat_min, lat_max = \ + self._add_pad(lon_min, lon_max, lat_min, lat_max) + + # check cycle + if self.lon_cycle: + lon_max = min(lon_max, lon_min + self.lon_cycle) + if self.lat_cycle: + lat_max = min(lat_max, lat_min + self.lat_cycle) + + if self.lon_minmax is not None: + min0 = self.lon_minmax[0] + lon_min = max(min0, lon_min) + max0 = self.lon_minmax[1] + lon_max = min(max0, lon_max) + + if self.lat_minmax is not None: + min0 = self.lat_minmax[0] + lat_min = max(min0, lat_min) + max0 = self.lat_minmax[1] + lat_max = min(max0, lat_max) + + return lon_min, lon_max, lat_min, lat_max diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axes_divider.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axes_divider.py new file mode 100644 index 0000000000000000000000000000000000000000..d0392be782d9c06404c3d83c2b8ca271bbb8fa72 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axes_divider.py @@ -0,0 +1,2 @@ +from mpl_toolkits.axes_grid1.axes_divider import ( # noqa + Divider, SubplotDivider, AxesDivider, make_axes_locatable) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axis_artist.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axis_artist.py new file mode 100644 index 0000000000000000000000000000000000000000..725c665d818ade7772b427114975a0b1bfcec3b0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axis_artist.py @@ -0,0 +1,1116 @@ +""" +The :mod:`.axis_artist` module implements custom artists to draw axis elements +(axis lines and labels, tick lines and labels, grid lines). + +Axis lines and labels and tick lines and labels are managed by the `AxisArtist` +class; grid lines are managed by the `GridlinesCollection` class. + +There is one `AxisArtist` per Axis; it can be accessed through +the ``axis`` dictionary of the parent Axes (which should be a +`mpl_toolkits.axislines.Axes`), e.g. ``ax.axis["bottom"]``. + +Children of the AxisArtist are accessed as attributes: ``.line`` and ``.label`` +for the axis line and label, ``.major_ticks``, ``.major_ticklabels``, +``.minor_ticks``, ``.minor_ticklabels`` for the tick lines and labels (e.g. +``ax.axis["bottom"].line``). + +Children properties (colors, fonts, line widths, etc.) can be set using +setters, e.g. :: + + # Make the major ticks of the bottom axis red. + ax.axis["bottom"].major_ticks.set_color("red") + +However, things like the locations of ticks, and their ticklabels need to be +changed from the side of the grid_helper. + +axis_direction +-------------- + +`AxisArtist`, `AxisLabel`, `TickLabels` have an *axis_direction* attribute, +which adjusts the location, angle, etc. The *axis_direction* must be one of +"left", "right", "bottom", "top", and follows the Matplotlib convention for +rectangular axis. + +For example, for the *bottom* axis (the left and right is relative to the +direction of the increasing coordinate), + +* ticklabels and axislabel are on the right +* ticklabels and axislabel have text angle of 0 +* ticklabels are baseline, center-aligned +* axislabel is top, center-aligned + +The text angles are actually relative to (90 + angle of the direction to the +ticklabel), which gives 0 for bottom axis. + +=================== ====== ======== ====== ======== +Property left bottom right top +=================== ====== ======== ====== ======== +ticklabel location left right right left +axislabel location left right right left +ticklabel angle 90 0 -90 180 +axislabel angle 180 0 0 180 +ticklabel va center baseline center baseline +axislabel va center top center bottom +ticklabel ha right center right center +axislabel ha right center right center +=================== ====== ======== ====== ======== + +Ticks are by default direct opposite side of the ticklabels. To make ticks to +the same side of the ticklabels, :: + + ax.axis["bottom"].major_ticks.set_tick_out(True) + +The following attributes can be customized (use the ``set_xxx`` methods): + +* `Ticks`: ticksize, tick_out +* `TickLabels`: pad +* `AxisLabel`: pad +""" + +# FIXME : +# angles are given in data coordinate - need to convert it to canvas coordinate + + +from operator import methodcaller + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +import matplotlib.artist as martist +import matplotlib.colors as mcolors +import matplotlib.text as mtext +from matplotlib.collections import LineCollection +from matplotlib.lines import Line2D +from matplotlib.patches import PathPatch +from matplotlib.path import Path +from matplotlib.transforms import ( + Affine2D, Bbox, IdentityTransform, ScaledTranslation) + +from .axisline_style import AxislineStyle + + +class AttributeCopier: + def get_ref_artist(self): + """ + Return the underlying artist that actually defines some properties + (e.g., color) of this artist. + """ + raise RuntimeError("get_ref_artist must overridden") + + def get_attribute_from_ref_artist(self, attr_name): + getter = methodcaller("get_" + attr_name) + prop = getter(super()) + return getter(self.get_ref_artist()) if prop == "auto" else prop + + +class Ticks(AttributeCopier, Line2D): + """ + Ticks are derived from `.Line2D`, and note that ticks themselves + are markers. Thus, you should use set_mec, set_mew, etc. + + To change the tick size (length), you need to use + `set_ticksize`. To change the direction of the ticks (ticks are + in opposite direction of ticklabels by default), use + ``set_tick_out(False)`` + """ + + def __init__(self, ticksize, tick_out=False, *, axis=None, **kwargs): + self._ticksize = ticksize + self.locs_angles_labels = [] + + self.set_tick_out(tick_out) + + self._axis = axis + if self._axis is not None: + if "color" not in kwargs: + kwargs["color"] = "auto" + if "mew" not in kwargs and "markeredgewidth" not in kwargs: + kwargs["markeredgewidth"] = "auto" + + Line2D.__init__(self, [0.], [0.], **kwargs) + self.set_snap(True) + + def get_ref_artist(self): + # docstring inherited + return self._axis.majorTicks[0].tick1line + + def set_color(self, color): + # docstring inherited + # Unlike the base Line2D.set_color, this also supports "auto". + if not cbook._str_equal(color, "auto"): + mcolors._check_color_like(color=color) + self._color = color + self.stale = True + + def get_color(self): + return self.get_attribute_from_ref_artist("color") + + def get_markeredgecolor(self): + return self.get_attribute_from_ref_artist("markeredgecolor") + + def get_markeredgewidth(self): + return self.get_attribute_from_ref_artist("markeredgewidth") + + def set_tick_out(self, b): + """Set whether ticks are drawn inside or outside the axes.""" + self._tick_out = b + + def get_tick_out(self): + """Return whether ticks are drawn inside or outside the axes.""" + return self._tick_out + + def set_ticksize(self, ticksize): + """Set length of the ticks in points.""" + self._ticksize = ticksize + + def get_ticksize(self): + """Return length of the ticks in points.""" + return self._ticksize + + def set_locs_angles(self, locs_angles): + self.locs_angles = locs_angles + + _tickvert_path = Path([[0., 0.], [1., 0.]]) + + def draw(self, renderer): + if not self.get_visible(): + return + + gc = renderer.new_gc() + gc.set_foreground(self.get_markeredgecolor()) + gc.set_linewidth(self.get_markeredgewidth()) + gc.set_alpha(self._alpha) + + path_trans = self.get_transform() + marker_transform = (Affine2D() + .scale(renderer.points_to_pixels(self._ticksize))) + if self.get_tick_out(): + marker_transform.rotate_deg(180) + + for loc, angle in self.locs_angles: + locs = path_trans.transform_non_affine(np.array([loc])) + if self.axes and not self.axes.viewLim.contains(*locs[0]): + continue + renderer.draw_markers( + gc, self._tickvert_path, + marker_transform + Affine2D().rotate_deg(angle), + Path(locs), path_trans.get_affine()) + + gc.restore() + + +class LabelBase(mtext.Text): + """ + A base class for `.AxisLabel` and `.TickLabels`. The position and + angle of the text are calculated by the offset_ref_angle, + text_ref_angle, and offset_radius attributes. + """ + + def __init__(self, *args, **kwargs): + self.locs_angles_labels = [] + self._ref_angle = 0 + self._offset_radius = 0. + + super().__init__(*args, **kwargs) + + self.set_rotation_mode("anchor") + self._text_follow_ref_angle = True + + @property + def _text_ref_angle(self): + if self._text_follow_ref_angle: + return self._ref_angle + 90 + else: + return 0 + + @property + def _offset_ref_angle(self): + return self._ref_angle + + _get_opposite_direction = {"left": "right", + "right": "left", + "top": "bottom", + "bottom": "top"}.__getitem__ + + def draw(self, renderer): + if not self.get_visible(): + return + + # save original and adjust some properties + tr = self.get_transform() + angle_orig = self.get_rotation() + theta = np.deg2rad(self._offset_ref_angle) + dd = self._offset_radius + dx, dy = dd * np.cos(theta), dd * np.sin(theta) + + self.set_transform(tr + Affine2D().translate(dx, dy)) + self.set_rotation(self._text_ref_angle + angle_orig) + super().draw(renderer) + # restore original properties + self.set_transform(tr) + self.set_rotation(angle_orig) + + def get_window_extent(self, renderer=None): + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + # save original and adjust some properties + tr = self.get_transform() + angle_orig = self.get_rotation() + theta = np.deg2rad(self._offset_ref_angle) + dd = self._offset_radius + dx, dy = dd * np.cos(theta), dd * np.sin(theta) + + self.set_transform(tr + Affine2D().translate(dx, dy)) + self.set_rotation(self._text_ref_angle + angle_orig) + bbox = super().get_window_extent(renderer).frozen() + # restore original properties + self.set_transform(tr) + self.set_rotation(angle_orig) + + return bbox + + +class AxisLabel(AttributeCopier, LabelBase): + """ + Axis label. Derived from `.Text`. The position of the text is updated + in the fly, so changing text position has no effect. Otherwise, the + properties can be changed as a normal `.Text`. + + To change the pad between tick labels and axis label, use `set_pad`. + """ + + def __init__(self, *args, axis_direction="bottom", axis=None, **kwargs): + self._axis = axis + self._pad = 5 + self._external_pad = 0 # in pixels + LabelBase.__init__(self, *args, **kwargs) + self.set_axis_direction(axis_direction) + + def set_pad(self, pad): + """ + Set the internal pad in points. + + The actual pad will be the sum of the internal pad and the + external pad (the latter is set automatically by the `.AxisArtist`). + + Parameters + ---------- + pad : float + The internal pad in points. + """ + self._pad = pad + + def get_pad(self): + """ + Return the internal pad in points. + + See `.set_pad` for more details. + """ + return self._pad + + def get_ref_artist(self): + # docstring inherited + return self._axis.label + + def get_text(self): + # docstring inherited + t = super().get_text() + if t == "__from_axes__": + return self._axis.label.get_text() + return self._text + + _default_alignments = dict(left=("bottom", "center"), + right=("top", "center"), + bottom=("top", "center"), + top=("bottom", "center")) + + def set_default_alignment(self, d): + """ + Set the default alignment. See `set_axis_direction` for details. + + Parameters + ---------- + d : {"left", "bottom", "right", "top"} + """ + va, ha = _api.check_getitem(self._default_alignments, d=d) + self.set_va(va) + self.set_ha(ha) + + _default_angles = dict(left=180, + right=0, + bottom=0, + top=180) + + def set_default_angle(self, d): + """ + Set the default angle. See `set_axis_direction` for details. + + Parameters + ---------- + d : {"left", "bottom", "right", "top"} + """ + self.set_rotation(_api.check_getitem(self._default_angles, d=d)) + + def set_axis_direction(self, d): + """ + Adjust the text angle and text alignment of axis label + according to the matplotlib convention. + + ===================== ========== ========= ========== ========== + Property left bottom right top + ===================== ========== ========= ========== ========== + axislabel angle 180 0 0 180 + axislabel va center top center bottom + axislabel ha right center right center + ===================== ========== ========= ========== ========== + + Note that the text angles are actually relative to (90 + angle + of the direction to the ticklabel), which gives 0 for bottom + axis. + + Parameters + ---------- + d : {"left", "bottom", "right", "top"} + """ + self.set_default_alignment(d) + self.set_default_angle(d) + + def get_color(self): + return self.get_attribute_from_ref_artist("color") + + def draw(self, renderer): + if not self.get_visible(): + return + + self._offset_radius = \ + self._external_pad + renderer.points_to_pixels(self.get_pad()) + + super().draw(renderer) + + def get_window_extent(self, renderer=None): + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + if not self.get_visible(): + return + + r = self._external_pad + renderer.points_to_pixels(self.get_pad()) + self._offset_radius = r + + bb = super().get_window_extent(renderer) + + return bb + + +class TickLabels(AxisLabel): # mtext.Text + """ + Tick labels. While derived from `.Text`, this single artist draws all + ticklabels. As in `.AxisLabel`, the position of the text is updated + in the fly, so changing text position has no effect. Otherwise, + the properties can be changed as a normal `.Text`. Unlike the + ticklabels of the mainline Matplotlib, properties of a single + ticklabel alone cannot be modified. + + To change the pad between ticks and ticklabels, use `~.AxisLabel.set_pad`. + """ + + def __init__(self, *, axis_direction="bottom", **kwargs): + super().__init__(**kwargs) + self.set_axis_direction(axis_direction) + self._axislabel_pad = 0 + + def get_ref_artist(self): + # docstring inherited + return self._axis.get_ticklabels()[0] + + def set_axis_direction(self, label_direction): + """ + Adjust the text angle and text alignment of ticklabels + according to the Matplotlib convention. + + The *label_direction* must be one of [left, right, bottom, top]. + + ===================== ========== ========= ========== ========== + Property left bottom right top + ===================== ========== ========= ========== ========== + ticklabel angle 90 0 -90 180 + ticklabel va center baseline center baseline + ticklabel ha right center right center + ===================== ========== ========= ========== ========== + + Note that the text angles are actually relative to (90 + angle + of the direction to the ticklabel), which gives 0 for bottom + axis. + + Parameters + ---------- + label_direction : {"left", "bottom", "right", "top"} + + """ + self.set_default_alignment(label_direction) + self.set_default_angle(label_direction) + self._axis_direction = label_direction + + def invert_axis_direction(self): + label_direction = self._get_opposite_direction(self._axis_direction) + self.set_axis_direction(label_direction) + + def _get_ticklabels_offsets(self, renderer, label_direction): + """ + Calculate the ticklabel offsets from the tick and their total heights. + + The offset only takes account the offset due to the vertical alignment + of the ticklabels: if axis direction is bottom and va is 'top', it will + return 0; if va is 'baseline', it will return (height-descent). + """ + whd_list = self.get_texts_widths_heights_descents(renderer) + + if not whd_list: + return 0, 0 + + r = 0 + va, ha = self.get_va(), self.get_ha() + + if label_direction == "left": + pad = max(w for w, h, d in whd_list) + if ha == "left": + r = pad + elif ha == "center": + r = .5 * pad + elif label_direction == "right": + pad = max(w for w, h, d in whd_list) + if ha == "right": + r = pad + elif ha == "center": + r = .5 * pad + elif label_direction == "bottom": + pad = max(h for w, h, d in whd_list) + if va == "bottom": + r = pad + elif va == "center": + r = .5 * pad + elif va == "baseline": + max_ascent = max(h - d for w, h, d in whd_list) + max_descent = max(d for w, h, d in whd_list) + r = max_ascent + pad = max_ascent + max_descent + elif label_direction == "top": + pad = max(h for w, h, d in whd_list) + if va == "top": + r = pad + elif va == "center": + r = .5 * pad + elif va == "baseline": + max_ascent = max(h - d for w, h, d in whd_list) + max_descent = max(d for w, h, d in whd_list) + r = max_descent + pad = max_ascent + max_descent + + # r : offset + # pad : total height of the ticklabels. This will be used to + # calculate the pad for the axislabel. + return r, pad + + _default_alignments = dict(left=("center", "right"), + right=("center", "left"), + bottom=("baseline", "center"), + top=("baseline", "center")) + + _default_angles = dict(left=90, + right=-90, + bottom=0, + top=180) + + def draw(self, renderer): + if not self.get_visible(): + self._axislabel_pad = self._external_pad + return + + r, total_width = self._get_ticklabels_offsets(renderer, + self._axis_direction) + + pad = self._external_pad + renderer.points_to_pixels(self.get_pad()) + self._offset_radius = r + pad + + for (x, y), a, l in self._locs_angles_labels: + if not l.strip(): + continue + self._ref_angle = a + self.set_x(x) + self.set_y(y) + self.set_text(l) + LabelBase.draw(self, renderer) + + # the value saved will be used to draw axislabel. + self._axislabel_pad = total_width + pad + + def set_locs_angles_labels(self, locs_angles_labels): + self._locs_angles_labels = locs_angles_labels + + def get_window_extents(self, renderer=None): + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + if not self.get_visible(): + self._axislabel_pad = self._external_pad + return [] + + bboxes = [] + + r, total_width = self._get_ticklabels_offsets(renderer, + self._axis_direction) + + pad = self._external_pad + renderer.points_to_pixels(self.get_pad()) + self._offset_radius = r + pad + + for (x, y), a, l in self._locs_angles_labels: + self._ref_angle = a + self.set_x(x) + self.set_y(y) + self.set_text(l) + bb = LabelBase.get_window_extent(self, renderer) + bboxes.append(bb) + + # the value saved will be used to draw axislabel. + self._axislabel_pad = total_width + pad + + return bboxes + + def get_texts_widths_heights_descents(self, renderer): + """ + Return a list of ``(width, height, descent)`` tuples for ticklabels. + + Empty labels are left out. + """ + whd_list = [] + for _loc, _angle, label in self._locs_angles_labels: + if not label.strip(): + continue + clean_line, ismath = self._preprocess_math(label) + whd = mtext._get_text_metrics_with_cache( + renderer, clean_line, self._fontproperties, ismath=ismath, + dpi=self.get_figure(root=True).dpi) + whd_list.append(whd) + return whd_list + + +class GridlinesCollection(LineCollection): + def __init__(self, *args, which="major", axis="both", **kwargs): + """ + Collection of grid lines. + + Parameters + ---------- + which : {"major", "minor"} + Which grid to consider. + axis : {"both", "x", "y"} + Which axis to consider. + *args, **kwargs + Passed to `.LineCollection`. + """ + self._which = which + self._axis = axis + super().__init__(*args, **kwargs) + self.set_grid_helper(None) + + def set_which(self, which): + """ + Select major or minor grid lines. + + Parameters + ---------- + which : {"major", "minor"} + """ + self._which = which + + def set_axis(self, axis): + """ + Select axis. + + Parameters + ---------- + axis : {"both", "x", "y"} + """ + self._axis = axis + + def set_grid_helper(self, grid_helper): + """ + Set grid helper. + + Parameters + ---------- + grid_helper : `.GridHelperBase` subclass + """ + self._grid_helper = grid_helper + + def draw(self, renderer): + if self._grid_helper is not None: + self._grid_helper.update_lim(self.axes) + gl = self._grid_helper.get_gridlines(self._which, self._axis) + self.set_segments([np.transpose(l) for l in gl]) + super().draw(renderer) + + +class AxisArtist(martist.Artist): + """ + An artist which draws axis (a line along which the n-th axes coord + is constant) line, ticks, tick labels, and axis label. + """ + + zorder = 2.5 + + @property + def LABELPAD(self): + return self.label.get_pad() + + @LABELPAD.setter + def LABELPAD(self, v): + self.label.set_pad(v) + + def __init__(self, axes, + helper, + offset=None, + axis_direction="bottom", + **kwargs): + """ + Parameters + ---------- + axes : `mpl_toolkits.axisartist.axislines.Axes` + helper : `~mpl_toolkits.axisartist.axislines.AxisArtistHelper` + """ + # axes is also used to follow the axis attribute (tick color, etc). + + super().__init__(**kwargs) + + self.axes = axes + + self._axis_artist_helper = helper + + if offset is None: + offset = (0, 0) + self.offset_transform = ScaledTranslation( + *offset, + Affine2D().scale(1 / 72) # points to inches. + + self.axes.get_figure(root=False).dpi_scale_trans) + + if axis_direction in ["left", "right"]: + self.axis = axes.yaxis + else: + self.axis = axes.xaxis + + self._axisline_style = None + self._axis_direction = axis_direction + + self._init_line() + self._init_ticks(**kwargs) + self._init_offsetText(axis_direction) + self._init_label() + + # axis direction + self._ticklabel_add_angle = 0. + self._axislabel_add_angle = 0. + self.set_axis_direction(axis_direction) + + # axis direction + + def set_axis_direction(self, axis_direction): + """ + Adjust the direction, text angle, and text alignment of tick labels + and axis labels following the Matplotlib convention for the rectangle + axes. + + The *axis_direction* must be one of [left, right, bottom, top]. + + ===================== ========== ========= ========== ========== + Property left bottom right top + ===================== ========== ========= ========== ========== + ticklabel direction "-" "+" "+" "-" + axislabel direction "-" "+" "+" "-" + ticklabel angle 90 0 -90 180 + ticklabel va center baseline center baseline + ticklabel ha right center right center + axislabel angle 180 0 0 180 + axislabel va center top center bottom + axislabel ha right center right center + ===================== ========== ========= ========== ========== + + Note that the direction "+" and "-" are relative to the direction of + the increasing coordinate. Also, the text angles are actually + relative to (90 + angle of the direction to the ticklabel), + which gives 0 for bottom axis. + + Parameters + ---------- + axis_direction : {"left", "bottom", "right", "top"} + """ + self.major_ticklabels.set_axis_direction(axis_direction) + self.label.set_axis_direction(axis_direction) + self._axis_direction = axis_direction + if axis_direction in ["left", "top"]: + self.set_ticklabel_direction("-") + self.set_axislabel_direction("-") + else: + self.set_ticklabel_direction("+") + self.set_axislabel_direction("+") + + def set_ticklabel_direction(self, tick_direction): + r""" + Adjust the direction of the tick labels. + + Note that the *tick_direction*\s '+' and '-' are relative to the + direction of the increasing coordinate. + + Parameters + ---------- + tick_direction : {"+", "-"} + """ + self._ticklabel_add_angle = _api.check_getitem( + {"+": 0, "-": 180}, tick_direction=tick_direction) + + def invert_ticklabel_direction(self): + self._ticklabel_add_angle = (self._ticklabel_add_angle + 180) % 360 + self.major_ticklabels.invert_axis_direction() + self.minor_ticklabels.invert_axis_direction() + + def set_axislabel_direction(self, label_direction): + r""" + Adjust the direction of the axis label. + + Note that the *label_direction*\s '+' and '-' are relative to the + direction of the increasing coordinate. + + Parameters + ---------- + label_direction : {"+", "-"} + """ + self._axislabel_add_angle = _api.check_getitem( + {"+": 0, "-": 180}, label_direction=label_direction) + + def get_transform(self): + return self.axes.transAxes + self.offset_transform + + def get_helper(self): + """ + Return axis artist helper instance. + """ + return self._axis_artist_helper + + def set_axisline_style(self, axisline_style=None, **kwargs): + """ + Set the axisline style. + + The new style is completely defined by the passed attributes. Existing + style attributes are forgotten. + + Parameters + ---------- + axisline_style : str or None + The line style, e.g. '->', optionally followed by a comma-separated + list of attributes. Alternatively, the attributes can be provided + as keywords. + + If *None* this returns a string containing the available styles. + + Examples + -------- + The following two commands are equal: + + >>> set_axisline_style("->,size=1.5") + >>> set_axisline_style("->", size=1.5) + """ + if axisline_style is None: + return AxislineStyle.pprint_styles() + + if isinstance(axisline_style, AxislineStyle._Base): + self._axisline_style = axisline_style + else: + self._axisline_style = AxislineStyle(axisline_style, **kwargs) + + self._init_line() + + def get_axisline_style(self): + """Return the current axisline style.""" + return self._axisline_style + + def _init_line(self): + """ + Initialize the *line* artist that is responsible to draw the axis line. + """ + tran = (self._axis_artist_helper.get_line_transform(self.axes) + + self.offset_transform) + + axisline_style = self.get_axisline_style() + if axisline_style is None: + self.line = PathPatch( + self._axis_artist_helper.get_line(self.axes), + color=mpl.rcParams['axes.edgecolor'], + fill=False, + linewidth=mpl.rcParams['axes.linewidth'], + capstyle=mpl.rcParams['lines.solid_capstyle'], + joinstyle=mpl.rcParams['lines.solid_joinstyle'], + transform=tran) + else: + self.line = axisline_style(self, transform=tran) + + def _draw_line(self, renderer): + self.line.set_path(self._axis_artist_helper.get_line(self.axes)) + if self.get_axisline_style() is not None: + self.line.set_line_mutation_scale(self.major_ticklabels.get_size()) + self.line.draw(renderer) + + def _init_ticks(self, **kwargs): + axis_name = self.axis.axis_name + + trans = (self._axis_artist_helper.get_tick_transform(self.axes) + + self.offset_transform) + + self.major_ticks = Ticks( + kwargs.get( + "major_tick_size", + mpl.rcParams[f"{axis_name}tick.major.size"]), + axis=self.axis, transform=trans) + self.minor_ticks = Ticks( + kwargs.get( + "minor_tick_size", + mpl.rcParams[f"{axis_name}tick.minor.size"]), + axis=self.axis, transform=trans) + + size = mpl.rcParams[f"{axis_name}tick.labelsize"] + self.major_ticklabels = TickLabels( + axis=self.axis, + axis_direction=self._axis_direction, + figure=self.axes.get_figure(root=False), + transform=trans, + fontsize=size, + pad=kwargs.get( + "major_tick_pad", mpl.rcParams[f"{axis_name}tick.major.pad"]), + ) + self.minor_ticklabels = TickLabels( + axis=self.axis, + axis_direction=self._axis_direction, + figure=self.axes.get_figure(root=False), + transform=trans, + fontsize=size, + pad=kwargs.get( + "minor_tick_pad", mpl.rcParams[f"{axis_name}tick.minor.pad"]), + ) + + def _get_tick_info(self, tick_iter): + """ + Return a pair of: + + - list of locs and angles for ticks + - list of locs, angles and labels for ticklabels. + """ + ticks_loc_angle = [] + ticklabels_loc_angle_label = [] + + ticklabel_add_angle = self._ticklabel_add_angle + + for loc, angle_normal, angle_tangent, label in tick_iter: + angle_label = angle_tangent - 90 + ticklabel_add_angle + angle_tick = (angle_normal + if 90 <= (angle_label - angle_normal) % 360 <= 270 + else angle_normal + 180) + ticks_loc_angle.append([loc, angle_tick]) + ticklabels_loc_angle_label.append([loc, angle_label, label]) + + return ticks_loc_angle, ticklabels_loc_angle_label + + def _update_ticks(self, renderer=None): + # set extra pad for major and minor ticklabels: use ticksize of + # majorticks even for minor ticks. not clear what is best. + + if renderer is None: + renderer = self.get_figure(root=True)._get_renderer() + + dpi_cor = renderer.points_to_pixels(1.) + if self.major_ticks.get_visible() and self.major_ticks.get_tick_out(): + ticklabel_pad = self.major_ticks._ticksize * dpi_cor + self.major_ticklabels._external_pad = ticklabel_pad + self.minor_ticklabels._external_pad = ticklabel_pad + else: + self.major_ticklabels._external_pad = 0 + self.minor_ticklabels._external_pad = 0 + + majortick_iter, minortick_iter = \ + self._axis_artist_helper.get_tick_iterators(self.axes) + + tick_loc_angle, ticklabel_loc_angle_label = \ + self._get_tick_info(majortick_iter) + self.major_ticks.set_locs_angles(tick_loc_angle) + self.major_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label) + + tick_loc_angle, ticklabel_loc_angle_label = \ + self._get_tick_info(minortick_iter) + self.minor_ticks.set_locs_angles(tick_loc_angle) + self.minor_ticklabels.set_locs_angles_labels(ticklabel_loc_angle_label) + + def _draw_ticks(self, renderer): + self._update_ticks(renderer) + self.major_ticks.draw(renderer) + self.major_ticklabels.draw(renderer) + self.minor_ticks.draw(renderer) + self.minor_ticklabels.draw(renderer) + if (self.major_ticklabels.get_visible() + or self.minor_ticklabels.get_visible()): + self._draw_offsetText(renderer) + + _offsetText_pos = dict(left=(0, 1, "bottom", "right"), + right=(1, 1, "bottom", "left"), + bottom=(1, 0, "top", "right"), + top=(1, 1, "bottom", "right")) + + def _init_offsetText(self, direction): + x, y, va, ha = self._offsetText_pos[direction] + self.offsetText = mtext.Annotation( + "", + xy=(x, y), xycoords="axes fraction", + xytext=(0, 0), textcoords="offset points", + color=mpl.rcParams['xtick.color'], + horizontalalignment=ha, verticalalignment=va, + ) + self.offsetText.set_transform(IdentityTransform()) + self.axes._set_artist_props(self.offsetText) + + def _update_offsetText(self): + self.offsetText.set_text(self.axis.major.formatter.get_offset()) + self.offsetText.set_size(self.major_ticklabels.get_size()) + offset = (self.major_ticklabels.get_pad() + + self.major_ticklabels.get_size() + + 2) + self.offsetText.xyann = (0, offset) + + def _draw_offsetText(self, renderer): + self._update_offsetText() + self.offsetText.draw(renderer) + + def _init_label(self, **kwargs): + tr = (self._axis_artist_helper.get_axislabel_transform(self.axes) + + self.offset_transform) + self.label = AxisLabel( + 0, 0, "__from_axes__", + color="auto", + fontsize=kwargs.get("labelsize", mpl.rcParams['axes.labelsize']), + fontweight=mpl.rcParams['axes.labelweight'], + axis=self.axis, + transform=tr, + axis_direction=self._axis_direction, + ) + self.label.set_figure(self.axes.get_figure(root=False)) + labelpad = kwargs.get("labelpad", 5) + self.label.set_pad(labelpad) + + def _update_label(self, renderer): + if not self.label.get_visible(): + return + + if self._ticklabel_add_angle != self._axislabel_add_angle: + if ((self.major_ticks.get_visible() + and not self.major_ticks.get_tick_out()) + or (self.minor_ticks.get_visible() + and not self.major_ticks.get_tick_out())): + axislabel_pad = self.major_ticks._ticksize + else: + axislabel_pad = 0 + else: + axislabel_pad = max(self.major_ticklabels._axislabel_pad, + self.minor_ticklabels._axislabel_pad) + + self.label._external_pad = axislabel_pad + + xy, angle_tangent = \ + self._axis_artist_helper.get_axislabel_pos_angle(self.axes) + if xy is None: + return + + angle_label = angle_tangent - 90 + + x, y = xy + self.label._ref_angle = angle_label + self._axislabel_add_angle + self.label.set(x=x, y=y) + + def _draw_label(self, renderer): + self._update_label(renderer) + self.label.draw(renderer) + + def set_label(self, s): + # docstring inherited + self.label.set_text(s) + + def get_tightbbox(self, renderer=None): + if not self.get_visible(): + return + self._axis_artist_helper.update_lim(self.axes) + self._update_ticks(renderer) + self._update_label(renderer) + + self.line.set_path(self._axis_artist_helper.get_line(self.axes)) + if self.get_axisline_style() is not None: + self.line.set_line_mutation_scale(self.major_ticklabels.get_size()) + + bb = [ + *self.major_ticklabels.get_window_extents(renderer), + *self.minor_ticklabels.get_window_extents(renderer), + self.label.get_window_extent(renderer), + self.offsetText.get_window_extent(renderer), + self.line.get_window_extent(renderer), + ] + bb = [b for b in bb if b and (b.width != 0 or b.height != 0)] + if bb: + _bbox = Bbox.union(bb) + return _bbox + else: + return None + + @martist.allow_rasterization + def draw(self, renderer): + # docstring inherited + if not self.get_visible(): + return + renderer.open_group(__name__, gid=self.get_gid()) + self._axis_artist_helper.update_lim(self.axes) + self._draw_ticks(renderer) + self._draw_line(renderer) + self._draw_label(renderer) + renderer.close_group(__name__) + + def toggle(self, all=None, ticks=None, ticklabels=None, label=None): + """ + Toggle visibility of ticks, ticklabels, and (axis) label. + To turn all off, :: + + axis.toggle(all=False) + + To turn all off but ticks on :: + + axis.toggle(all=False, ticks=True) + + To turn all on but (axis) label off :: + + axis.toggle(all=True, label=False) + + """ + if all: + _ticks, _ticklabels, _label = True, True, True + elif all is not None: + _ticks, _ticklabels, _label = False, False, False + else: + _ticks, _ticklabels, _label = None, None, None + + if ticks is not None: + _ticks = ticks + if ticklabels is not None: + _ticklabels = ticklabels + if label is not None: + _label = label + + if _ticks is not None: + self.major_ticks.set_visible(_ticks) + self.minor_ticks.set_visible(_ticks) + if _ticklabels is not None: + self.major_ticklabels.set_visible(_ticklabels) + self.minor_ticklabels.set_visible(_ticklabels) + if _label is not None: + self.label.set_visible(_label) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axisline_style.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axisline_style.py new file mode 100644 index 0000000000000000000000000000000000000000..7f25b98082ef52b9f162542a3eafaec3b9750fd0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axisline_style.py @@ -0,0 +1,193 @@ +""" +Provides classes to style the axis lines. +""" +import math + +import numpy as np + +import matplotlib as mpl +from matplotlib.patches import _Style, FancyArrowPatch +from matplotlib.path import Path +from matplotlib.transforms import IdentityTransform + + +class _FancyAxislineStyle: + class SimpleArrow(FancyArrowPatch): + """The artist class that will be returned for SimpleArrow style.""" + _ARROW_STYLE = "->" + + def __init__(self, axis_artist, line_path, transform, + line_mutation_scale): + self._axis_artist = axis_artist + self._line_transform = transform + self._line_path = line_path + self._line_mutation_scale = line_mutation_scale + + FancyArrowPatch.__init__(self, + path=self._line_path, + arrowstyle=self._ARROW_STYLE, + patchA=None, + patchB=None, + shrinkA=0., + shrinkB=0., + mutation_scale=line_mutation_scale, + mutation_aspect=None, + transform=IdentityTransform(), + ) + + def set_line_mutation_scale(self, scale): + self.set_mutation_scale(scale*self._line_mutation_scale) + + def _extend_path(self, path, mutation_size=10): + """ + Extend the path to make a room for drawing arrow. + """ + (x0, y0), (x1, y1) = path.vertices[-2:] + theta = math.atan2(y1 - y0, x1 - x0) + x2 = x1 + math.cos(theta) * mutation_size + y2 = y1 + math.sin(theta) * mutation_size + if path.codes is None: + return Path(np.concatenate([path.vertices, [[x2, y2]]])) + else: + return Path(np.concatenate([path.vertices, [[x2, y2]]]), + np.concatenate([path.codes, [Path.LINETO]])) + + def set_path(self, path): + self._line_path = path + + def draw(self, renderer): + """ + Draw the axis line. + 1) Transform the path to the display coordinate. + 2) Extend the path to make a room for arrow. + 3) Update the path of the FancyArrowPatch. + 4) Draw. + """ + path_in_disp = self._line_transform.transform_path(self._line_path) + mutation_size = self.get_mutation_scale() # line_mutation_scale() + extended_path = self._extend_path(path_in_disp, + mutation_size=mutation_size) + self._path_original = extended_path + FancyArrowPatch.draw(self, renderer) + + def get_window_extent(self, renderer=None): + + path_in_disp = self._line_transform.transform_path(self._line_path) + mutation_size = self.get_mutation_scale() # line_mutation_scale() + extended_path = self._extend_path(path_in_disp, + mutation_size=mutation_size) + self._path_original = extended_path + return FancyArrowPatch.get_window_extent(self, renderer) + + class FilledArrow(SimpleArrow): + """The artist class that will be returned for FilledArrow style.""" + _ARROW_STYLE = "-|>" + + def __init__(self, axis_artist, line_path, transform, + line_mutation_scale, facecolor): + super().__init__(axis_artist, line_path, transform, + line_mutation_scale) + self.set_facecolor(facecolor) + + +class AxislineStyle(_Style): + """ + A container class which defines style classes for AxisArtists. + + An instance of any axisline style class is a callable object, + whose call signature is :: + + __call__(self, axis_artist, path, transform) + + When called, this should return an `.Artist` with the following methods:: + + def set_path(self, path): + # set the path for axisline. + + def set_line_mutation_scale(self, scale): + # set the scale + + def draw(self, renderer): + # draw + """ + + _style_list = {} + + class _Base: + # The derived classes are required to be able to be initialized + # w/o arguments, i.e., all its argument (except self) must have + # the default values. + + def __init__(self): + """ + initialization. + """ + super().__init__() + + def __call__(self, axis_artist, transform): + """ + Given the AxisArtist instance, and transform for the path (set_path + method), return the Matplotlib artist for drawing the axis line. + """ + return self.new_line(axis_artist, transform) + + class SimpleArrow(_Base): + """ + A simple arrow. + """ + + ArrowAxisClass = _FancyAxislineStyle.SimpleArrow + + def __init__(self, size=1): + """ + Parameters + ---------- + size : float + Size of the arrow as a fraction of the ticklabel size. + """ + + self.size = size + super().__init__() + + def new_line(self, axis_artist, transform): + + linepath = Path([(0, 0), (0, 1)]) + axisline = self.ArrowAxisClass(axis_artist, linepath, transform, + line_mutation_scale=self.size) + return axisline + + _style_list["->"] = SimpleArrow + + class FilledArrow(SimpleArrow): + """ + An arrow with a filled head. + """ + + ArrowAxisClass = _FancyAxislineStyle.FilledArrow + + def __init__(self, size=1, facecolor=None): + """ + Parameters + ---------- + size : float + Size of the arrow as a fraction of the ticklabel size. + facecolor : :mpltype:`color`, default: :rc:`axes.edgecolor` + Fill color. + + .. versionadded:: 3.7 + """ + + if facecolor is None: + facecolor = mpl.rcParams['axes.edgecolor'] + self.size = size + self._facecolor = facecolor + super().__init__(size=size) + + def new_line(self, axis_artist, transform): + linepath = Path([(0, 0), (0, 1)]) + axisline = self.ArrowAxisClass(axis_artist, linepath, transform, + line_mutation_scale=self.size, + facecolor=self._facecolor) + return axisline + + _style_list["-|>"] = FilledArrow diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axislines.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axislines.py new file mode 100644 index 0000000000000000000000000000000000000000..8d06cb236269d00ed20a27297b59fa816338e79a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/axislines.py @@ -0,0 +1,479 @@ +""" +Axislines includes modified implementation of the Axes class. The +biggest difference is that the artists responsible for drawing the axis spine, +ticks, ticklabels and axis labels are separated out from Matplotlib's Axis +class. Originally, this change was motivated to support curvilinear +grid. Here are a few reasons that I came up with a new axes class: + +* "top" and "bottom" x-axis (or "left" and "right" y-axis) can have + different ticks (tick locations and labels). This is not possible + with the current Matplotlib, although some twin axes trick can help. + +* Curvilinear grid. + +* angled ticks. + +In the new axes class, xaxis and yaxis is set to not visible by +default, and new set of artist (AxisArtist) are defined to draw axis +line, ticks, ticklabels and axis label. Axes.axis attribute serves as +a dictionary of these artists, i.e., ax.axis["left"] is a AxisArtist +instance responsible to draw left y-axis. The default Axes.axis contains +"bottom", "left", "top" and "right". + +AxisArtist can be considered as a container artist and has the following +children artists which will draw ticks, labels, etc. + +* line +* major_ticks, major_ticklabels +* minor_ticks, minor_ticklabels +* offsetText +* label + +Note that these are separate artists from `matplotlib.axis.Axis`, thus most +tick-related functions in Matplotlib won't work. For example, color and +markerwidth of the ``ax.axis["bottom"].major_ticks`` will follow those of +Axes.xaxis unless explicitly specified. + +In addition to AxisArtist, the Axes will have *gridlines* attribute, +which obviously draws grid lines. The gridlines needs to be separated +from the axis as some gridlines can never pass any axis. +""" + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api +import matplotlib.axes as maxes +from matplotlib.path import Path +from mpl_toolkits.axes_grid1 import mpl_axes +from .axisline_style import AxislineStyle # noqa +from .axis_artist import AxisArtist, GridlinesCollection + + +class _AxisArtistHelperBase: + """ + Base class for axis helper. + + Subclasses should define the methods listed below. The *axes* + argument will be the ``.axes`` attribute of the caller artist. :: + + # Construct the spine. + + def get_line_transform(self, axes): + return transform + + def get_line(self, axes): + return path + + # Construct the label. + + def get_axislabel_transform(self, axes): + return transform + + def get_axislabel_pos_angle(self, axes): + return (x, y), angle + + # Construct the ticks. + + def get_tick_transform(self, axes): + return transform + + def get_tick_iterators(self, axes): + # A pair of iterables (one for major ticks, one for minor ticks) + # that yield (tick_position, tick_angle, tick_label). + return iter_major, iter_minor + """ + + def __init__(self, nth_coord): + self.nth_coord = nth_coord + + def update_lim(self, axes): + pass + + def get_nth_coord(self): + return self.nth_coord + + def _to_xy(self, values, const): + """ + Create a (*values.shape, 2)-shape array representing (x, y) pairs. + + The other coordinate is filled with the constant *const*. + + Example:: + + >>> self.nth_coord = 0 + >>> self._to_xy([1, 2, 3], const=0) + array([[1, 0], + [2, 0], + [3, 0]]) + """ + if self.nth_coord == 0: + return np.stack(np.broadcast_arrays(values, const), axis=-1) + elif self.nth_coord == 1: + return np.stack(np.broadcast_arrays(const, values), axis=-1) + else: + raise ValueError("Unexpected nth_coord") + + +class _FixedAxisArtistHelperBase(_AxisArtistHelperBase): + """Helper class for a fixed (in the axes coordinate) axis.""" + + @_api.delete_parameter("3.9", "nth_coord") + def __init__(self, loc, nth_coord=None): + """``nth_coord = 0``: x-axis; ``nth_coord = 1``: y-axis.""" + super().__init__(_api.check_getitem( + {"bottom": 0, "top": 0, "left": 1, "right": 1}, loc=loc)) + self._loc = loc + self._pos = {"bottom": 0, "top": 1, "left": 0, "right": 1}[loc] + # axis line in transAxes + self._path = Path(self._to_xy((0, 1), const=self._pos)) + + # LINE + + def get_line(self, axes): + return self._path + + def get_line_transform(self, axes): + return axes.transAxes + + # LABEL + + def get_axislabel_transform(self, axes): + return axes.transAxes + + def get_axislabel_pos_angle(self, axes): + """ + Return the label reference position in transAxes. + + get_label_transform() returns a transform of (transAxes+offset) + """ + return dict(left=((0., 0.5), 90), # (position, angle_tangent) + right=((1., 0.5), 90), + bottom=((0.5, 0.), 0), + top=((0.5, 1.), 0))[self._loc] + + # TICK + + def get_tick_transform(self, axes): + return [axes.get_xaxis_transform(), axes.get_yaxis_transform()][self.nth_coord] + + +class _FloatingAxisArtistHelperBase(_AxisArtistHelperBase): + def __init__(self, nth_coord, value): + self._value = value + super().__init__(nth_coord) + + def get_line(self, axes): + raise RuntimeError("get_line method should be defined by the derived class") + + +class FixedAxisArtistHelperRectilinear(_FixedAxisArtistHelperBase): + + @_api.delete_parameter("3.9", "nth_coord") + def __init__(self, axes, loc, nth_coord=None): + """ + nth_coord = along which coordinate value varies + in 2D, nth_coord = 0 -> x axis, nth_coord = 1 -> y axis + """ + super().__init__(loc) + self.axis = [axes.xaxis, axes.yaxis][self.nth_coord] + + # TICK + + def get_tick_iterators(self, axes): + """tick_loc, tick_angle, tick_label""" + angle_normal, angle_tangent = {0: (90, 0), 1: (0, 90)}[self.nth_coord] + + major = self.axis.major + major_locs = major.locator() + major_labels = major.formatter.format_ticks(major_locs) + + minor = self.axis.minor + minor_locs = minor.locator() + minor_labels = minor.formatter.format_ticks(minor_locs) + + tick_to_axes = self.get_tick_transform(axes) - axes.transAxes + + def _f(locs, labels): + for loc, label in zip(locs, labels): + c = self._to_xy(loc, const=self._pos) + # check if the tick point is inside axes + c2 = tick_to_axes.transform(c) + if mpl.transforms._interval_contains_close((0, 1), c2[self.nth_coord]): + yield c, angle_normal, angle_tangent, label + + return _f(major_locs, major_labels), _f(minor_locs, minor_labels) + + +class FloatingAxisArtistHelperRectilinear(_FloatingAxisArtistHelperBase): + + def __init__(self, axes, nth_coord, + passingthrough_point, axis_direction="bottom"): + super().__init__(nth_coord, passingthrough_point) + self._axis_direction = axis_direction + self.axis = [axes.xaxis, axes.yaxis][self.nth_coord] + + def get_line(self, axes): + fixed_coord = 1 - self.nth_coord + data_to_axes = axes.transData - axes.transAxes + p = data_to_axes.transform([self._value, self._value]) + return Path(self._to_xy((0, 1), const=p[fixed_coord])) + + def get_line_transform(self, axes): + return axes.transAxes + + def get_axislabel_transform(self, axes): + return axes.transAxes + + def get_axislabel_pos_angle(self, axes): + """ + Return the label reference position in transAxes. + + get_label_transform() returns a transform of (transAxes+offset) + """ + angle = [0, 90][self.nth_coord] + fixed_coord = 1 - self.nth_coord + data_to_axes = axes.transData - axes.transAxes + p = data_to_axes.transform([self._value, self._value]) + verts = self._to_xy(0.5, const=p[fixed_coord]) + return (verts, angle) if 0 <= verts[fixed_coord] <= 1 else (None, None) + + def get_tick_transform(self, axes): + return axes.transData + + def get_tick_iterators(self, axes): + """tick_loc, tick_angle, tick_label""" + angle_normal, angle_tangent = {0: (90, 0), 1: (0, 90)}[self.nth_coord] + + major = self.axis.major + major_locs = major.locator() + major_labels = major.formatter.format_ticks(major_locs) + + minor = self.axis.minor + minor_locs = minor.locator() + minor_labels = minor.formatter.format_ticks(minor_locs) + + data_to_axes = axes.transData - axes.transAxes + + def _f(locs, labels): + for loc, label in zip(locs, labels): + c = self._to_xy(loc, const=self._value) + c1, c2 = data_to_axes.transform(c) + if 0 <= c1 <= 1 and 0 <= c2 <= 1: + yield c, angle_normal, angle_tangent, label + + return _f(major_locs, major_labels), _f(minor_locs, minor_labels) + + +class AxisArtistHelper: # Backcompat. + Fixed = _FixedAxisArtistHelperBase + Floating = _FloatingAxisArtistHelperBase + + +class AxisArtistHelperRectlinear: # Backcompat. + Fixed = FixedAxisArtistHelperRectilinear + Floating = FloatingAxisArtistHelperRectilinear + + +class GridHelperBase: + + def __init__(self): + self._old_limits = None + super().__init__() + + def update_lim(self, axes): + x1, x2 = axes.get_xlim() + y1, y2 = axes.get_ylim() + if self._old_limits != (x1, x2, y1, y2): + self._update_grid(x1, y1, x2, y2) + self._old_limits = (x1, x2, y1, y2) + + def _update_grid(self, x1, y1, x2, y2): + """Cache relevant computations when the axes limits have changed.""" + + def get_gridlines(self, which, axis): + """ + Return list of grid lines as a list of paths (list of points). + + Parameters + ---------- + which : {"both", "major", "minor"} + axis : {"both", "x", "y"} + """ + return [] + + +class GridHelperRectlinear(GridHelperBase): + + def __init__(self, axes): + super().__init__() + self.axes = axes + + @_api.delete_parameter( + "3.9", "nth_coord", addendum="'nth_coord' is now inferred from 'loc'.") + def new_fixed_axis( + self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): + if axes is None: + _api.warn_external( + "'new_fixed_axis' explicitly requires the axes keyword.") + axes = self.axes + if axis_direction is None: + axis_direction = loc + return AxisArtist(axes, FixedAxisArtistHelperRectilinear(axes, loc), + offset=offset, axis_direction=axis_direction) + + def new_floating_axis(self, nth_coord, value, axis_direction="bottom", axes=None): + if axes is None: + _api.warn_external( + "'new_floating_axis' explicitly requires the axes keyword.") + axes = self.axes + helper = FloatingAxisArtistHelperRectilinear( + axes, nth_coord, value, axis_direction) + axisline = AxisArtist(axes, helper, axis_direction=axis_direction) + axisline.line.set_clip_on(True) + axisline.line.set_clip_box(axisline.axes.bbox) + return axisline + + def get_gridlines(self, which="major", axis="both"): + """ + Return list of gridline coordinates in data coordinates. + + Parameters + ---------- + which : {"both", "major", "minor"} + axis : {"both", "x", "y"} + """ + _api.check_in_list(["both", "major", "minor"], which=which) + _api.check_in_list(["both", "x", "y"], axis=axis) + gridlines = [] + + if axis in ("both", "x"): + locs = [] + y1, y2 = self.axes.get_ylim() + if which in ("both", "major"): + locs.extend(self.axes.xaxis.major.locator()) + if which in ("both", "minor"): + locs.extend(self.axes.xaxis.minor.locator()) + gridlines.extend([[x, x], [y1, y2]] for x in locs) + + if axis in ("both", "y"): + x1, x2 = self.axes.get_xlim() + locs = [] + if self.axes.yaxis._major_tick_kw["gridOn"]: + locs.extend(self.axes.yaxis.major.locator()) + if self.axes.yaxis._minor_tick_kw["gridOn"]: + locs.extend(self.axes.yaxis.minor.locator()) + gridlines.extend([[x1, x2], [y, y]] for y in locs) + + return gridlines + + +class Axes(maxes.Axes): + + def __init__(self, *args, grid_helper=None, **kwargs): + self._axisline_on = True + self._grid_helper = grid_helper if grid_helper else GridHelperRectlinear(self) + super().__init__(*args, **kwargs) + self.toggle_axisline(True) + + def toggle_axisline(self, b=None): + if b is None: + b = not self._axisline_on + if b: + self._axisline_on = True + self.spines[:].set_visible(False) + self.xaxis.set_visible(False) + self.yaxis.set_visible(False) + else: + self._axisline_on = False + self.spines[:].set_visible(True) + self.xaxis.set_visible(True) + self.yaxis.set_visible(True) + + @property + def axis(self): + return self._axislines + + def clear(self): + # docstring inherited + + # Init gridlines before clear() as clear() calls grid(). + self.gridlines = gridlines = GridlinesCollection( + [], + colors=mpl.rcParams['grid.color'], + linestyles=mpl.rcParams['grid.linestyle'], + linewidths=mpl.rcParams['grid.linewidth']) + self._set_artist_props(gridlines) + gridlines.set_grid_helper(self.get_grid_helper()) + + super().clear() + + # clip_path is set after Axes.clear(): that's when a patch is created. + gridlines.set_clip_path(self.axes.patch) + + # Init axis artists. + self._axislines = mpl_axes.Axes.AxisDict(self) + new_fixed_axis = self.get_grid_helper().new_fixed_axis + self._axislines.update({ + loc: new_fixed_axis(loc=loc, axes=self, axis_direction=loc) + for loc in ["bottom", "top", "left", "right"]}) + for axisline in [self._axislines["top"], self._axislines["right"]]: + axisline.label.set_visible(False) + axisline.major_ticklabels.set_visible(False) + axisline.minor_ticklabels.set_visible(False) + + def get_grid_helper(self): + return self._grid_helper + + def grid(self, visible=None, which='major', axis="both", **kwargs): + """ + Toggle the gridlines, and optionally set the properties of the lines. + """ + # There are some discrepancies in the behavior of grid() between + # axes_grid and Matplotlib, because axes_grid explicitly sets the + # visibility of the gridlines. + super().grid(visible, which=which, axis=axis, **kwargs) + if not self._axisline_on: + return + if visible is None: + visible = (self.axes.xaxis._minor_tick_kw["gridOn"] + or self.axes.xaxis._major_tick_kw["gridOn"] + or self.axes.yaxis._minor_tick_kw["gridOn"] + or self.axes.yaxis._major_tick_kw["gridOn"]) + self.gridlines.set(which=which, axis=axis, visible=visible) + self.gridlines.set(**kwargs) + + def get_children(self): + if self._axisline_on: + children = [*self._axislines.values(), self.gridlines] + else: + children = [] + children.extend(super().get_children()) + return children + + def new_fixed_axis(self, loc, offset=None): + return self.get_grid_helper().new_fixed_axis(loc, offset=offset, axes=self) + + def new_floating_axis(self, nth_coord, value, axis_direction="bottom"): + return self.get_grid_helper().new_floating_axis( + nth_coord, value, axis_direction=axis_direction, axes=self) + + +class AxesZero(Axes): + + def clear(self): + super().clear() + new_floating_axis = self.get_grid_helper().new_floating_axis + self._axislines.update( + xzero=new_floating_axis( + nth_coord=0, value=0., axis_direction="bottom", axes=self), + yzero=new_floating_axis( + nth_coord=1, value=0., axis_direction="left", axes=self), + ) + for k in ["xzero", "yzero"]: + self._axislines[k].line.set_clip_path(self.patch) + self._axislines[k].set_visible(False) + + +Subplot = Axes +SubplotZero = AxesZero diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/floating_axes.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/floating_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..74e4c941879babca194cec7d60fe949e648cb4cf --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/floating_axes.py @@ -0,0 +1,275 @@ +""" +An experimental support for curvilinear grid. +""" + +# TODO : +# see if tick_iterator method can be simplified by reusing the parent method. + +import functools + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook +import matplotlib.patches as mpatches +from matplotlib.path import Path + +from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory + +from . import axislines, grid_helper_curvelinear +from .axis_artist import AxisArtist +from .grid_finder import ExtremeFinderSimple + + +class FloatingAxisArtistHelper( + grid_helper_curvelinear.FloatingAxisArtistHelper): + pass + + +class FixedAxisArtistHelper(grid_helper_curvelinear.FloatingAxisArtistHelper): + + def __init__(self, grid_helper, side, nth_coord_ticks=None): + """ + nth_coord = along which coordinate value varies. + nth_coord = 0 -> x axis, nth_coord = 1 -> y axis + """ + lon1, lon2, lat1, lat2 = grid_helper.grid_finder.extreme_finder(*[None] * 5) + value, nth_coord = _api.check_getitem( + dict(left=(lon1, 0), right=(lon2, 0), bottom=(lat1, 1), top=(lat2, 1)), + side=side) + super().__init__(grid_helper, nth_coord, value, axis_direction=side) + if nth_coord_ticks is None: + nth_coord_ticks = nth_coord + self.nth_coord_ticks = nth_coord_ticks + + self.value = value + self.grid_helper = grid_helper + self._side = side + + def update_lim(self, axes): + self.grid_helper.update_lim(axes) + self._grid_info = self.grid_helper._grid_info + + def get_tick_iterators(self, axes): + """tick_loc, tick_angle, tick_label, (optionally) tick_label""" + + grid_finder = self.grid_helper.grid_finder + + lat_levs, lat_n, lat_factor = self._grid_info["lat_info"] + yy0 = lat_levs / lat_factor + + lon_levs, lon_n, lon_factor = self._grid_info["lon_info"] + xx0 = lon_levs / lon_factor + + extremes = self.grid_helper.grid_finder.extreme_finder(*[None] * 5) + xmin, xmax = sorted(extremes[:2]) + ymin, ymax = sorted(extremes[2:]) + + def trf_xy(x, y): + trf = grid_finder.get_transform() + axes.transData + return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T + + if self.nth_coord == 0: + mask = (ymin <= yy0) & (yy0 <= ymax) + (xx1, yy1), (dxx1, dyy1), (dxx2, dyy2) = \ + grid_helper_curvelinear._value_and_jacobian( + trf_xy, self.value, yy0[mask], (xmin, xmax), (ymin, ymax)) + labels = self._grid_info["lat_labels"] + + elif self.nth_coord == 1: + mask = (xmin <= xx0) & (xx0 <= xmax) + (xx1, yy1), (dxx2, dyy2), (dxx1, dyy1) = \ + grid_helper_curvelinear._value_and_jacobian( + trf_xy, xx0[mask], self.value, (xmin, xmax), (ymin, ymax)) + labels = self._grid_info["lon_labels"] + + labels = [l for l, m in zip(labels, mask) if m] + + angle_normal = np.arctan2(dyy1, dxx1) + angle_tangent = np.arctan2(dyy2, dxx2) + mm = (dyy1 == 0) & (dxx1 == 0) # points with degenerate normal + angle_normal[mm] = angle_tangent[mm] + np.pi / 2 + + tick_to_axes = self.get_tick_transform(axes) - axes.transAxes + in_01 = functools.partial( + mpl.transforms._interval_contains_close, (0, 1)) + + def f1(): + for x, y, normal, tangent, lab \ + in zip(xx1, yy1, angle_normal, angle_tangent, labels): + c2 = tick_to_axes.transform((x, y)) + if in_01(c2[0]) and in_01(c2[1]): + yield [x, y], *np.rad2deg([normal, tangent]), lab + + return f1(), iter([]) + + def get_line(self, axes): + self.update_lim(axes) + k, v = dict(left=("lon_lines0", 0), + right=("lon_lines0", 1), + bottom=("lat_lines0", 0), + top=("lat_lines0", 1))[self._side] + xx, yy = self._grid_info[k][v] + return Path(np.column_stack([xx, yy])) + + +class ExtremeFinderFixed(ExtremeFinderSimple): + # docstring inherited + + def __init__(self, extremes): + """ + This subclass always returns the same bounding box. + + Parameters + ---------- + extremes : (float, float, float, float) + The bounding box that this helper always returns. + """ + self._extremes = extremes + + def __call__(self, transform_xy, x1, y1, x2, y2): + # docstring inherited + return self._extremes + + +class GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear): + + def __init__(self, aux_trans, extremes, + grid_locator1=None, + grid_locator2=None, + tick_formatter1=None, + tick_formatter2=None): + # docstring inherited + super().__init__(aux_trans, + extreme_finder=ExtremeFinderFixed(extremes), + grid_locator1=grid_locator1, + grid_locator2=grid_locator2, + tick_formatter1=tick_formatter1, + tick_formatter2=tick_formatter2) + + def new_fixed_axis( + self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): + if axes is None: + axes = self.axes + if axis_direction is None: + axis_direction = loc + # This is not the same as the FixedAxisArtistHelper class used by + # grid_helper_curvelinear.GridHelperCurveLinear.new_fixed_axis! + helper = FixedAxisArtistHelper( + self, loc, nth_coord_ticks=nth_coord) + axisline = AxisArtist(axes, helper, axis_direction=axis_direction) + # Perhaps should be moved to the base class? + axisline.line.set_clip_on(True) + axisline.line.set_clip_box(axisline.axes.bbox) + return axisline + + # new_floating_axis will inherit the grid_helper's extremes. + + # def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"): + # axis = super(GridHelperCurveLinear, + # self).new_floating_axis(nth_coord, + # value, axes=axes, + # axis_direction=axis_direction) + # # set extreme values of the axis helper + # if nth_coord == 1: + # axis.get_helper().set_extremes(*self._extremes[:2]) + # elif nth_coord == 0: + # axis.get_helper().set_extremes(*self._extremes[2:]) + # return axis + + def _update_grid(self, x1, y1, x2, y2): + if self._grid_info is None: + self._grid_info = dict() + + grid_info = self._grid_info + + grid_finder = self.grid_finder + extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy, + x1, y1, x2, y2) + + lon_min, lon_max = sorted(extremes[:2]) + lat_min, lat_max = sorted(extremes[2:]) + grid_info["extremes"] = lon_min, lon_max, lat_min, lat_max # extremes + + lon_levs, lon_n, lon_factor = \ + grid_finder.grid_locator1(lon_min, lon_max) + lon_levs = np.asarray(lon_levs) + lat_levs, lat_n, lat_factor = \ + grid_finder.grid_locator2(lat_min, lat_max) + lat_levs = np.asarray(lat_levs) + + grid_info["lon_info"] = lon_levs, lon_n, lon_factor + grid_info["lat_info"] = lat_levs, lat_n, lat_factor + + grid_info["lon_labels"] = grid_finder._format_ticks( + 1, "bottom", lon_factor, lon_levs) + grid_info["lat_labels"] = grid_finder._format_ticks( + 2, "bottom", lat_factor, lat_levs) + + lon_values = lon_levs[:lon_n] / lon_factor + lat_values = lat_levs[:lat_n] / lat_factor + + lon_lines, lat_lines = grid_finder._get_raw_grid_lines( + lon_values[(lon_min < lon_values) & (lon_values < lon_max)], + lat_values[(lat_min < lat_values) & (lat_values < lat_max)], + lon_min, lon_max, lat_min, lat_max) + + grid_info["lon_lines"] = lon_lines + grid_info["lat_lines"] = lat_lines + + lon_lines, lat_lines = grid_finder._get_raw_grid_lines( + # lon_min, lon_max, lat_min, lat_max) + extremes[:2], extremes[2:], *extremes) + + grid_info["lon_lines0"] = lon_lines + grid_info["lat_lines0"] = lat_lines + + def get_gridlines(self, which="major", axis="both"): + grid_lines = [] + if axis in ["both", "x"]: + grid_lines.extend(self._grid_info["lon_lines"]) + if axis in ["both", "y"]: + grid_lines.extend(self._grid_info["lat_lines"]) + return grid_lines + + +class FloatingAxesBase: + + def __init__(self, *args, grid_helper, **kwargs): + _api.check_isinstance(GridHelperCurveLinear, grid_helper=grid_helper) + super().__init__(*args, grid_helper=grid_helper, **kwargs) + self.set_aspect(1.) + + def _gen_axes_patch(self): + # docstring inherited + x0, x1, y0, y1 = self.get_grid_helper().grid_finder.extreme_finder(*[None] * 5) + patch = mpatches.Polygon([(x0, y0), (x1, y0), (x1, y1), (x0, y1)]) + patch.get_path()._interpolation_steps = 100 + return patch + + def clear(self): + super().clear() + self.patch.set_transform( + self.get_grid_helper().grid_finder.get_transform() + + self.transData) + # The original patch is not in the draw tree; it is only used for + # clipping purposes. + orig_patch = super()._gen_axes_patch() + orig_patch.set_figure(self.get_figure(root=False)) + orig_patch.set_transform(self.transAxes) + self.patch.set_clip_path(orig_patch) + self.gridlines.set_clip_path(orig_patch) + self.adjust_axes_lim() + + def adjust_axes_lim(self): + bbox = self.patch.get_path().get_extents( + # First transform to pixel coords, then to parent data coords. + self.patch.get_transform() - self.transData) + bbox = bbox.expanded(1.02, 1.02) + self.set_xlim(bbox.xmin, bbox.xmax) + self.set_ylim(bbox.ymin, bbox.ymax) + + +floatingaxes_class_factory = cbook._make_class_factory(FloatingAxesBase, "Floating{}") +FloatingAxes = floatingaxes_class_factory(host_axes_class_factory(axislines.Axes)) +FloatingSubplot = FloatingAxes diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_finder.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..ff67aa6e872044bb74e8f2e3882a4d3719cbd55d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_finder.py @@ -0,0 +1,326 @@ +import numpy as np + +from matplotlib import ticker as mticker, _api +from matplotlib.transforms import Bbox, Transform + + +def _find_line_box_crossings(xys, bbox): + """ + Find the points where a polyline crosses a bbox, and the crossing angles. + + Parameters + ---------- + xys : (N, 2) array + The polyline coordinates. + bbox : `.Bbox` + The bounding box. + + Returns + ------- + list of ((float, float), float) + Four separate lists of crossings, for the left, right, bottom, and top + sides of the bbox, respectively. For each list, the entries are the + ``((x, y), ccw_angle_in_degrees)`` of the crossing, where an angle of 0 + means that the polyline is moving to the right at the crossing point. + + The entries are computed by linearly interpolating at each crossing + between the nearest points on either side of the bbox edges. + """ + crossings = [] + dxys = xys[1:] - xys[:-1] + for sl in [slice(None), slice(None, None, -1)]: + us, vs = xys.T[sl] # "this" coord, "other" coord + dus, dvs = dxys.T[sl] + umin, vmin = bbox.min[sl] + umax, vmax = bbox.max[sl] + for u0, inside in [(umin, us > umin), (umax, us < umax)]: + cross = [] + idxs, = (inside[:-1] ^ inside[1:]).nonzero() + for idx in idxs: + v = vs[idx] + (u0 - us[idx]) * dvs[idx] / dus[idx] + if not vmin <= v <= vmax: + continue + crossing = (u0, v)[sl] + theta = np.degrees(np.arctan2(*dxys[idx][::-1])) + cross.append((crossing, theta)) + crossings.append(cross) + return crossings + + +class ExtremeFinderSimple: + """ + A helper class to figure out the range of grid lines that need to be drawn. + """ + + def __init__(self, nx, ny): + """ + Parameters + ---------- + nx, ny : int + The number of samples in each direction. + """ + self.nx = nx + self.ny = ny + + def __call__(self, transform_xy, x1, y1, x2, y2): + """ + Compute an approximation of the bounding box obtained by applying + *transform_xy* to the box delimited by ``(x1, y1, x2, y2)``. + + The intended use is to have ``(x1, y1, x2, y2)`` in axes coordinates, + and have *transform_xy* be the transform from axes coordinates to data + coordinates; this method then returns the range of data coordinates + that span the actual axes. + + The computation is done by sampling ``nx * ny`` equispaced points in + the ``(x1, y1, x2, y2)`` box and finding the resulting points with + extremal coordinates; then adding some padding to take into account the + finite sampling. + + As each sampling step covers a relative range of *1/nx* or *1/ny*, + the padding is computed by expanding the span covered by the extremal + coordinates by these fractions. + """ + x, y = np.meshgrid( + np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny)) + xt, yt = transform_xy(np.ravel(x), np.ravel(y)) + return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max()) + + def _add_pad(self, x_min, x_max, y_min, y_max): + """Perform the padding mentioned in `__call__`.""" + dx = (x_max - x_min) / self.nx + dy = (y_max - y_min) / self.ny + return x_min - dx, x_max + dx, y_min - dy, y_max + dy + + +class _User2DTransform(Transform): + """A transform defined by two user-set functions.""" + + input_dims = output_dims = 2 + + def __init__(self, forward, backward): + """ + Parameters + ---------- + forward, backward : callable + The forward and backward transforms, taking ``x`` and ``y`` as + separate arguments and returning ``(tr_x, tr_y)``. + """ + # The normal Matplotlib convention would be to take and return an + # (N, 2) array but axisartist uses the transposed version. + super().__init__() + self._forward = forward + self._backward = backward + + def transform_non_affine(self, values): + # docstring inherited + return np.transpose(self._forward(*np.transpose(values))) + + def inverted(self): + # docstring inherited + return type(self)(self._backward, self._forward) + + +class GridFinder: + """ + Internal helper for `~.grid_helper_curvelinear.GridHelperCurveLinear`, with + the same constructor parameters; should not be directly instantiated. + """ + + def __init__(self, + transform, + extreme_finder=None, + grid_locator1=None, + grid_locator2=None, + tick_formatter1=None, + tick_formatter2=None): + if extreme_finder is None: + extreme_finder = ExtremeFinderSimple(20, 20) + if grid_locator1 is None: + grid_locator1 = MaxNLocator() + if grid_locator2 is None: + grid_locator2 = MaxNLocator() + if tick_formatter1 is None: + tick_formatter1 = FormatterPrettyPrint() + if tick_formatter2 is None: + tick_formatter2 = FormatterPrettyPrint() + self.extreme_finder = extreme_finder + self.grid_locator1 = grid_locator1 + self.grid_locator2 = grid_locator2 + self.tick_formatter1 = tick_formatter1 + self.tick_formatter2 = tick_formatter2 + self.set_transform(transform) + + def _format_ticks(self, idx, direction, factor, levels): + """ + Helper to support both standard formatters (inheriting from + `.mticker.Formatter`) and axisartist-specific ones; should be called instead of + directly calling ``self.tick_formatter1`` and ``self.tick_formatter2``. This + method should be considered as a temporary workaround which will be removed in + the future at the same time as axisartist-specific formatters. + """ + fmt = _api.check_getitem( + {1: self.tick_formatter1, 2: self.tick_formatter2}, idx=idx) + return (fmt.format_ticks(levels) if isinstance(fmt, mticker.Formatter) + else fmt(direction, factor, levels)) + + def get_grid_info(self, x1, y1, x2, y2): + """ + lon_values, lat_values : list of grid values. if integer is given, + rough number of grids in each direction. + """ + + extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2) + + # min & max rage of lat (or lon) for each grid line will be drawn. + # i.e., gridline of lon=0 will be drawn from lat_min to lat_max. + + lon_min, lon_max, lat_min, lat_max = extremes + lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max) + lon_levs = np.asarray(lon_levs) + lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max) + lat_levs = np.asarray(lat_levs) + + lon_values = lon_levs[:lon_n] / lon_factor + lat_values = lat_levs[:lat_n] / lat_factor + + lon_lines, lat_lines = self._get_raw_grid_lines(lon_values, + lat_values, + lon_min, lon_max, + lat_min, lat_max) + + bb = Bbox.from_extents(x1, y1, x2, y2).expanded(1 + 2e-10, 1 + 2e-10) + + grid_info = { + "extremes": extremes, + # "lon", "lat", filled below. + } + + for idx, lon_or_lat, levs, factor, values, lines in [ + (1, "lon", lon_levs, lon_factor, lon_values, lon_lines), + (2, "lat", lat_levs, lat_factor, lat_values, lat_lines), + ]: + grid_info[lon_or_lat] = gi = { + "lines": [[l] for l in lines], + "ticks": {"left": [], "right": [], "bottom": [], "top": []}, + } + for (lx, ly), v, level in zip(lines, values, levs): + all_crossings = _find_line_box_crossings(np.column_stack([lx, ly]), bb) + for side, crossings in zip( + ["left", "right", "bottom", "top"], all_crossings): + for crossing in crossings: + gi["ticks"][side].append({"level": level, "loc": crossing}) + for side in gi["ticks"]: + levs = [tick["level"] for tick in gi["ticks"][side]] + labels = self._format_ticks(idx, side, factor, levs) + for tick, label in zip(gi["ticks"][side], labels): + tick["label"] = label + + return grid_info + + def _get_raw_grid_lines(self, + lon_values, lat_values, + lon_min, lon_max, lat_min, lat_max): + + lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation + lats_i = np.linspace(lat_min, lat_max, 100) + + lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i) + for lon in lon_values] + lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat)) + for lat in lat_values] + + return lon_lines, lat_lines + + def set_transform(self, aux_trans): + if isinstance(aux_trans, Transform): + self._aux_transform = aux_trans + elif len(aux_trans) == 2 and all(map(callable, aux_trans)): + self._aux_transform = _User2DTransform(*aux_trans) + else: + raise TypeError("'aux_trans' must be either a Transform " + "instance or a pair of callables") + + def get_transform(self): + return self._aux_transform + + update_transform = set_transform # backcompat alias. + + def transform_xy(self, x, y): + return self._aux_transform.transform(np.column_stack([x, y])).T + + def inv_transform_xy(self, x, y): + return self._aux_transform.inverted().transform( + np.column_stack([x, y])).T + + def update(self, **kwargs): + for k, v in kwargs.items(): + if k in ["extreme_finder", + "grid_locator1", + "grid_locator2", + "tick_formatter1", + "tick_formatter2"]: + setattr(self, k, v) + else: + raise ValueError(f"Unknown update property {k!r}") + + +class MaxNLocator(mticker.MaxNLocator): + def __init__(self, nbins=10, steps=None, + trim=True, + integer=False, + symmetric=False, + prune=None): + # trim argument has no effect. It has been left for API compatibility + super().__init__(nbins, steps=steps, integer=integer, + symmetric=symmetric, prune=prune) + self.create_dummy_axis() + + def __call__(self, v1, v2): + locs = super().tick_values(v1, v2) + return np.array(locs), len(locs), 1 # 1: factor (see angle_helper) + + +class FixedLocator: + def __init__(self, locs): + self._locs = locs + + def __call__(self, v1, v2): + v1, v2 = sorted([v1, v2]) + locs = np.array([l for l in self._locs if v1 <= l <= v2]) + return locs, len(locs), 1 # 1: factor (see angle_helper) + + +# Tick Formatter + +class FormatterPrettyPrint: + def __init__(self, useMathText=True): + self._fmt = mticker.ScalarFormatter( + useMathText=useMathText, useOffset=False) + self._fmt.create_dummy_axis() + + def __call__(self, direction, factor, values): + return self._fmt.format_ticks(values) + + +class DictFormatter: + def __init__(self, format_dict, formatter=None): + """ + format_dict : dictionary for format strings to be used. + formatter : fall-back formatter + """ + super().__init__() + self._format_dict = format_dict + self._fallback_formatter = formatter + + def __call__(self, direction, factor, values): + """ + factor is ignored if value is found in the dictionary + """ + if self._fallback_formatter: + fallback_strings = self._fallback_formatter( + direction, factor, values) + else: + fallback_strings = [""] * len(values) + return [self._format_dict.get(k, v) + for k, v in zip(values, fallback_strings)] diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_helper_curvelinear.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_helper_curvelinear.py new file mode 100644 index 0000000000000000000000000000000000000000..a7eb9d5cfe2108c3691e72f527e98b7b73e95a65 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/grid_helper_curvelinear.py @@ -0,0 +1,328 @@ +""" +An experimental support for curvilinear grid. +""" + +import functools + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api +from matplotlib.path import Path +from matplotlib.transforms import Affine2D, IdentityTransform +from .axislines import ( + _FixedAxisArtistHelperBase, _FloatingAxisArtistHelperBase, GridHelperBase) +from .axis_artist import AxisArtist +from .grid_finder import GridFinder + + +def _value_and_jacobian(func, xs, ys, xlims, ylims): + """ + Compute *func* and its derivatives along x and y at positions *xs*, *ys*, + while ensuring that finite difference calculations don't try to evaluate + values outside of *xlims*, *ylims*. + """ + eps = np.finfo(float).eps ** (1/2) # see e.g. scipy.optimize.approx_fprime + val = func(xs, ys) + # Take the finite difference step in the direction where the bound is the + # furthest; the step size is min of epsilon and distance to that bound. + xlo, xhi = sorted(xlims) + dxlo = xs - xlo + dxhi = xhi - xs + xeps = (np.take([-1, 1], dxhi >= dxlo) + * np.minimum(eps, np.maximum(dxlo, dxhi))) + val_dx = func(xs + xeps, ys) + ylo, yhi = sorted(ylims) + dylo = ys - ylo + dyhi = yhi - ys + yeps = (np.take([-1, 1], dyhi >= dylo) + * np.minimum(eps, np.maximum(dylo, dyhi))) + val_dy = func(xs, ys + yeps) + return (val, (val_dx - val) / xeps, (val_dy - val) / yeps) + + +class FixedAxisArtistHelper(_FixedAxisArtistHelperBase): + """ + Helper class for a fixed axis. + """ + + def __init__(self, grid_helper, side, nth_coord_ticks=None): + """ + nth_coord = along which coordinate value varies. + nth_coord = 0 -> x axis, nth_coord = 1 -> y axis + """ + + super().__init__(loc=side) + + self.grid_helper = grid_helper + if nth_coord_ticks is None: + nth_coord_ticks = self.nth_coord + self.nth_coord_ticks = nth_coord_ticks + + self.side = side + + def update_lim(self, axes): + self.grid_helper.update_lim(axes) + + def get_tick_transform(self, axes): + return axes.transData + + def get_tick_iterators(self, axes): + """tick_loc, tick_angle, tick_label""" + v1, v2 = axes.get_ylim() if self.nth_coord == 0 else axes.get_xlim() + if v1 > v2: # Inverted limits. + side = {"left": "right", "right": "left", + "top": "bottom", "bottom": "top"}[self.side] + else: + side = self.side + + angle_tangent = dict(left=90, right=90, bottom=0, top=0)[side] + + def iter_major(): + for nth_coord, show_labels in [ + (self.nth_coord_ticks, True), (1 - self.nth_coord_ticks, False)]: + gi = self.grid_helper._grid_info[["lon", "lat"][nth_coord]] + for tick in gi["ticks"][side]: + yield (*tick["loc"], angle_tangent, + (tick["label"] if show_labels else "")) + + return iter_major(), iter([]) + + +class FloatingAxisArtistHelper(_FloatingAxisArtistHelperBase): + + def __init__(self, grid_helper, nth_coord, value, axis_direction=None): + """ + nth_coord = along which coordinate value varies. + nth_coord = 0 -> x axis, nth_coord = 1 -> y axis + """ + super().__init__(nth_coord, value) + self.value = value + self.grid_helper = grid_helper + self._extremes = -np.inf, np.inf + self._line_num_points = 100 # number of points to create a line + + def set_extremes(self, e1, e2): + if e1 is None: + e1 = -np.inf + if e2 is None: + e2 = np.inf + self._extremes = e1, e2 + + def update_lim(self, axes): + self.grid_helper.update_lim(axes) + + x1, x2 = axes.get_xlim() + y1, y2 = axes.get_ylim() + grid_finder = self.grid_helper.grid_finder + extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy, + x1, y1, x2, y2) + + lon_min, lon_max, lat_min, lat_max = extremes + e_min, e_max = self._extremes # ranges of other coordinates + if self.nth_coord == 0: + lat_min = max(e_min, lat_min) + lat_max = min(e_max, lat_max) + elif self.nth_coord == 1: + lon_min = max(e_min, lon_min) + lon_max = min(e_max, lon_max) + + lon_levs, lon_n, lon_factor = \ + grid_finder.grid_locator1(lon_min, lon_max) + lat_levs, lat_n, lat_factor = \ + grid_finder.grid_locator2(lat_min, lat_max) + + if self.nth_coord == 0: + xx0 = np.full(self._line_num_points, self.value) + yy0 = np.linspace(lat_min, lat_max, self._line_num_points) + xx, yy = grid_finder.transform_xy(xx0, yy0) + elif self.nth_coord == 1: + xx0 = np.linspace(lon_min, lon_max, self._line_num_points) + yy0 = np.full(self._line_num_points, self.value) + xx, yy = grid_finder.transform_xy(xx0, yy0) + + self._grid_info = { + "extremes": (lon_min, lon_max, lat_min, lat_max), + "lon_info": (lon_levs, lon_n, np.asarray(lon_factor)), + "lat_info": (lat_levs, lat_n, np.asarray(lat_factor)), + "lon_labels": grid_finder._format_ticks( + 1, "bottom", lon_factor, lon_levs), + "lat_labels": grid_finder._format_ticks( + 2, "bottom", lat_factor, lat_levs), + "line_xy": (xx, yy), + } + + def get_axislabel_transform(self, axes): + return Affine2D() # axes.transData + + def get_axislabel_pos_angle(self, axes): + def trf_xy(x, y): + trf = self.grid_helper.grid_finder.get_transform() + axes.transData + return trf.transform([x, y]).T + + xmin, xmax, ymin, ymax = self._grid_info["extremes"] + if self.nth_coord == 0: + xx0 = self.value + yy0 = (ymin + ymax) / 2 + elif self.nth_coord == 1: + xx0 = (xmin + xmax) / 2 + yy0 = self.value + xy1, dxy1_dx, dxy1_dy = _value_and_jacobian( + trf_xy, xx0, yy0, (xmin, xmax), (ymin, ymax)) + p = axes.transAxes.inverted().transform(xy1) + if 0 <= p[0] <= 1 and 0 <= p[1] <= 1: + d = [dxy1_dy, dxy1_dx][self.nth_coord] + return xy1, np.rad2deg(np.arctan2(*d[::-1])) + else: + return None, None + + def get_tick_transform(self, axes): + return IdentityTransform() # axes.transData + + def get_tick_iterators(self, axes): + """tick_loc, tick_angle, tick_label, (optionally) tick_label""" + + lat_levs, lat_n, lat_factor = self._grid_info["lat_info"] + yy0 = lat_levs / lat_factor + + lon_levs, lon_n, lon_factor = self._grid_info["lon_info"] + xx0 = lon_levs / lon_factor + + e0, e1 = self._extremes + + def trf_xy(x, y): + trf = self.grid_helper.grid_finder.get_transform() + axes.transData + return trf.transform(np.column_stack(np.broadcast_arrays(x, y))).T + + # find angles + if self.nth_coord == 0: + mask = (e0 <= yy0) & (yy0 <= e1) + (xx1, yy1), (dxx1, dyy1), (dxx2, dyy2) = _value_and_jacobian( + trf_xy, self.value, yy0[mask], (-np.inf, np.inf), (e0, e1)) + labels = self._grid_info["lat_labels"] + + elif self.nth_coord == 1: + mask = (e0 <= xx0) & (xx0 <= e1) + (xx1, yy1), (dxx2, dyy2), (dxx1, dyy1) = _value_and_jacobian( + trf_xy, xx0[mask], self.value, (-np.inf, np.inf), (e0, e1)) + labels = self._grid_info["lon_labels"] + + labels = [l for l, m in zip(labels, mask) if m] + + angle_normal = np.arctan2(dyy1, dxx1) + angle_tangent = np.arctan2(dyy2, dxx2) + mm = (dyy1 == 0) & (dxx1 == 0) # points with degenerate normal + angle_normal[mm] = angle_tangent[mm] + np.pi / 2 + + tick_to_axes = self.get_tick_transform(axes) - axes.transAxes + in_01 = functools.partial( + mpl.transforms._interval_contains_close, (0, 1)) + + def iter_major(): + for x, y, normal, tangent, lab \ + in zip(xx1, yy1, angle_normal, angle_tangent, labels): + c2 = tick_to_axes.transform((x, y)) + if in_01(c2[0]) and in_01(c2[1]): + yield [x, y], *np.rad2deg([normal, tangent]), lab + + return iter_major(), iter([]) + + def get_line_transform(self, axes): + return axes.transData + + def get_line(self, axes): + self.update_lim(axes) + x, y = self._grid_info["line_xy"] + return Path(np.column_stack([x, y])) + + +class GridHelperCurveLinear(GridHelperBase): + def __init__(self, aux_trans, + extreme_finder=None, + grid_locator1=None, + grid_locator2=None, + tick_formatter1=None, + tick_formatter2=None): + """ + Parameters + ---------- + aux_trans : `.Transform` or tuple[Callable, Callable] + The transform from curved coordinates to rectilinear coordinate: + either a `.Transform` instance (which provides also its inverse), + or a pair of callables ``(trans, inv_trans)`` that define the + transform and its inverse. The callables should have signature:: + + x_rect, y_rect = trans(x_curved, y_curved) + x_curved, y_curved = inv_trans(x_rect, y_rect) + + extreme_finder + + grid_locator1, grid_locator2 + Grid locators for each axis. + + tick_formatter1, tick_formatter2 + Tick formatters for each axis. + """ + super().__init__() + self._grid_info = None + self.grid_finder = GridFinder(aux_trans, + extreme_finder, + grid_locator1, + grid_locator2, + tick_formatter1, + tick_formatter2) + + def update_grid_finder(self, aux_trans=None, **kwargs): + if aux_trans is not None: + self.grid_finder.update_transform(aux_trans) + self.grid_finder.update(**kwargs) + self._old_limits = None # Force revalidation. + + @_api.make_keyword_only("3.9", "nth_coord") + def new_fixed_axis( + self, loc, nth_coord=None, axis_direction=None, offset=None, axes=None): + if axes is None: + axes = self.axes + if axis_direction is None: + axis_direction = loc + helper = FixedAxisArtistHelper(self, loc, nth_coord_ticks=nth_coord) + axisline = AxisArtist(axes, helper, axis_direction=axis_direction) + # Why is clip not set on axisline, unlike in new_floating_axis or in + # the floating_axig.GridHelperCurveLinear subclass? + return axisline + + def new_floating_axis(self, nth_coord, value, axes=None, axis_direction="bottom"): + if axes is None: + axes = self.axes + helper = FloatingAxisArtistHelper( + self, nth_coord, value, axis_direction) + axisline = AxisArtist(axes, helper) + axisline.line.set_clip_on(True) + axisline.line.set_clip_box(axisline.axes.bbox) + # axisline.major_ticklabels.set_visible(True) + # axisline.minor_ticklabels.set_visible(False) + return axisline + + def _update_grid(self, x1, y1, x2, y2): + self._grid_info = self.grid_finder.get_grid_info(x1, y1, x2, y2) + + def get_gridlines(self, which="major", axis="both"): + grid_lines = [] + if axis in ["both", "x"]: + for gl in self._grid_info["lon"]["lines"]: + grid_lines.extend(gl) + if axis in ["both", "y"]: + for gl in self._grid_info["lat"]["lines"]: + grid_lines.extend(gl) + return grid_lines + + @_api.deprecated("3.9") + def get_tick_iterator(self, nth_coord, axis_side, minor=False): + angle_tangent = dict(left=90, right=90, bottom=0, top=0)[axis_side] + lon_or_lat = ["lon", "lat"][nth_coord] + if not minor: # major ticks + for tick in self._grid_info[lon_or_lat]["ticks"][axis_side]: + yield *tick["loc"], angle_tangent, tick["label"] + else: + for tick in self._grid_info[lon_or_lat]["ticks"][axis_side]: + yield *tick["loc"], angle_tangent, "" diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/parasite_axes.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/parasite_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..4ebd6acc03be2dbb0f5c3360ede2a6a36a3be01b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/parasite_axes.py @@ -0,0 +1,7 @@ +from mpl_toolkits.axes_grid1.parasite_axes import ( + host_axes_class_factory, parasite_axes_class_factory) +from .axislines import Axes + + +ParasiteAxes = parasite_axes_class_factory(Axes) +HostAxes = SubplotHost = host_axes_class_factory(Axes) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4d8ed16a6a24a8c15ab2956ef678a7f256cd80 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__init__.py @@ -0,0 +1,10 @@ +from pathlib import Path + + +# Check that the test directories exist +if not (Path(__file__).parent / "baseline_images").exists(): + raise OSError( + 'The baseline image directory does not exist. ' + 'This is most likely because the test data is not installed. ' + 'You may need to install matplotlib from source to get the ' + 'test data.') diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08b622f37ee54da166a912f5561d632e2e7479c8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/conftest.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/conftest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..56cb11664051b8ee63a95d021ad641f002e7ee04 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/conftest.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_angle_helper.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_angle_helper.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..35f90ab590073786c018ec07e1a318959d53a0a4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_angle_helper.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axis_artist.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axis_artist.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a50d388677ee9f030d086e9c9bb117ed81341599 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axis_artist.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axislines.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axislines.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..06bb86e203afb8754688668884701da5b3192c0c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_axislines.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_floating_axes.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_floating_axes.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17f914def060887d1f945f755c186213a11a9d0d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_floating_axes.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_finder.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_finder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a66d9c063002d4b0560518ab1e0ddefd574e09d6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_finder.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_helper_curvelinear.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_helper_curvelinear.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..34996ed86012128c76f561fd86f39c9f76bf2cdf Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/__pycache__/test_grid_helper_curvelinear.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/conftest.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..61c2de3e07bac4db323f8704961264d123e01544 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/conftest.py @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import (mpl_test_settings, # noqa + pytest_configure, pytest_unconfigure) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_angle_helper.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_angle_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..3156b33b69c4f59418f2dc78f700ba105547155a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_angle_helper.py @@ -0,0 +1,141 @@ +import re + +import numpy as np +import pytest + +from mpl_toolkits.axisartist.angle_helper import ( + FormatterDMS, FormatterHMS, select_step, select_step24, select_step360) + + +_MS_RE = ( + r'''\$ # Mathtext + ( + # The sign sometimes appears on a 0 when a fraction is shown. + # Check later that there's only one. + (?P-)? + (?P[0-9.]+) # Degrees value + {degree} # Degree symbol (to be replaced by format.) + )? + ( + (?(degree)\\,) # Separator if degrees are also visible. + (?P-)? + (?P[0-9.]+) # Minutes value + {minute} # Minute symbol (to be replaced by format.) + )? + ( + (?(minute)\\,) # Separator if minutes are also visible. + (?P-)? + (?P[0-9.]+) # Seconds value + {second} # Second symbol (to be replaced by format.) + )? + \$ # Mathtext + ''' +) +DMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterDMS.deg_mark), + minute=re.escape(FormatterDMS.min_mark), + second=re.escape(FormatterDMS.sec_mark)), + re.VERBOSE) +HMS_RE = re.compile(_MS_RE.format(degree=re.escape(FormatterHMS.deg_mark), + minute=re.escape(FormatterHMS.min_mark), + second=re.escape(FormatterHMS.sec_mark)), + re.VERBOSE) + + +def dms2float(degrees, minutes=0, seconds=0): + return degrees + minutes / 60.0 + seconds / 3600.0 + + +@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [ + ((-180, 180, 10), {'hour': False}, np.arange(-180, 181, 30), 1.0), + ((-12, 12, 10), {'hour': True}, np.arange(-12, 13, 2), 1.0) +]) +def test_select_step(args, kwargs, expected_levels, expected_factor): + levels, n, factor = select_step(*args, **kwargs) + + assert n == len(levels) + np.testing.assert_array_equal(levels, expected_levels) + assert factor == expected_factor + + +@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [ + ((-180, 180, 10), {}, np.arange(-180, 181, 30), 1.0), + ((-12, 12, 10), {}, np.arange(-750, 751, 150), 60.0) +]) +def test_select_step24(args, kwargs, expected_levels, expected_factor): + levels, n, factor = select_step24(*args, **kwargs) + + assert n == len(levels) + np.testing.assert_array_equal(levels, expected_levels) + assert factor == expected_factor + + +@pytest.mark.parametrize('args, kwargs, expected_levels, expected_factor', [ + ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {}, + np.arange(1215, 1306, 15), 60.0), + ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {}, + np.arange(73820, 73835, 2), 3600.0), + ((dms2float(20, 21.2), dms2float(20, 53.3), 5), {}, + np.arange(1220, 1256, 5), 60.0), + ((21.2, 33.3, 5), {}, + np.arange(20, 35, 2), 1.0), + ((dms2float(20, 21.2), dms2float(21, 33.3), 5), {}, + np.arange(1215, 1306, 15), 60.0), + ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=33.3), 5), {}, + np.arange(73820, 73835, 2), 3600.0), + ((dms2float(20.5, seconds=21.2), dms2float(20.5, seconds=21.4), 5), {}, + np.arange(7382120, 7382141, 5), 360000.0), + # test threshold factor + ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5), + {'threshold_factor': 60}, np.arange(12301, 12310), 600.0), + ((dms2float(20.5, seconds=11.2), dms2float(20.5, seconds=53.3), 5), + {'threshold_factor': 1}, np.arange(20502, 20517, 2), 1000.0), +]) +def test_select_step360(args, kwargs, expected_levels, expected_factor): + levels, n, factor = select_step360(*args, **kwargs) + + assert n == len(levels) + np.testing.assert_array_equal(levels, expected_levels) + assert factor == expected_factor + + +@pytest.mark.parametrize('Formatter, regex', + [(FormatterDMS, DMS_RE), + (FormatterHMS, HMS_RE)], + ids=['Degree/Minute/Second', 'Hour/Minute/Second']) +@pytest.mark.parametrize('direction, factor, values', [ + ("left", 60, [0, -30, -60]), + ("left", 600, [12301, 12302, 12303]), + ("left", 3600, [0, -30, -60]), + ("left", 36000, [738210, 738215, 738220]), + ("left", 360000, [7382120, 7382125, 7382130]), + ("left", 1., [45, 46, 47]), + ("left", 10., [452, 453, 454]), +]) +def test_formatters(Formatter, regex, direction, factor, values): + fmt = Formatter() + result = fmt(direction, factor, values) + + prev_degree = prev_minute = prev_second = None + for tick, value in zip(result, values): + m = regex.match(tick) + assert m is not None, f'{tick!r} is not an expected tick format.' + + sign = sum(m.group(sign + '_sign') is not None + for sign in ('degree', 'minute', 'second')) + assert sign <= 1, f'Only one element of tick {tick!r} may have a sign.' + sign = 1 if sign == 0 else -1 + + degree = float(m.group('degree') or prev_degree or 0) + minute = float(m.group('minute') or prev_minute or 0) + second = float(m.group('second') or prev_second or 0) + if Formatter == FormatterHMS: + # 360 degrees as plot range -> 24 hours as labelled range + expected_value = pytest.approx((value // 15) / factor) + else: + expected_value = pytest.approx(value / factor) + assert sign * dms2float(degree, minute, second) == expected_value, \ + f'{tick!r} does not match expected tick value.' + + prev_degree = degree + prev_minute = minute + prev_second = second diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axis_artist.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axis_artist.py new file mode 100644 index 0000000000000000000000000000000000000000..d44a61b6dd4aebebd14f0e240c130e390b0bc70b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axis_artist.py @@ -0,0 +1,99 @@ +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison + +from mpl_toolkits.axisartist import AxisArtistHelperRectlinear +from mpl_toolkits.axisartist.axis_artist import (AxisArtist, AxisLabel, + LabelBase, Ticks, TickLabels) + + +@image_comparison(['axis_artist_ticks.png'], style='default') +def test_ticks(): + fig, ax = plt.subplots() + + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + locs_angles = [((i / 10, 0.0), i * 30) for i in range(-1, 12)] + + ticks_in = Ticks(ticksize=10, axis=ax.xaxis) + ticks_in.set_locs_angles(locs_angles) + ax.add_artist(ticks_in) + + ticks_out = Ticks(ticksize=10, tick_out=True, color='C3', axis=ax.xaxis) + ticks_out.set_locs_angles(locs_angles) + ax.add_artist(ticks_out) + + +@image_comparison(['axis_artist_labelbase.png'], style='default') +def test_labelbase(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig, ax = plt.subplots() + + ax.plot([0.5], [0.5], "o") + + label = LabelBase(0.5, 0.5, "Test") + label._ref_angle = -90 + label._offset_radius = 50 + label.set_rotation(-90) + label.set(ha="center", va="top") + ax.add_artist(label) + + +@image_comparison(['axis_artist_ticklabels.png'], style='default') +def test_ticklabels(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig, ax = plt.subplots() + + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + ax.plot([0.2, 0.4], [0.5, 0.5], "o") + + ticks = Ticks(ticksize=10, axis=ax.xaxis) + ax.add_artist(ticks) + locs_angles_labels = [((0.2, 0.5), -90, "0.2"), + ((0.4, 0.5), -120, "0.4")] + tick_locs_angles = [(xy, a + 180) for xy, a, l in locs_angles_labels] + ticks.set_locs_angles(tick_locs_angles) + + ticklabels = TickLabels(axis_direction="left") + ticklabels._locs_angles_labels = locs_angles_labels + ticklabels.set_pad(10) + ax.add_artist(ticklabels) + + ax.plot([0.5], [0.5], "s") + axislabel = AxisLabel(0.5, 0.5, "Test") + axislabel._offset_radius = 20 + axislabel._ref_angle = 0 + axislabel.set_axis_direction("bottom") + ax.add_artist(axislabel) + + ax.set_xlim(0, 1) + ax.set_ylim(0, 1) + + +@image_comparison(['axis_artist.png'], style='default') +def test_axis_artist(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig, ax = plt.subplots() + + ax.xaxis.set_visible(False) + ax.yaxis.set_visible(False) + + for loc in ('left', 'right', 'bottom'): + helper = AxisArtistHelperRectlinear.Fixed(ax, loc=loc) + axisline = AxisArtist(ax, helper, offset=None, axis_direction=loc) + ax.add_artist(axisline) + + # Settings for bottom AxisArtist. + axisline.set_label("TTT") + axisline.major_ticks.set_tick_out(False) + axisline.label.set_pad(5) + + ax.set_ylabel("Test") diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axislines.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axislines.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc3707421b61fed84a5ba7fc3958cac7de8dc85 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_axislines.py @@ -0,0 +1,145 @@ +import numpy as np +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison +from matplotlib.transforms import IdentityTransform + +from mpl_toolkits.axisartist.axislines import AxesZero, SubplotZero, Subplot +from mpl_toolkits.axisartist import Axes, SubplotHost + + +@image_comparison(['SubplotZero.png'], style='default') +def test_SubplotZero(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure() + + ax = SubplotZero(fig, 1, 1, 1) + fig.add_subplot(ax) + + ax.axis["xzero"].set_visible(True) + ax.axis["xzero"].label.set_text("Axis Zero") + + for n in ["top", "right"]: + ax.axis[n].set_visible(False) + + xx = np.arange(0, 2 * np.pi, 0.01) + ax.plot(xx, np.sin(xx)) + ax.set_ylabel("Test") + + +@image_comparison(['Subplot.png'], style='default') +def test_Subplot(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure() + + ax = Subplot(fig, 1, 1, 1) + fig.add_subplot(ax) + + xx = np.arange(0, 2 * np.pi, 0.01) + ax.plot(xx, np.sin(xx)) + ax.set_ylabel("Test") + + ax.axis["top"].major_ticks.set_tick_out(True) + ax.axis["bottom"].major_ticks.set_tick_out(True) + + ax.axis["bottom"].set_label("Tk0") + + +def test_Axes(): + fig = plt.figure() + ax = Axes(fig, [0.15, 0.1, 0.65, 0.8]) + fig.add_axes(ax) + ax.plot([1, 2, 3], [0, 1, 2]) + ax.set_xscale('log') + fig.canvas.draw() + + +@image_comparison(['ParasiteAxesAuxTrans_meshplot.png'], + remove_text=True, style='default', tol=0.075) +def test_ParasiteAxesAuxTrans(): + data = np.ones((6, 6)) + data[2, 2] = 2 + data[0, :] = 0 + data[-2, :] = 0 + data[:, 0] = 0 + data[:, -2] = 0 + x = np.arange(6) + y = np.arange(6) + xx, yy = np.meshgrid(x, y) + + funcnames = ['pcolor', 'pcolormesh', 'contourf'] + + fig = plt.figure() + for i, name in enumerate(funcnames): + + ax1 = SubplotHost(fig, 1, 3, i+1) + fig.add_subplot(ax1) + + ax2 = ax1.get_aux_axes(IdentityTransform(), viewlim_mode=None) + if name.startswith('pcolor'): + getattr(ax2, name)(xx, yy, data[:-1, :-1]) + else: + getattr(ax2, name)(xx, yy, data) + ax1.set_xlim((0, 5)) + ax1.set_ylim((0, 5)) + + ax2.contour(xx, yy, data, colors='k') + + +@image_comparison(['axisline_style.png'], remove_text=True, style='mpl20') +def test_axisline_style(): + fig = plt.figure(figsize=(2, 2)) + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>") + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['axisline_style_size_color.png'], remove_text=True, + style='mpl20') +def test_axisline_style_size_color(): + fig = plt.figure(figsize=(2, 2)) + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>", size=2.0, facecolor='r') + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->, size=1.5") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['axisline_style_tight.png'], remove_text=True, + style='mpl20') +def test_axisline_style_tight(): + fig = plt.figure(figsize=(2, 2), layout='tight') + ax = fig.add_subplot(axes_class=AxesZero) + ax.axis["xzero"].set_axisline_style("-|>", size=5, facecolor='g') + ax.axis["xzero"].set_visible(True) + ax.axis["yzero"].set_axisline_style("->, size=8") + ax.axis["yzero"].set_visible(True) + + for direction in ("left", "right", "bottom", "top"): + ax.axis[direction].set_visible(False) + + +@image_comparison(['subplotzero_ylabel.png'], style='mpl20') +def test_subplotzero_ylabel(): + fig = plt.figure() + ax = fig.add_subplot(111, axes_class=SubplotZero) + + ax.set(xlim=(-3, 7), ylim=(-3, 7), xlabel="x", ylabel="y") + + zero_axis = ax.axis["xzero", "yzero"] + zero_axis.set_visible(True) # they are hidden by default + + ax.axis["left", "right", "bottom", "top"].set_visible(False) + + zero_axis.set_axisline_style("->") diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_floating_axes.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_floating_axes.py new file mode 100644 index 0000000000000000000000000000000000000000..7644fea1696599273f6214d7735bb919b500108c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_floating_axes.py @@ -0,0 +1,115 @@ +import numpy as np + +import matplotlib.pyplot as plt +import matplotlib.projections as mprojections +import matplotlib.transforms as mtransforms +from matplotlib.testing.decorators import image_comparison +from mpl_toolkits.axisartist.axislines import Subplot +from mpl_toolkits.axisartist.floating_axes import ( + FloatingAxes, GridHelperCurveLinear) +from mpl_toolkits.axisartist.grid_finder import FixedLocator +from mpl_toolkits.axisartist import angle_helper + + +def test_subplot(): + fig = plt.figure(figsize=(5, 5)) + ax = Subplot(fig, 111) + fig.add_subplot(ax) + + +# Rather high tolerance to allow ongoing work with floating axes internals; +# remove when image is regenerated. +@image_comparison(['curvelinear3.png'], style='default', tol=5) +def test_curvelinear3(): + fig = plt.figure(figsize=(5, 5)) + + tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) + + mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False)) + grid_helper = GridHelperCurveLinear( + tr, + extremes=(0, 360, 10, 3), + grid_locator1=angle_helper.LocatorDMS(15), + grid_locator2=FixedLocator([2, 4, 6, 8, 10]), + tick_formatter1=angle_helper.FormatterDMS(), + tick_formatter2=None) + ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper) + + r_scale = 10 + tr2 = mtransforms.Affine2D().scale(1, 1 / r_scale) + tr + grid_helper2 = GridHelperCurveLinear( + tr2, + extremes=(0, 360, 10 * r_scale, 3 * r_scale), + grid_locator2=FixedLocator([30, 60, 90])) + + ax1.axis["right"] = axis = grid_helper2.new_fixed_axis("right", axes=ax1) + + ax1.axis["left"].label.set_text("Test 1") + ax1.axis["right"].label.set_text("Test 2") + ax1.axis["left", "right"].set_visible(False) + + axis = grid_helper.new_floating_axis(1, 7, axes=ax1, + axis_direction="bottom") + ax1.axis["z"] = axis + axis.toggle(all=True, label=True) + axis.label.set_text("z = ?") + axis.label.set_visible(True) + axis.line.set_color("0.5") + + ax2 = ax1.get_aux_axes(tr) + + xx, yy = [67, 90, 75, 30], [2, 5, 8, 4] + ax2.scatter(xx, yy) + l, = ax2.plot(xx, yy, "k-") + l.set_clip_path(ax1.patch) + + +# Rather high tolerance to allow ongoing work with floating axes internals; +# remove when image is regenerated. +@image_comparison(['curvelinear4.png'], style='default', tol=0.9) +def test_curvelinear4(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure(figsize=(5, 5)) + + tr = (mtransforms.Affine2D().scale(np.pi / 180, 1) + + mprojections.PolarAxes.PolarTransform(apply_theta_transforms=False)) + grid_helper = GridHelperCurveLinear( + tr, + extremes=(120, 30, 10, 0), + grid_locator1=angle_helper.LocatorDMS(5), + grid_locator2=FixedLocator([2, 4, 6, 8, 10]), + tick_formatter1=angle_helper.FormatterDMS(), + tick_formatter2=None) + ax1 = fig.add_subplot(axes_class=FloatingAxes, grid_helper=grid_helper) + ax1.clear() # Check that clear() also restores the correct limits on ax1. + + ax1.axis["left"].label.set_text("Test 1") + ax1.axis["right"].label.set_text("Test 2") + ax1.axis["top"].set_visible(False) + + axis = grid_helper.new_floating_axis(1, 70, axes=ax1, + axis_direction="bottom") + ax1.axis["z"] = axis + axis.toggle(all=True, label=True) + axis.label.set_axis_direction("top") + axis.label.set_text("z = ?") + axis.label.set_visible(True) + axis.line.set_color("0.5") + + ax2 = ax1.get_aux_axes(tr) + + xx, yy = [67, 90, 75, 30], [2, 5, 8, 4] + ax2.scatter(xx, yy) + l, = ax2.plot(xx, yy, "k-") + l.set_clip_path(ax1.patch) + + +def test_axis_direction(): + # Check that axis direction is propagated on a floating axis + fig = plt.figure() + ax = Subplot(fig, 111) + fig.add_subplot(ax) + ax.axis['y'] = ax.new_floating_axis(nth_coord=1, value=0, + axis_direction='left') + assert ax.axis['y']._axis_direction == 'left' diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_finder.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_finder.py new file mode 100644 index 0000000000000000000000000000000000000000..6b397675ee10098a93545cc712a4b3c07384cbc2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_finder.py @@ -0,0 +1,34 @@ +import numpy as np +import pytest + +from matplotlib.transforms import Bbox +from mpl_toolkits.axisartist.grid_finder import ( + _find_line_box_crossings, FormatterPrettyPrint, MaxNLocator) + + +def test_find_line_box_crossings(): + x = np.array([-3, -2, -1, 0., 1, 2, 3, 2, 1, 0, -1, -2, -3, 5]) + y = np.arange(len(x)) + bbox = Bbox.from_extents(-2, 3, 2, 12.5) + left, right, bottom, top = _find_line_box_crossings( + np.column_stack([x, y]), bbox) + ((lx0, ly0), la0), ((lx1, ly1), la1), = left + ((rx0, ry0), ra0), ((rx1, ry1), ra1), = right + ((bx0, by0), ba0), = bottom + ((tx0, ty0), ta0), = top + assert (lx0, ly0, la0) == (-2, 11, 135) + assert (lx1, ly1, la1) == pytest.approx((-2., 12.125, 7.125016)) + assert (rx0, ry0, ra0) == (2, 5, 45) + assert (rx1, ry1, ra1) == (2, 7, 135) + assert (bx0, by0, ba0) == (0, 3, 45) + assert (tx0, ty0, ta0) == pytest.approx((1., 12.5, 7.125016)) + + +def test_pretty_print_format(): + locator = MaxNLocator() + locs, nloc, factor = locator(0, 100) + + fmt = FormatterPrettyPrint() + + assert fmt("left", None, locs) == \ + [r'$\mathdefault{%d}$' % (l, ) for l in locs] diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_helper_curvelinear.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_helper_curvelinear.py new file mode 100644 index 0000000000000000000000000000000000000000..1b266044bdd06d995a1df86779dac97dae8cb13e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/axisartist/tests/test_grid_helper_curvelinear.py @@ -0,0 +1,207 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.path import Path +from matplotlib.projections import PolarAxes +from matplotlib.ticker import FuncFormatter +from matplotlib.transforms import Affine2D, Transform +from matplotlib.testing.decorators import image_comparison + +from mpl_toolkits.axisartist import SubplotHost +from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory +from mpl_toolkits.axisartist import angle_helper +from mpl_toolkits.axisartist.axislines import Axes +from mpl_toolkits.axisartist.grid_helper_curvelinear import \ + GridHelperCurveLinear + + +@image_comparison(['custom_transform.png'], style='default', tol=0.2) +def test_custom_transform(): + class MyTransform(Transform): + input_dims = output_dims = 2 + + def __init__(self, resolution): + """ + Resolution is the number of steps to interpolate between each input + line segment to approximate its path in transformed space. + """ + Transform.__init__(self) + self._resolution = resolution + + def transform(self, ll): + x, y = ll.T + return np.column_stack([x, y - x]) + + transform_non_affine = transform + + def transform_path(self, path): + ipath = path.interpolated(self._resolution) + return Path(self.transform(ipath.vertices), ipath.codes) + + transform_path_non_affine = transform_path + + def inverted(self): + return MyTransformInv(self._resolution) + + class MyTransformInv(Transform): + input_dims = output_dims = 2 + + def __init__(self, resolution): + Transform.__init__(self) + self._resolution = resolution + + def transform(self, ll): + x, y = ll.T + return np.column_stack([x, y + x]) + + def inverted(self): + return MyTransform(self._resolution) + + fig = plt.figure() + + SubplotHost = host_axes_class_factory(Axes) + + tr = MyTransform(1) + grid_helper = GridHelperCurveLinear(tr) + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + fig.add_subplot(ax1) + + ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal") + ax2.plot([3, 6], [5.0, 10.]) + + ax1.set_aspect(1.) + ax1.set_xlim(0, 10) + ax1.set_ylim(0, 10) + + ax1.grid(True) + + +@image_comparison(['polar_box.png'], style='default', tol=0.04) +def test_polar_box(): + fig = plt.figure(figsize=(5, 5)) + + # PolarAxes.PolarTransform takes radian. However, we want our coordinate + # system in degree + tr = (Affine2D().scale(np.pi / 180., 1.) + + PolarAxes.PolarTransform(apply_theta_transforms=False)) + + # polar projection, which involves cycle, and also has limits in + # its coordinates, needs a special method to find the extremes + # (min, max of the coordinate within the view). + extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, + lon_cycle=360, + lat_cycle=None, + lon_minmax=None, + lat_minmax=(0, np.inf)) + + grid_helper = GridHelperCurveLinear( + tr, + extreme_finder=extreme_finder, + grid_locator1=angle_helper.LocatorDMS(12), + tick_formatter1=angle_helper.FormatterDMS(), + tick_formatter2=FuncFormatter(lambda x, p: "eight" if x == 8 else f"{int(x)}"), + ) + + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + + ax1.axis["right"].major_ticklabels.set_visible(True) + ax1.axis["top"].major_ticklabels.set_visible(True) + + # let right axis shows ticklabels for 1st coordinate (angle) + ax1.axis["right"].get_helper().nth_coord_ticks = 0 + # let bottom axis shows ticklabels for 2nd coordinate (radius) + ax1.axis["bottom"].get_helper().nth_coord_ticks = 1 + + fig.add_subplot(ax1) + + ax1.axis["lat"] = axis = grid_helper.new_floating_axis(0, 45, axes=ax1) + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(2, 12) + + ax1.axis["lon"] = axis = grid_helper.new_floating_axis(1, 6, axes=ax1) + axis.label.set_text("Test 2") + axis.get_helper().set_extremes(-180, 90) + + # A parasite axes with given transform + ax2 = ax1.get_aux_axes(tr, viewlim_mode="equal") + assert ax2.transData == tr + ax1.transData + # Anything you draw in ax2 will match the ticks and grids of ax1. + ax2.plot(np.linspace(0, 30, 50), np.linspace(10, 10, 50)) + + ax1.set_aspect(1.) + ax1.set_xlim(-5, 12) + ax1.set_ylim(-5, 10) + + ax1.grid(True) + + +# Remove tol & kerning_factor when this test image is regenerated. +@image_comparison(['axis_direction.png'], style='default', tol=0.13) +def test_axis_direction(): + plt.rcParams['text.kerning_factor'] = 6 + + fig = plt.figure(figsize=(5, 5)) + + # PolarAxes.PolarTransform takes radian. However, we want our coordinate + # system in degree + tr = (Affine2D().scale(np.pi / 180., 1.) + + PolarAxes.PolarTransform(apply_theta_transforms=False)) + + # polar projection, which involves cycle, and also has limits in + # its coordinates, needs a special method to find the extremes + # (min, max of the coordinate within the view). + + # 20, 20 : number of sampling points along x, y direction + extreme_finder = angle_helper.ExtremeFinderCycle(20, 20, + lon_cycle=360, + lat_cycle=None, + lon_minmax=None, + lat_minmax=(0, np.inf), + ) + + grid_locator1 = angle_helper.LocatorDMS(12) + tick_formatter1 = angle_helper.FormatterDMS() + + grid_helper = GridHelperCurveLinear(tr, + extreme_finder=extreme_finder, + grid_locator1=grid_locator1, + tick_formatter1=tick_formatter1) + + ax1 = SubplotHost(fig, 1, 1, 1, grid_helper=grid_helper) + + for axis in ax1.axis.values(): + axis.set_visible(False) + + fig.add_subplot(ax1) + + ax1.axis["lat1"] = axis = grid_helper.new_floating_axis( + 0, 130, + axes=ax1, axis_direction="left") + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(0.001, 10) + + ax1.axis["lat2"] = axis = grid_helper.new_floating_axis( + 0, 50, + axes=ax1, axis_direction="right") + axis.label.set_text("Test") + axis.label.set_visible(True) + axis.get_helper().set_extremes(0.001, 10) + + ax1.axis["lon"] = axis = grid_helper.new_floating_axis( + 1, 10, + axes=ax1, axis_direction="bottom") + axis.label.set_text("Test 2") + axis.get_helper().set_extremes(50, 130) + axis.major_ticklabels.set_axis_direction("top") + axis.label.set_axis_direction("top") + + grid_helper.grid_finder.grid_locator1.set_params(nbins=5) + grid_helper.grid_finder.grid_locator2.set_params(nbins=5) + + ax1.set_aspect(1.) + ax1.set_xlim(-8, 8) + ax1.set_ylim(-4, 12) + + ax1.grid(True) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..a089fbd6b70ebdafb19f6c902d49e5e3bdc05f43 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__init__.py @@ -0,0 +1,3 @@ +from .axes3d import Axes3D + +__all__ = ['Axes3D'] diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a5195f9637930123411b0455c468bfcdfd01102 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/art3d.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/art3d.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..be693420d3bc9ff25e242704fd4894561fbb50d7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/art3d.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/axis3d.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/axis3d.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab5b67835e3a1c35c35dcae44a5c3f4f8455ea12 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/axis3d.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/proj3d.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/proj3d.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..772f6e1a87b28be0614967bc3e078138eb8eb17d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/__pycache__/proj3d.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/art3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/art3d.py new file mode 100644 index 0000000000000000000000000000000000000000..deb0ca34302c03cda08e57b28a82cb3654e45aaa --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/art3d.py @@ -0,0 +1,1427 @@ +# art3d.py, original mplot3d version by John Porter +# Parts rewritten by Reinier Heeres +# Minor additions by Ben Axelrod + +""" +Module containing 3D artist code and functions to convert 2D +artists into 3D versions which can be added to an Axes3D. +""" + +import math + +import numpy as np + +from contextlib import contextmanager + +from matplotlib import ( + _api, artist, cbook, colors as mcolors, lines, text as mtext, + path as mpath) +from matplotlib.collections import ( + Collection, LineCollection, PolyCollection, PatchCollection, PathCollection) +from matplotlib.colors import Normalize +from matplotlib.patches import Patch +from . import proj3d + + +def _norm_angle(a): + """Return the given angle normalized to -180 < *a* <= 180 degrees.""" + a = (a + 360) % 360 + if a > 180: + a = a - 360 + return a + + +def _norm_text_angle(a): + """Return the given angle normalized to -90 < *a* <= 90 degrees.""" + a = (a + 180) % 180 + if a > 90: + a = a - 180 + return a + + +def get_dir_vector(zdir): + """ + Return a direction vector. + + Parameters + ---------- + zdir : {'x', 'y', 'z', None, 3-tuple} + The direction. Possible values are: + + - 'x': equivalent to (1, 0, 0) + - 'y': equivalent to (0, 1, 0) + - 'z': equivalent to (0, 0, 1) + - *None*: equivalent to (0, 0, 0) + - an iterable (x, y, z) is converted to an array + + Returns + ------- + x, y, z : array + The direction vector. + """ + if zdir == 'x': + return np.array((1, 0, 0)) + elif zdir == 'y': + return np.array((0, 1, 0)) + elif zdir == 'z': + return np.array((0, 0, 1)) + elif zdir is None: + return np.array((0, 0, 0)) + elif np.iterable(zdir) and len(zdir) == 3: + return np.array(zdir) + else: + raise ValueError("'x', 'y', 'z', None or vector of length 3 expected") + + +def _viewlim_mask(xs, ys, zs, axes): + """ + Return original points with points outside the axes view limits masked. + + Parameters + ---------- + xs, ys, zs : array-like + The points to mask. + axes : Axes3D + The axes to use for the view limits. + + Returns + ------- + xs_masked, ys_masked, zs_masked : np.ma.array + The masked points. + """ + mask = np.logical_or.reduce((xs < axes.xy_viewLim.xmin, + xs > axes.xy_viewLim.xmax, + ys < axes.xy_viewLim.ymin, + ys > axes.xy_viewLim.ymax, + zs < axes.zz_viewLim.xmin, + zs > axes.zz_viewLim.xmax)) + xs_masked = np.ma.array(xs, mask=mask) + ys_masked = np.ma.array(ys, mask=mask) + zs_masked = np.ma.array(zs, mask=mask) + return xs_masked, ys_masked, zs_masked + + +class Text3D(mtext.Text): + """ + Text object with 3D position and direction. + + Parameters + ---------- + x, y, z : float + The position of the text. + text : str + The text string to display. + zdir : {'x', 'y', 'z', None, 3-tuple} + The direction of the text. See `.get_dir_vector` for a description of + the values. + axlim_clip : bool, default: False + Whether to hide text outside the axes view limits. + + Other Parameters + ---------------- + **kwargs + All other parameters are passed on to `~matplotlib.text.Text`. + """ + + def __init__(self, x=0, y=0, z=0, text='', zdir='z', axlim_clip=False, + **kwargs): + mtext.Text.__init__(self, x, y, text, **kwargs) + self.set_3d_properties(z, zdir, axlim_clip) + + def get_position_3d(self): + """Return the (x, y, z) position of the text.""" + return self._x, self._y, self._z + + def set_position_3d(self, xyz, zdir=None): + """ + Set the (*x*, *y*, *z*) position of the text. + + Parameters + ---------- + xyz : (float, float, float) + The position in 3D space. + zdir : {'x', 'y', 'z', None, 3-tuple} + The direction of the text. If unspecified, the *zdir* will not be + changed. See `.get_dir_vector` for a description of the values. + """ + super().set_position(xyz[:2]) + self.set_z(xyz[2]) + if zdir is not None: + self._dir_vec = get_dir_vector(zdir) + + def set_z(self, z): + """ + Set the *z* position of the text. + + Parameters + ---------- + z : float + """ + self._z = z + self.stale = True + + def set_3d_properties(self, z=0, zdir='z', axlim_clip=False): + """ + Set the *z* position and direction of the text. + + Parameters + ---------- + z : float + The z-position in 3D space. + zdir : {'x', 'y', 'z', 3-tuple} + The direction of the text. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide text outside the axes view limits. + """ + self._z = z + self._dir_vec = get_dir_vector(zdir) + self._axlim_clip = axlim_clip + self.stale = True + + @artist.allow_rasterization + def draw(self, renderer): + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(self._x, self._y, self._z, self.axes) + position3d = np.ma.row_stack((xs, ys, zs)).ravel().filled(np.nan) + else: + xs, ys, zs = self._x, self._y, self._z + position3d = np.asanyarray([xs, ys, zs]) + + proj = proj3d._proj_trans_points( + [position3d, position3d + self._dir_vec], self.axes.M) + dx = proj[0][1] - proj[0][0] + dy = proj[1][1] - proj[1][0] + angle = math.degrees(math.atan2(dy, dx)) + with cbook._setattr_cm(self, _x=proj[0][0], _y=proj[1][0], + _rotation=_norm_text_angle(angle)): + mtext.Text.draw(self, renderer) + self.stale = False + + def get_tightbbox(self, renderer=None): + # Overwriting the 2d Text behavior which is not valid for 3d. + # For now, just return None to exclude from layout calculation. + return None + + +def text_2d_to_3d(obj, z=0, zdir='z', axlim_clip=False): + """ + Convert a `.Text` to a `.Text3D` object. + + Parameters + ---------- + z : float + The z-position in 3D space. + zdir : {'x', 'y', 'z', 3-tuple} + The direction of the text. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide text outside the axes view limits. + """ + obj.__class__ = Text3D + obj.set_3d_properties(z, zdir, axlim_clip) + + +class Line3D(lines.Line2D): + """ + 3D line object. + + .. note:: Use `get_data_3d` to obtain the data associated with the line. + `~.Line2D.get_data`, `~.Line2D.get_xdata`, and `~.Line2D.get_ydata` return + the x- and y-coordinates of the projected 2D-line, not the x- and y-data of + the 3D-line. Similarly, use `set_data_3d` to set the data, not + `~.Line2D.set_data`, `~.Line2D.set_xdata`, and `~.Line2D.set_ydata`. + """ + + def __init__(self, xs, ys, zs, *args, axlim_clip=False, **kwargs): + """ + + Parameters + ---------- + xs : array-like + The x-data to be plotted. + ys : array-like + The y-data to be plotted. + zs : array-like + The z-data to be plotted. + *args, **kwargs + Additional arguments are passed to `~matplotlib.lines.Line2D`. + """ + super().__init__([], [], *args, **kwargs) + self.set_data_3d(xs, ys, zs) + self._axlim_clip = axlim_clip + + def set_3d_properties(self, zs=0, zdir='z', axlim_clip=False): + """ + Set the *z* position and direction of the line. + + Parameters + ---------- + zs : float or array of floats + The location along the *zdir* axis in 3D space to position the + line. + zdir : {'x', 'y', 'z'} + Plane to plot line orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide lines with an endpoint outside the axes view limits. + """ + xs = self.get_xdata() + ys = self.get_ydata() + zs = cbook._to_unmasked_float_array(zs).ravel() + zs = np.broadcast_to(zs, len(xs)) + self._verts3d = juggle_axes(xs, ys, zs, zdir) + self._axlim_clip = axlim_clip + self.stale = True + + def set_data_3d(self, *args): + """ + Set the x, y and z data + + Parameters + ---------- + x : array-like + The x-data to be plotted. + y : array-like + The y-data to be plotted. + z : array-like + The z-data to be plotted. + + Notes + ----- + Accepts x, y, z arguments or a single array-like (x, y, z) + """ + if len(args) == 1: + args = args[0] + for name, xyz in zip('xyz', args): + if not np.iterable(xyz): + raise RuntimeError(f'{name} must be a sequence') + self._verts3d = args + self.stale = True + + def get_data_3d(self): + """ + Get the current data + + Returns + ------- + verts3d : length-3 tuple or array-like + The current data as a tuple or array-like. + """ + return self._verts3d + + @artist.allow_rasterization + def draw(self, renderer): + if self._axlim_clip: + xs3d, ys3d, zs3d = _viewlim_mask(*self._verts3d, self.axes) + else: + xs3d, ys3d, zs3d = self._verts3d + xs, ys, zs, tis = proj3d._proj_transform_clip(xs3d, ys3d, zs3d, + self.axes.M, + self.axes._focal_length) + self.set_data(xs, ys) + super().draw(renderer) + self.stale = False + + +def line_2d_to_3d(line, zs=0, zdir='z', axlim_clip=False): + """ + Convert a `.Line2D` to a `.Line3D` object. + + Parameters + ---------- + zs : float + The location along the *zdir* axis in 3D space to position the line. + zdir : {'x', 'y', 'z'} + Plane to plot line orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide lines with an endpoint outside the axes view limits. + """ + + line.__class__ = Line3D + line.set_3d_properties(zs, zdir, axlim_clip) + + +def _path_to_3d_segment(path, zs=0, zdir='z'): + """Convert a path to a 3D segment.""" + + zs = np.broadcast_to(zs, len(path)) + pathsegs = path.iter_segments(simplify=False, curves=False) + seg = [(x, y, z) for (((x, y), code), z) in zip(pathsegs, zs)] + seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] + return seg3d + + +def _paths_to_3d_segments(paths, zs=0, zdir='z'): + """Convert paths from a collection object to 3D segments.""" + + if not np.iterable(zs): + zs = np.broadcast_to(zs, len(paths)) + else: + if len(zs) != len(paths): + raise ValueError('Number of z-coordinates does not match paths.') + + segs = [_path_to_3d_segment(path, pathz, zdir) + for path, pathz in zip(paths, zs)] + return segs + + +def _path_to_3d_segment_with_codes(path, zs=0, zdir='z'): + """Convert a path to a 3D segment with path codes.""" + + zs = np.broadcast_to(zs, len(path)) + pathsegs = path.iter_segments(simplify=False, curves=False) + seg_codes = [((x, y, z), code) for ((x, y), code), z in zip(pathsegs, zs)] + if seg_codes: + seg, codes = zip(*seg_codes) + seg3d = [juggle_axes(x, y, z, zdir) for (x, y, z) in seg] + else: + seg3d = [] + codes = [] + return seg3d, list(codes) + + +def _paths_to_3d_segments_with_codes(paths, zs=0, zdir='z'): + """ + Convert paths from a collection object to 3D segments with path codes. + """ + + zs = np.broadcast_to(zs, len(paths)) + segments_codes = [_path_to_3d_segment_with_codes(path, pathz, zdir) + for path, pathz in zip(paths, zs)] + if segments_codes: + segments, codes = zip(*segments_codes) + else: + segments, codes = [], [] + return list(segments), list(codes) + + +class Collection3D(Collection): + """A collection of 3D paths.""" + + def do_3d_projection(self): + """Project the points according to renderer matrix.""" + vs_list = [vs for vs, _ in self._3dverts_codes] + if self._axlim_clip: + vs_list = [np.ma.row_stack(_viewlim_mask(*vs.T, self.axes)).T + for vs in vs_list] + xyzs_list = [proj3d.proj_transform(*vs.T, self.axes.M) for vs in vs_list] + self._paths = [mpath.Path(np.ma.column_stack([xs, ys]), cs) + for (xs, ys, _), (_, cs) in zip(xyzs_list, self._3dverts_codes)] + zs = np.concatenate([zs for _, _, zs in xyzs_list]) + return zs.min() if len(zs) else 1e9 + + +def collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False): + """Convert a `.Collection` to a `.Collection3D` object.""" + zs = np.broadcast_to(zs, len(col.get_paths())) + col._3dverts_codes = [ + (np.column_stack(juggle_axes( + *np.column_stack([p.vertices, np.broadcast_to(z, len(p.vertices))]).T, + zdir)), + p.codes) + for p, z in zip(col.get_paths(), zs)] + col.__class__ = cbook._make_class_factory(Collection3D, "{}3D")(type(col)) + col._axlim_clip = axlim_clip + + +class Line3DCollection(LineCollection): + """ + A collection of 3D lines. + """ + def __init__(self, lines, axlim_clip=False, **kwargs): + super().__init__(lines, **kwargs) + self._axlim_clip = axlim_clip + + def set_sort_zpos(self, val): + """Set the position to use for z-sorting.""" + self._sort_zpos = val + self.stale = True + + def set_segments(self, segments): + """ + Set 3D segments. + """ + self._segments3d = segments + super().set_segments([]) + + def do_3d_projection(self): + """ + Project the points according to renderer matrix. + """ + segments = self._segments3d + if self._axlim_clip: + all_points = np.ma.vstack(segments) + masked_points = np.ma.column_stack([*_viewlim_mask(*all_points.T, + self.axes)]) + segment_lengths = [np.shape(segment)[0] for segment in segments] + segments = np.split(masked_points, np.cumsum(segment_lengths[:-1])) + xyslist = [proj3d._proj_trans_points(points, self.axes.M) + for points in segments] + segments_2d = [np.ma.column_stack([xs, ys]) for xs, ys, zs in xyslist] + LineCollection.set_segments(self, segments_2d) + + # FIXME + minz = 1e9 + for xs, ys, zs in xyslist: + minz = min(minz, min(zs)) + return minz + + +def line_collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False): + """Convert a `.LineCollection` to a `.Line3DCollection` object.""" + segments3d = _paths_to_3d_segments(col.get_paths(), zs, zdir) + col.__class__ = Line3DCollection + col.set_segments(segments3d) + col._axlim_clip = axlim_clip + + +class Patch3D(Patch): + """ + 3D patch object. + """ + + def __init__(self, *args, zs=(), zdir='z', axlim_clip=False, **kwargs): + """ + Parameters + ---------- + verts : + zs : float + The location along the *zdir* axis in 3D space to position the + patch. + zdir : {'x', 'y', 'z'} + Plane to plot patch orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + """ + super().__init__(*args, **kwargs) + self.set_3d_properties(zs, zdir, axlim_clip) + + def set_3d_properties(self, verts, zs=0, zdir='z', axlim_clip=False): + """ + Set the *z* position and direction of the patch. + + Parameters + ---------- + verts : + zs : float + The location along the *zdir* axis in 3D space to position the + patch. + zdir : {'x', 'y', 'z'} + Plane to plot patch orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + """ + zs = np.broadcast_to(zs, len(verts)) + self._segment3d = [juggle_axes(x, y, z, zdir) + for ((x, y), z) in zip(verts, zs)] + self._axlim_clip = axlim_clip + + def get_path(self): + # docstring inherited + # self._path2d is not initialized until do_3d_projection + if not hasattr(self, '_path2d'): + self.axes.M = self.axes.get_proj() + self.do_3d_projection() + return self._path2d + + def do_3d_projection(self): + s = self._segment3d + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(*zip(*s), self.axes) + else: + xs, ys, zs = zip(*s) + vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs, + self.axes.M, + self.axes._focal_length) + self._path2d = mpath.Path(np.ma.column_stack([vxs, vys])) + return min(vzs) + + +class PathPatch3D(Patch3D): + """ + 3D PathPatch object. + """ + + def __init__(self, path, *, zs=(), zdir='z', axlim_clip=False, **kwargs): + """ + Parameters + ---------- + path : + zs : float + The location along the *zdir* axis in 3D space to position the + path patch. + zdir : {'x', 'y', 'z', 3-tuple} + Plane to plot path patch orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide path patches with a point outside the axes view limits. + """ + # Not super().__init__! + Patch.__init__(self, **kwargs) + self.set_3d_properties(path, zs, zdir, axlim_clip) + + def set_3d_properties(self, path, zs=0, zdir='z', axlim_clip=False): + """ + Set the *z* position and direction of the path patch. + + Parameters + ---------- + path : + zs : float + The location along the *zdir* axis in 3D space to position the + path patch. + zdir : {'x', 'y', 'z', 3-tuple} + Plane to plot path patch orthogonal to. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide path patches with a point outside the axes view limits. + """ + Patch3D.set_3d_properties(self, path.vertices, zs=zs, zdir=zdir, + axlim_clip=axlim_clip) + self._code3d = path.codes + + def do_3d_projection(self): + s = self._segment3d + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(*zip(*s), self.axes) + else: + xs, ys, zs = zip(*s) + vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs, + self.axes.M, + self.axes._focal_length) + self._path2d = mpath.Path(np.ma.column_stack([vxs, vys]), self._code3d) + return min(vzs) + + +def _get_patch_verts(patch): + """Return a list of vertices for the path of a patch.""" + trans = patch.get_patch_transform() + path = patch.get_path() + polygons = path.to_polygons(trans) + return polygons[0] if len(polygons) else np.array([]) + + +def patch_2d_to_3d(patch, z=0, zdir='z', axlim_clip=False): + """Convert a `.Patch` to a `.Patch3D` object.""" + verts = _get_patch_verts(patch) + patch.__class__ = Patch3D + patch.set_3d_properties(verts, z, zdir, axlim_clip) + + +def pathpatch_2d_to_3d(pathpatch, z=0, zdir='z'): + """Convert a `.PathPatch` to a `.PathPatch3D` object.""" + path = pathpatch.get_path() + trans = pathpatch.get_patch_transform() + + mpath = trans.transform_path(path) + pathpatch.__class__ = PathPatch3D + pathpatch.set_3d_properties(mpath, z, zdir) + + +class Patch3DCollection(PatchCollection): + """ + A collection of 3D patches. + """ + + def __init__(self, *args, + zs=0, zdir='z', depthshade=True, axlim_clip=False, **kwargs): + """ + Create a collection of flat 3D patches with its normal vector + pointed in *zdir* direction, and located at *zs* on the *zdir* + axis. 'zs' can be a scalar or an array-like of the same length as + the number of patches in the collection. + + Constructor arguments are the same as for + :class:`~matplotlib.collections.PatchCollection`. In addition, + keywords *zs=0* and *zdir='z'* are available. + + Also, the keyword argument *depthshade* is available to indicate + whether to shade the patches in order to give the appearance of depth + (default is *True*). This is typically desired in scatter plots. + """ + self._depthshade = depthshade + super().__init__(*args, **kwargs) + self.set_3d_properties(zs, zdir, axlim_clip) + + def get_depthshade(self): + return self._depthshade + + def set_depthshade(self, depthshade): + """ + Set whether depth shading is performed on collection members. + + Parameters + ---------- + depthshade : bool + Whether to shade the patches in order to give the appearance of + depth. + """ + self._depthshade = depthshade + self.stale = True + + def set_sort_zpos(self, val): + """Set the position to use for z-sorting.""" + self._sort_zpos = val + self.stale = True + + def set_3d_properties(self, zs, zdir, axlim_clip=False): + """ + Set the *z* positions and direction of the patches. + + Parameters + ---------- + zs : float or array of floats + The location or locations to place the patches in the collection + along the *zdir* axis. + zdir : {'x', 'y', 'z'} + Plane to plot patches orthogonal to. + All patches must have the same direction. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + """ + # Force the collection to initialize the face and edgecolors + # just in case it is a scalarmappable with a colormap. + self.update_scalarmappable() + offsets = self.get_offsets() + if len(offsets) > 0: + xs, ys = offsets.T + else: + xs = [] + ys = [] + self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) + self._z_markers_idx = slice(-1) + self._vzs = None + self._axlim_clip = axlim_clip + self.stale = True + + def do_3d_projection(self): + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(*self._offsets3d, self.axes) + else: + xs, ys, zs = self._offsets3d + vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs, + self.axes.M, + self.axes._focal_length) + self._vzs = vzs + super().set_offsets(np.ma.column_stack([vxs, vys])) + + if vzs.size > 0: + return min(vzs) + else: + return np.nan + + def _maybe_depth_shade_and_sort_colors(self, color_array): + color_array = ( + _zalpha(color_array, self._vzs) + if self._vzs is not None and self._depthshade + else color_array + ) + if len(color_array) > 1: + color_array = color_array[self._z_markers_idx] + return mcolors.to_rgba_array(color_array, self._alpha) + + def get_facecolor(self): + return self._maybe_depth_shade_and_sort_colors(super().get_facecolor()) + + def get_edgecolor(self): + # We need this check here to make sure we do not double-apply the depth + # based alpha shading when the edge color is "face" which means the + # edge colour should be identical to the face colour. + if cbook._str_equal(self._edgecolors, 'face'): + return self.get_facecolor() + return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor()) + + +class Path3DCollection(PathCollection): + """ + A collection of 3D paths. + """ + + def __init__(self, *args, + zs=0, zdir='z', depthshade=True, axlim_clip=False, **kwargs): + """ + Create a collection of flat 3D paths with its normal vector + pointed in *zdir* direction, and located at *zs* on the *zdir* + axis. 'zs' can be a scalar or an array-like of the same length as + the number of paths in the collection. + + Constructor arguments are the same as for + :class:`~matplotlib.collections.PathCollection`. In addition, + keywords *zs=0* and *zdir='z'* are available. + + Also, the keyword argument *depthshade* is available to indicate + whether to shade the patches in order to give the appearance of depth + (default is *True*). This is typically desired in scatter plots. + """ + self._depthshade = depthshade + self._in_draw = False + super().__init__(*args, **kwargs) + self.set_3d_properties(zs, zdir, axlim_clip) + self._offset_zordered = None + + def draw(self, renderer): + with self._use_zordered_offset(): + with cbook._setattr_cm(self, _in_draw=True): + super().draw(renderer) + + def set_sort_zpos(self, val): + """Set the position to use for z-sorting.""" + self._sort_zpos = val + self.stale = True + + def set_3d_properties(self, zs, zdir, axlim_clip=False): + """ + Set the *z* positions and direction of the paths. + + Parameters + ---------- + zs : float or array of floats + The location or locations to place the paths in the collection + along the *zdir* axis. + zdir : {'x', 'y', 'z'} + Plane to plot paths orthogonal to. + All paths must have the same direction. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide paths with a vertex outside the axes view limits. + """ + # Force the collection to initialize the face and edgecolors + # just in case it is a scalarmappable with a colormap. + self.update_scalarmappable() + offsets = self.get_offsets() + if len(offsets) > 0: + xs, ys = offsets.T + else: + xs = [] + ys = [] + self._zdir = zdir + self._offsets3d = juggle_axes(xs, ys, np.atleast_1d(zs), zdir) + # In the base draw methods we access the attributes directly which + # means we cannot resolve the shuffling in the getter methods like + # we do for the edge and face colors. + # + # This means we need to carry around a cache of the unsorted sizes and + # widths (postfixed with 3d) and in `do_3d_projection` set the + # depth-sorted version of that data into the private state used by the + # base collection class in its draw method. + # + # Grab the current sizes and linewidths to preserve them. + self._sizes3d = self._sizes + self._linewidths3d = np.array(self._linewidths) + xs, ys, zs = self._offsets3d + + # Sort the points based on z coordinates + # Performance optimization: Create a sorted index array and reorder + # points and point properties according to the index array + self._z_markers_idx = slice(-1) + self._vzs = None + + self._axlim_clip = axlim_clip + self.stale = True + + def set_sizes(self, sizes, dpi=72.0): + super().set_sizes(sizes, dpi) + if not self._in_draw: + self._sizes3d = sizes + + def set_linewidth(self, lw): + super().set_linewidth(lw) + if not self._in_draw: + self._linewidths3d = np.array(self._linewidths) + + def get_depthshade(self): + return self._depthshade + + def set_depthshade(self, depthshade): + """ + Set whether depth shading is performed on collection members. + + Parameters + ---------- + depthshade : bool + Whether to shade the patches in order to give the appearance of + depth. + """ + self._depthshade = depthshade + self.stale = True + + def do_3d_projection(self): + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(*self._offsets3d, self.axes) + else: + xs, ys, zs = self._offsets3d + vxs, vys, vzs, vis = proj3d._proj_transform_clip(xs, ys, zs, + self.axes.M, + self.axes._focal_length) + # Sort the points based on z coordinates + # Performance optimization: Create a sorted index array and reorder + # points and point properties according to the index array + z_markers_idx = self._z_markers_idx = np.ma.argsort(vzs)[::-1] + self._vzs = vzs + + # we have to special case the sizes because of code in collections.py + # as the draw method does + # self.set_sizes(self._sizes, self.figure.dpi) + # so we cannot rely on doing the sorting on the way out via get_* + + if len(self._sizes3d) > 1: + self._sizes = self._sizes3d[z_markers_idx] + + if len(self._linewidths3d) > 1: + self._linewidths = self._linewidths3d[z_markers_idx] + + PathCollection.set_offsets(self, np.ma.column_stack((vxs, vys))) + + # Re-order items + vzs = vzs[z_markers_idx] + vxs = vxs[z_markers_idx] + vys = vys[z_markers_idx] + + # Store ordered offset for drawing purpose + self._offset_zordered = np.ma.column_stack((vxs, vys)) + + return np.min(vzs) if vzs.size else np.nan + + @contextmanager + def _use_zordered_offset(self): + if self._offset_zordered is None: + # Do nothing + yield + else: + # Swap offset with z-ordered offset + old_offset = self._offsets + super().set_offsets(self._offset_zordered) + try: + yield + finally: + self._offsets = old_offset + + def _maybe_depth_shade_and_sort_colors(self, color_array): + color_array = ( + _zalpha(color_array, self._vzs) + if self._vzs is not None and self._depthshade + else color_array + ) + if len(color_array) > 1: + color_array = color_array[self._z_markers_idx] + return mcolors.to_rgba_array(color_array, self._alpha) + + def get_facecolor(self): + return self._maybe_depth_shade_and_sort_colors(super().get_facecolor()) + + def get_edgecolor(self): + # We need this check here to make sure we do not double-apply the depth + # based alpha shading when the edge color is "face" which means the + # edge colour should be identical to the face colour. + if cbook._str_equal(self._edgecolors, 'face'): + return self.get_facecolor() + return self._maybe_depth_shade_and_sort_colors(super().get_edgecolor()) + + +def patch_collection_2d_to_3d(col, zs=0, zdir='z', depthshade=True, axlim_clip=False): + """ + Convert a `.PatchCollection` into a `.Patch3DCollection` object + (or a `.PathCollection` into a `.Path3DCollection` object). + + Parameters + ---------- + col : `~matplotlib.collections.PatchCollection` or \ +`~matplotlib.collections.PathCollection` + The collection to convert. + zs : float or array of floats + The location or locations to place the patches in the collection along + the *zdir* axis. Default: 0. + zdir : {'x', 'y', 'z'} + The axis in which to place the patches. Default: "z". + See `.get_dir_vector` for a description of the values. + depthshade : bool, default: True + Whether to shade the patches to give a sense of depth. + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + """ + if isinstance(col, PathCollection): + col.__class__ = Path3DCollection + col._offset_zordered = None + elif isinstance(col, PatchCollection): + col.__class__ = Patch3DCollection + col._depthshade = depthshade + col._in_draw = False + col.set_3d_properties(zs, zdir, axlim_clip) + + +class Poly3DCollection(PolyCollection): + """ + A collection of 3D polygons. + + .. note:: + **Filling of 3D polygons** + + There is no simple definition of the enclosed surface of a 3D polygon + unless the polygon is planar. + + In practice, Matplotlib fills the 2D projection of the polygon. This + gives a correct filling appearance only for planar polygons. For all + other polygons, you'll find orientations in which the edges of the + polygon intersect in the projection. This will lead to an incorrect + visualization of the 3D area. + + If you need filled areas, it is recommended to create them via + `~mpl_toolkits.mplot3d.axes3d.Axes3D.plot_trisurf`, which creates a + triangulation and thus generates consistent surfaces. + """ + + def __init__(self, verts, *args, zsort='average', shade=False, + lightsource=None, axlim_clip=False, **kwargs): + """ + Parameters + ---------- + verts : list of (N, 3) array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (N, 3). + zsort : {'average', 'min', 'max'}, default: 'average' + The calculation method for the z-order. + See `~.Poly3DCollection.set_zsort` for details. + shade : bool, default: False + Whether to shade *facecolors* and *edgecolors*. When activating + *shade*, *facecolors* and/or *edgecolors* must be provided. + + .. versionadded:: 3.7 + + lightsource : `~matplotlib.colors.LightSource`, optional + The lightsource to use when *shade* is True. + + .. versionadded:: 3.7 + + axlim_clip : bool, default: False + Whether to hide polygons with a vertex outside the view limits. + + *args, **kwargs + All other parameters are forwarded to `.PolyCollection`. + + Notes + ----- + Note that this class does a bit of magic with the _facecolors + and _edgecolors properties. + """ + if shade: + normals = _generate_normals(verts) + facecolors = kwargs.get('facecolors', None) + if facecolors is not None: + kwargs['facecolors'] = _shade_colors( + facecolors, normals, lightsource + ) + + edgecolors = kwargs.get('edgecolors', None) + if edgecolors is not None: + kwargs['edgecolors'] = _shade_colors( + edgecolors, normals, lightsource + ) + if facecolors is None and edgecolors is None: + raise ValueError( + "You must provide facecolors, edgecolors, or both for " + "shade to work.") + super().__init__(verts, *args, **kwargs) + if isinstance(verts, np.ndarray): + if verts.ndim != 3: + raise ValueError('verts must be a list of (N, 3) array-like') + else: + if any(len(np.shape(vert)) != 2 for vert in verts): + raise ValueError('verts must be a list of (N, 3) array-like') + self.set_zsort(zsort) + self._codes3d = None + self._axlim_clip = axlim_clip + + _zsort_functions = { + 'average': np.average, + 'min': np.min, + 'max': np.max, + } + + def set_zsort(self, zsort): + """ + Set the calculation method for the z-order. + + Parameters + ---------- + zsort : {'average', 'min', 'max'} + The function applied on the z-coordinates of the vertices in the + viewer's coordinate system, to determine the z-order. + """ + self._zsortfunc = self._zsort_functions[zsort] + self._sort_zpos = None + self.stale = True + + @_api.deprecated("3.10") + def get_vector(self, segments3d): + return self._get_vector(segments3d) + + def _get_vector(self, segments3d): + """Optimize points for projection.""" + if len(segments3d): + xs, ys, zs = np.vstack(segments3d).T + else: # vstack can't stack zero arrays. + xs, ys, zs = [], [], [] + ones = np.ones(len(xs)) + self._vec = np.array([xs, ys, zs, ones]) + + indices = [0, *np.cumsum([len(segment) for segment in segments3d])] + self._segslices = [*map(slice, indices[:-1], indices[1:])] + + def set_verts(self, verts, closed=True): + """ + Set 3D vertices. + + Parameters + ---------- + verts : list of (N, 3) array-like + The sequence of polygons [*verts0*, *verts1*, ...] where each + element *verts_i* defines the vertices of polygon *i* as a 2D + array-like of shape (N, 3). + closed : bool, default: True + Whether the polygon should be closed by adding a CLOSEPOLY + connection at the end. + """ + self._get_vector(verts) + # 2D verts will be updated at draw time + super().set_verts([], False) + self._closed = closed + + def set_verts_and_codes(self, verts, codes): + """Set 3D vertices with path codes.""" + # set vertices with closed=False to prevent PolyCollection from + # setting path codes + self.set_verts(verts, closed=False) + # and set our own codes instead. + self._codes3d = codes + + def set_3d_properties(self, axlim_clip=False): + # Force the collection to initialize the face and edgecolors + # just in case it is a scalarmappable with a colormap. + self.update_scalarmappable() + self._sort_zpos = None + self.set_zsort('average') + self._facecolor3d = PolyCollection.get_facecolor(self) + self._edgecolor3d = PolyCollection.get_edgecolor(self) + self._alpha3d = PolyCollection.get_alpha(self) + self.stale = True + + def set_sort_zpos(self, val): + """Set the position to use for z-sorting.""" + self._sort_zpos = val + self.stale = True + + def do_3d_projection(self): + """ + Perform the 3D projection for this object. + """ + if self._A is not None: + # force update of color mapping because we re-order them + # below. If we do not do this here, the 2D draw will call + # this, but we will never port the color mapped values back + # to the 3D versions. + # + # We hold the 3D versions in a fixed order (the order the user + # passed in) and sort the 2D version by view depth. + self.update_scalarmappable() + if self._face_is_mapped: + self._facecolor3d = self._facecolors + if self._edge_is_mapped: + self._edgecolor3d = self._edgecolors + if self._axlim_clip: + xs, ys, zs = _viewlim_mask(*self._vec[0:3], self.axes) + if self._vec.shape[0] == 4: # Will be 3 (xyz) or 4 (xyzw) + w_masked = np.ma.masked_where(zs.mask, self._vec[3]) + vec = np.ma.array([xs, ys, zs, w_masked]) + else: + vec = np.ma.array([xs, ys, zs]) + else: + vec = self._vec + txs, tys, tzs = proj3d._proj_transform_vec(vec, self.axes.M) + xyzlist = [(txs[sl], tys[sl], tzs[sl]) for sl in self._segslices] + + # This extra fuss is to re-order face / edge colors + cface = self._facecolor3d + cedge = self._edgecolor3d + if len(cface) != len(xyzlist): + cface = cface.repeat(len(xyzlist), axis=0) + if len(cedge) != len(xyzlist): + if len(cedge) == 0: + cedge = cface + else: + cedge = cedge.repeat(len(xyzlist), axis=0) + + if xyzlist: + # sort by depth (furthest drawn first) + z_segments_2d = sorted( + ((self._zsortfunc(zs.data), np.ma.column_stack([xs, ys]), fc, ec, idx) + for idx, ((xs, ys, zs), fc, ec) + in enumerate(zip(xyzlist, cface, cedge))), + key=lambda x: x[0], reverse=True) + + _, segments_2d, self._facecolors2d, self._edgecolors2d, idxs = \ + zip(*z_segments_2d) + else: + segments_2d = [] + self._facecolors2d = np.empty((0, 4)) + self._edgecolors2d = np.empty((0, 4)) + idxs = [] + + if self._codes3d is not None: + codes = [self._codes3d[idx] for idx in idxs] + PolyCollection.set_verts_and_codes(self, segments_2d, codes) + else: + PolyCollection.set_verts(self, segments_2d, self._closed) + + if len(self._edgecolor3d) != len(cface): + self._edgecolors2d = self._edgecolor3d + + # Return zorder value + if self._sort_zpos is not None: + zvec = np.array([[0], [0], [self._sort_zpos], [1]]) + ztrans = proj3d._proj_transform_vec(zvec, self.axes.M) + return ztrans[2][0] + elif tzs.size > 0: + # FIXME: Some results still don't look quite right. + # In particular, examine contourf3d_demo2.py + # with az = -54 and elev = -45. + return np.min(tzs) + else: + return np.nan + + def set_facecolor(self, colors): + # docstring inherited + super().set_facecolor(colors) + self._facecolor3d = PolyCollection.get_facecolor(self) + + def set_edgecolor(self, colors): + # docstring inherited + super().set_edgecolor(colors) + self._edgecolor3d = PolyCollection.get_edgecolor(self) + + def set_alpha(self, alpha): + # docstring inherited + artist.Artist.set_alpha(self, alpha) + try: + self._facecolor3d = mcolors.to_rgba_array( + self._facecolor3d, self._alpha) + except (AttributeError, TypeError, IndexError): + pass + try: + self._edgecolors = mcolors.to_rgba_array( + self._edgecolor3d, self._alpha) + except (AttributeError, TypeError, IndexError): + pass + self.stale = True + + def get_facecolor(self): + # docstring inherited + # self._facecolors2d is not initialized until do_3d_projection + if not hasattr(self, '_facecolors2d'): + self.axes.M = self.axes.get_proj() + self.do_3d_projection() + return np.asarray(self._facecolors2d) + + def get_edgecolor(self): + # docstring inherited + # self._edgecolors2d is not initialized until do_3d_projection + if not hasattr(self, '_edgecolors2d'): + self.axes.M = self.axes.get_proj() + self.do_3d_projection() + return np.asarray(self._edgecolors2d) + + +def poly_collection_2d_to_3d(col, zs=0, zdir='z', axlim_clip=False): + """ + Convert a `.PolyCollection` into a `.Poly3DCollection` object. + + Parameters + ---------- + col : `~matplotlib.collections.PolyCollection` + The collection to convert. + zs : float or array of floats + The location or locations to place the polygons in the collection along + the *zdir* axis. Default: 0. + zdir : {'x', 'y', 'z'} + The axis in which to place the patches. Default: 'z'. + See `.get_dir_vector` for a description of the values. + """ + segments_3d, codes = _paths_to_3d_segments_with_codes( + col.get_paths(), zs, zdir) + col.__class__ = Poly3DCollection + col.set_verts_and_codes(segments_3d, codes) + col.set_3d_properties() + col._axlim_clip = axlim_clip + + +def juggle_axes(xs, ys, zs, zdir): + """ + Reorder coordinates so that 2D *xs*, *ys* can be plotted in the plane + orthogonal to *zdir*. *zdir* is normally 'x', 'y' or 'z'. However, if + *zdir* starts with a '-' it is interpreted as a compensation for + `rotate_axes`. + """ + if zdir == 'x': + return zs, xs, ys + elif zdir == 'y': + return xs, zs, ys + elif zdir[0] == '-': + return rotate_axes(xs, ys, zs, zdir) + else: + return xs, ys, zs + + +def rotate_axes(xs, ys, zs, zdir): + """ + Reorder coordinates so that the axes are rotated with *zdir* along + the original z axis. Prepending the axis with a '-' does the + inverse transform, so *zdir* can be 'x', '-x', 'y', '-y', 'z' or '-z'. + """ + if zdir in ('x', '-y'): + return ys, zs, xs + elif zdir in ('-x', 'y'): + return zs, xs, ys + else: + return xs, ys, zs + + +def _zalpha(colors, zs): + """Modify the alphas of the color list according to depth.""" + # FIXME: This only works well if the points for *zs* are well-spaced + # in all three dimensions. Otherwise, at certain orientations, + # the min and max zs are very close together. + # Should really normalize against the viewing depth. + if len(colors) == 0 or len(zs) == 0: + return np.zeros((0, 4)) + norm = Normalize(min(zs), max(zs)) + sats = 1 - norm(zs) * 0.7 + rgba = np.broadcast_to(mcolors.to_rgba_array(colors), (len(zs), 4)) + return np.column_stack([rgba[:, :3], rgba[:, 3] * sats]) + + +def _all_points_on_plane(xs, ys, zs, atol=1e-8): + """ + Check if all points are on the same plane. Note that NaN values are + ignored. + + Parameters + ---------- + xs, ys, zs : array-like + The x, y, and z coordinates of the points. + atol : float, default: 1e-8 + The tolerance for the equality check. + """ + xs, ys, zs = np.asarray(xs), np.asarray(ys), np.asarray(zs) + points = np.column_stack([xs, ys, zs]) + points = points[~np.isnan(points).any(axis=1)] + # Check for the case where we have less than 3 unique points + points = np.unique(points, axis=0) + if len(points) <= 3: + return True + # Calculate the vectors from the first point to all other points + vs = (points - points[0])[1:] + vs = vs / np.linalg.norm(vs, axis=1)[:, np.newaxis] + # Filter out parallel vectors + vs = np.unique(vs, axis=0) + if len(vs) <= 2: + return True + # Filter out parallel and antiparallel vectors to the first vector + cross_norms = np.linalg.norm(np.cross(vs[0], vs[1:]), axis=1) + zero_cross_norms = np.where(np.isclose(cross_norms, 0, atol=atol))[0] + 1 + vs = np.delete(vs, zero_cross_norms, axis=0) + if len(vs) <= 2: + return True + # Calculate the normal vector from the first three points + n = np.cross(vs[0], vs[1]) + n = n / np.linalg.norm(n) + # If the dot product of the normal vector and all other vectors is zero, + # all points are on the same plane + dots = np.dot(n, vs.transpose()) + return np.allclose(dots, 0, atol=atol) + + +def _generate_normals(polygons): + """ + Compute the normals of a list of polygons, one normal per polygon. + + Normals point towards the viewer for a face with its vertices in + counterclockwise order, following the right hand rule. + + Uses three points equally spaced around the polygon. This method assumes + that the points are in a plane. Otherwise, more than one shade is required, + which is not supported. + + Parameters + ---------- + polygons : list of (M_i, 3) array-like, or (..., M, 3) array-like + A sequence of polygons to compute normals for, which can have + varying numbers of vertices. If the polygons all have the same + number of vertices and array is passed, then the operation will + be vectorized. + + Returns + ------- + normals : (..., 3) array + A normal vector estimated for the polygon. + """ + if isinstance(polygons, np.ndarray): + # optimization: polygons all have the same number of points, so can + # vectorize + n = polygons.shape[-2] + i1, i2, i3 = 0, n//3, 2*n//3 + v1 = polygons[..., i1, :] - polygons[..., i2, :] + v2 = polygons[..., i2, :] - polygons[..., i3, :] + else: + # The subtraction doesn't vectorize because polygons is jagged. + v1 = np.empty((len(polygons), 3)) + v2 = np.empty((len(polygons), 3)) + for poly_i, ps in enumerate(polygons): + n = len(ps) + ps = np.asarray(ps) + i1, i2, i3 = 0, n//3, 2*n//3 + v1[poly_i, :] = ps[i1, :] - ps[i2, :] + v2[poly_i, :] = ps[i2, :] - ps[i3, :] + return np.cross(v1, v2) + + +def _shade_colors(color, normals, lightsource=None): + """ + Shade *color* using normal vectors given by *normals*, + assuming a *lightsource* (using default position if not given). + *color* can also be an array of the same length as *normals*. + """ + if lightsource is None: + # chosen for backwards-compatibility + lightsource = mcolors.LightSource(azdeg=225, altdeg=19.4712) + + with np.errstate(invalid="ignore"): + shade = ((normals / np.linalg.norm(normals, axis=1, keepdims=True)) + @ lightsource.direction) + mask = ~np.isnan(shade) + + if mask.any(): + # convert dot product to allowed shading fractions + in_norm = mcolors.Normalize(-1, 1) + out_norm = mcolors.Normalize(0.3, 1).inverse + + def norm(x): + return out_norm(in_norm(x)) + + shade[~mask] = 0 + + color = mcolors.to_rgba_array(color) + # shape of color should be (M, 4) (where M is number of faces) + # shape of shade should be (M,) + # colors should have final shape of (M, 4) + alpha = color[:, 3] + colors = norm(shade)[:, np.newaxis] * color + colors[:, 3] = alpha + else: + colors = np.asanyarray(color).copy() + + return colors diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axes3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axes3d.py new file mode 100644 index 0000000000000000000000000000000000000000..d0ba360c314bbaa39efd5e64936a07e6cd0ec0f6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axes3d.py @@ -0,0 +1,4162 @@ +""" +axes3d.py, original mplot3d version by John Porter +Created: 23 Sep 2005 + +Parts fixed by Reinier Heeres +Minor additions by Ben Axelrod +Significant updates and revisions by Ben Root + +Module containing Axes3D, an object which can plot 3D objects on a +2D matplotlib figure. +""" + +from collections import defaultdict +import itertools +import math +import textwrap +import warnings + +import numpy as np + +import matplotlib as mpl +from matplotlib import _api, cbook, _docstring, _preprocess_data +import matplotlib.artist as martist +import matplotlib.collections as mcoll +import matplotlib.colors as mcolors +import matplotlib.image as mimage +import matplotlib.lines as mlines +import matplotlib.patches as mpatches +import matplotlib.container as mcontainer +import matplotlib.transforms as mtransforms +from matplotlib.axes import Axes +from matplotlib.axes._base import _axis_method_wrapper, _process_plot_format +from matplotlib.transforms import Bbox +from matplotlib.tri._triangulation import Triangulation + +from . import art3d +from . import proj3d +from . import axis3d + + +@_docstring.interpd +@_api.define_aliases({ + "xlim": ["xlim3d"], "ylim": ["ylim3d"], "zlim": ["zlim3d"]}) +class Axes3D(Axes): + """ + 3D Axes object. + + .. note:: + + As a user, you do not instantiate Axes directly, but use Axes creation + methods instead; e.g. from `.pyplot` or `.Figure`: + `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` or `.Figure.add_axes`. + """ + name = '3d' + + _axis_names = ("x", "y", "z") + Axes._shared_axes["z"] = cbook.Grouper() + Axes._shared_axes["view"] = cbook.Grouper() + + def __init__( + self, fig, rect=None, *args, + elev=30, azim=-60, roll=0, shareview=None, sharez=None, + proj_type='persp', focal_length=None, + box_aspect=None, + computed_zorder=True, + **kwargs, + ): + """ + Parameters + ---------- + fig : Figure + The parent figure. + rect : tuple (left, bottom, width, height), default: None. + The ``(left, bottom, width, height)`` Axes position. + elev : float, default: 30 + The elevation angle in degrees rotates the camera above and below + the x-y plane, with a positive angle corresponding to a location + above the plane. + azim : float, default: -60 + The azimuthal angle in degrees rotates the camera about the z axis, + with a positive angle corresponding to a right-handed rotation. In + other words, a positive azimuth rotates the camera about the origin + from its location along the +x axis towards the +y axis. + roll : float, default: 0 + The roll angle in degrees rotates the camera about the viewing + axis. A positive angle spins the camera clockwise, causing the + scene to rotate counter-clockwise. + shareview : Axes3D, optional + Other Axes to share view angles with. Note that it is not possible + to unshare axes. + sharez : Axes3D, optional + Other Axes to share z-limits with. Note that it is not possible to + unshare axes. + proj_type : {'persp', 'ortho'} + The projection type, default 'persp'. + focal_length : float, default: None + For a projection type of 'persp', the focal length of the virtual + camera. Must be > 0. If None, defaults to 1. + For a projection type of 'ortho', must be set to either None + or infinity (numpy.inf). If None, defaults to infinity. + The focal length can be computed from a desired Field Of View via + the equation: focal_length = 1/tan(FOV/2) + box_aspect : 3-tuple of floats, default: None + Changes the physical dimensions of the Axes3D, such that the ratio + of the axis lengths in display units is x:y:z. + If None, defaults to 4:4:3 + computed_zorder : bool, default: True + If True, the draw order is computed based on the average position + of the `.Artist`\\s along the view direction. + Set to False if you want to manually control the order in which + Artists are drawn on top of each other using their *zorder* + attribute. This can be used for fine-tuning if the automatic order + does not produce the desired result. Note however, that a manual + zorder will only be correct for a limited view angle. If the figure + is rotated by the user, it will look wrong from certain angles. + + **kwargs + Other optional keyword arguments: + + %(Axes3D:kwdoc)s + """ + + if rect is None: + rect = [0.0, 0.0, 1.0, 1.0] + + self.initial_azim = azim + self.initial_elev = elev + self.initial_roll = roll + self.set_proj_type(proj_type, focal_length) + self.computed_zorder = computed_zorder + + self.xy_viewLim = Bbox.unit() + self.zz_viewLim = Bbox.unit() + xymargin = 0.05 * 10/11 # match mpl3.8 appearance + self.xy_dataLim = Bbox([[xymargin, xymargin], + [1 - xymargin, 1 - xymargin]]) + # z-limits are encoded in the x-component of the Bbox, y is un-used + self.zz_dataLim = Bbox.unit() + + # inhibit autoscale_view until the axes are defined + # they can't be defined until Axes.__init__ has been called + self.view_init(self.initial_elev, self.initial_azim, self.initial_roll) + + self._sharez = sharez + if sharez is not None: + self._shared_axes["z"].join(self, sharez) + self._adjustable = 'datalim' + + self._shareview = shareview + if shareview is not None: + self._shared_axes["view"].join(self, shareview) + + if kwargs.pop('auto_add_to_figure', False): + raise AttributeError( + 'auto_add_to_figure is no longer supported for Axes3D. ' + 'Use fig.add_axes(ax) instead.' + ) + + super().__init__( + fig, rect, frameon=True, box_aspect=box_aspect, *args, **kwargs + ) + # Disable drawing of axes by base class + super().set_axis_off() + # Enable drawing of axes by Axes3D class + self.set_axis_on() + self.M = None + self.invM = None + + self._view_margin = 1/48 # default value to match mpl3.8 + self.autoscale_view() + + # func used to format z -- fall back on major formatters + self.fmt_zdata = None + + self.mouse_init() + fig = self.get_figure(root=True) + fig.canvas.callbacks._connect_picklable( + 'motion_notify_event', self._on_move) + fig.canvas.callbacks._connect_picklable( + 'button_press_event', self._button_press) + fig.canvas.callbacks._connect_picklable( + 'button_release_event', self._button_release) + self.set_top_view() + + self.patch.set_linewidth(0) + # Calculate the pseudo-data width and height + pseudo_bbox = self.transLimits.inverted().transform([(0, 0), (1, 1)]) + self._pseudo_w, self._pseudo_h = pseudo_bbox[1] - pseudo_bbox[0] + + # mplot3d currently manages its own spines and needs these turned off + # for bounding box calculations + self.spines[:].set_visible(False) + + def set_axis_off(self): + self._axis3don = False + self.stale = True + + def set_axis_on(self): + self._axis3don = True + self.stale = True + + def convert_zunits(self, z): + """ + For artists in an Axes, if the zaxis has units support, + convert *z* using zaxis unit type + """ + return self.zaxis.convert_units(z) + + def set_top_view(self): + # this happens to be the right view for the viewing coordinates + # moved up and to the left slightly to fit labels and axes + xdwl = 0.95 / self._dist + xdw = 0.9 / self._dist + ydwl = 0.95 / self._dist + ydw = 0.9 / self._dist + # Set the viewing pane. + self.viewLim.intervalx = (-xdwl, xdw) + self.viewLim.intervaly = (-ydwl, ydw) + self.stale = True + + def _init_axis(self): + """Init 3D Axes; overrides creation of regular X/Y Axes.""" + self.xaxis = axis3d.XAxis(self) + self.yaxis = axis3d.YAxis(self) + self.zaxis = axis3d.ZAxis(self) + + def get_zaxis(self): + """Return the ``ZAxis`` (`~.axis3d.Axis`) instance.""" + return self.zaxis + + get_zgridlines = _axis_method_wrapper("zaxis", "get_gridlines") + get_zticklines = _axis_method_wrapper("zaxis", "get_ticklines") + + def _transformed_cube(self, vals): + """Return cube with limits from *vals* transformed by self.M.""" + minx, maxx, miny, maxy, minz, maxz = vals + xyzs = [(minx, miny, minz), + (maxx, miny, minz), + (maxx, maxy, minz), + (minx, maxy, minz), + (minx, miny, maxz), + (maxx, miny, maxz), + (maxx, maxy, maxz), + (minx, maxy, maxz)] + return proj3d._proj_points(xyzs, self.M) + + def set_aspect(self, aspect, adjustable=None, anchor=None, share=False): + """ + Set the aspect ratios. + + Parameters + ---------- + aspect : {'auto', 'equal', 'equalxy', 'equalxz', 'equalyz'} + Possible values: + + ========= ================================================== + value description + ========= ================================================== + 'auto' automatic; fill the position rectangle with data. + 'equal' adapt all the axes to have equal aspect ratios. + 'equalxy' adapt the x and y axes to have equal aspect ratios. + 'equalxz' adapt the x and z axes to have equal aspect ratios. + 'equalyz' adapt the y and z axes to have equal aspect ratios. + ========= ================================================== + + adjustable : None or {'box', 'datalim'}, optional + If not *None*, this defines which parameter will be adjusted to + meet the required aspect. See `.set_adjustable` for further + details. + + anchor : None or str or 2-tuple of float, optional + If not *None*, this defines where the Axes will be drawn if there + is extra space due to aspect constraints. The most common way to + specify the anchor are abbreviations of cardinal directions: + + ===== ===================== + value description + ===== ===================== + 'C' centered + 'SW' lower left corner + 'S' middle of bottom edge + 'SE' lower right corner + etc. + ===== ===================== + + See `~.Axes.set_anchor` for further details. + + share : bool, default: False + If ``True``, apply the settings to all shared Axes. + + See Also + -------- + mpl_toolkits.mplot3d.axes3d.Axes3D.set_box_aspect + """ + _api.check_in_list(('auto', 'equal', 'equalxy', 'equalyz', 'equalxz'), + aspect=aspect) + super().set_aspect( + aspect='auto', adjustable=adjustable, anchor=anchor, share=share) + self._aspect = aspect + + if aspect in ('equal', 'equalxy', 'equalxz', 'equalyz'): + ax_indices = self._equal_aspect_axis_indices(aspect) + + view_intervals = np.array([self.xaxis.get_view_interval(), + self.yaxis.get_view_interval(), + self.zaxis.get_view_interval()]) + ptp = np.ptp(view_intervals, axis=1) + if self._adjustable == 'datalim': + mean = np.mean(view_intervals, axis=1) + scale = max(ptp[ax_indices] / self._box_aspect[ax_indices]) + deltas = scale * self._box_aspect + + for i, set_lim in enumerate((self.set_xlim3d, + self.set_ylim3d, + self.set_zlim3d)): + if i in ax_indices: + set_lim(mean[i] - deltas[i]/2., mean[i] + deltas[i]/2., + auto=True, view_margin=None) + else: # 'box' + # Change the box aspect such that the ratio of the length of + # the unmodified axis to the length of the diagonal + # perpendicular to it remains unchanged. + box_aspect = np.array(self._box_aspect) + box_aspect[ax_indices] = ptp[ax_indices] + remaining_ax_indices = {0, 1, 2}.difference(ax_indices) + if remaining_ax_indices: + remaining = remaining_ax_indices.pop() + old_diag = np.linalg.norm(self._box_aspect[ax_indices]) + new_diag = np.linalg.norm(box_aspect[ax_indices]) + box_aspect[remaining] *= new_diag / old_diag + self.set_box_aspect(box_aspect) + + def _equal_aspect_axis_indices(self, aspect): + """ + Get the indices for which of the x, y, z axes are constrained to have + equal aspect ratios. + + Parameters + ---------- + aspect : {'auto', 'equal', 'equalxy', 'equalxz', 'equalyz'} + See descriptions in docstring for `.set_aspect()`. + """ + ax_indices = [] # aspect == 'auto' + if aspect == 'equal': + ax_indices = [0, 1, 2] + elif aspect == 'equalxy': + ax_indices = [0, 1] + elif aspect == 'equalxz': + ax_indices = [0, 2] + elif aspect == 'equalyz': + ax_indices = [1, 2] + return ax_indices + + def set_box_aspect(self, aspect, *, zoom=1): + """ + Set the Axes box aspect. + + The box aspect is the ratio of height to width in display + units for each face of the box when viewed perpendicular to + that face. This is not to be confused with the data aspect (see + `~.Axes3D.set_aspect`). The default ratios are 4:4:3 (x:y:z). + + To simulate having equal aspect in data space, set the box + aspect to match your data range in each dimension. + + *zoom* controls the overall size of the Axes3D in the figure. + + Parameters + ---------- + aspect : 3-tuple of floats or None + Changes the physical dimensions of the Axes3D, such that the ratio + of the axis lengths in display units is x:y:z. + If None, defaults to (4, 4, 3). + + zoom : float, default: 1 + Control overall size of the Axes3D in the figure. Must be > 0. + """ + if zoom <= 0: + raise ValueError(f'Argument zoom = {zoom} must be > 0') + + if aspect is None: + aspect = np.asarray((4, 4, 3), dtype=float) + else: + aspect = np.asarray(aspect, dtype=float) + _api.check_shape((3,), aspect=aspect) + # The scale 1.8294640721620434 is tuned to match the mpl3.2 appearance. + # The 25/24 factor is to compensate for the change in automargin + # behavior in mpl3.9. This comes from the padding of 1/48 on both sides + # of the axes in mpl3.8. + aspect *= 1.8294640721620434 * 25/24 * zoom / np.linalg.norm(aspect) + + self._box_aspect = self._roll_to_vertical(aspect, reverse=True) + self.stale = True + + def apply_aspect(self, position=None): + if position is None: + position = self.get_position(original=True) + + # in the superclass, we would go through and actually deal with axis + # scales and box/datalim. Those are all irrelevant - all we need to do + # is make sure our coordinate system is square. + trans = self.get_figure().transSubfigure + bb = mtransforms.Bbox.unit().transformed(trans) + # this is the physical aspect of the panel (or figure): + fig_aspect = bb.height / bb.width + + box_aspect = 1 + pb = position.frozen() + pb1 = pb.shrunk_to_aspect(box_aspect, pb, fig_aspect) + self._set_position(pb1.anchored(self.get_anchor(), pb), 'active') + + @martist.allow_rasterization + def draw(self, renderer): + if not self.get_visible(): + return + self._unstale_viewLim() + + # draw the background patch + self.patch.draw(renderer) + self._frameon = False + + # first, set the aspect + # this is duplicated from `axes._base._AxesBase.draw` + # but must be called before any of the artist are drawn as + # it adjusts the view limits and the size of the bounding box + # of the Axes + locator = self.get_axes_locator() + self.apply_aspect(locator(self, renderer) if locator else None) + + # add the projection matrix to the renderer + self.M = self.get_proj() + self.invM = np.linalg.inv(self.M) + + collections_and_patches = ( + artist for artist in self._children + if isinstance(artist, (mcoll.Collection, mpatches.Patch)) + and artist.get_visible()) + if self.computed_zorder: + # Calculate projection of collections and patches and zorder + # them. Make sure they are drawn above the grids. + zorder_offset = max(axis.get_zorder() + for axis in self._axis_map.values()) + 1 + collection_zorder = patch_zorder = zorder_offset + + for artist in sorted(collections_and_patches, + key=lambda artist: artist.do_3d_projection(), + reverse=True): + if isinstance(artist, mcoll.Collection): + artist.zorder = collection_zorder + collection_zorder += 1 + elif isinstance(artist, mpatches.Patch): + artist.zorder = patch_zorder + patch_zorder += 1 + else: + for artist in collections_and_patches: + artist.do_3d_projection() + + if self._axis3don: + # Draw panes first + for axis in self._axis_map.values(): + axis.draw_pane(renderer) + # Then gridlines + for axis in self._axis_map.values(): + axis.draw_grid(renderer) + # Then axes, labels, text, and ticks + for axis in self._axis_map.values(): + axis.draw(renderer) + + # Then rest + super().draw(renderer) + + def get_axis_position(self): + tc = self._transformed_cube(self.get_w_lims()) + xhigh = tc[1][2] > tc[2][2] + yhigh = tc[3][2] > tc[2][2] + zhigh = tc[0][2] > tc[2][2] + return xhigh, yhigh, zhigh + + def update_datalim(self, xys, **kwargs): + """ + Not implemented in `~mpl_toolkits.mplot3d.axes3d.Axes3D`. + """ + pass + + get_autoscalez_on = _axis_method_wrapper("zaxis", "_get_autoscale_on") + set_autoscalez_on = _axis_method_wrapper("zaxis", "_set_autoscale_on") + + def get_zmargin(self): + """ + Retrieve autoscaling margin of the z-axis. + + .. versionadded:: 3.9 + + Returns + ------- + zmargin : float + + See Also + -------- + mpl_toolkits.mplot3d.axes3d.Axes3D.set_zmargin + """ + return self._zmargin + + def set_zmargin(self, m): + """ + Set padding of Z data limits prior to autoscaling. + + *m* times the data interval will be added to each end of that interval + before it is used in autoscaling. If *m* is negative, this will clip + the data range instead of expanding it. + + For example, if your data is in the range [0, 2], a margin of 0.1 will + result in a range [-0.2, 2.2]; a margin of -0.1 will result in a range + of [0.2, 1.8]. + + Parameters + ---------- + m : float greater than -0.5 + """ + if m <= -0.5: + raise ValueError("margin must be greater than -0.5") + self._zmargin = m + self._request_autoscale_view("z") + self.stale = True + + def margins(self, *margins, x=None, y=None, z=None, tight=True): + """ + Set or retrieve autoscaling margins. + + See `.Axes.margins` for full documentation. Because this function + applies to 3D Axes, it also takes a *z* argument, and returns + ``(xmargin, ymargin, zmargin)``. + """ + if margins and (x is not None or y is not None or z is not None): + raise TypeError('Cannot pass both positional and keyword ' + 'arguments for x, y, and/or z.') + elif len(margins) == 1: + x = y = z = margins[0] + elif len(margins) == 3: + x, y, z = margins + elif margins: + raise TypeError('Must pass a single positional argument for all ' + 'margins, or one for each margin (x, y, z).') + + if x is None and y is None and z is None: + if tight is not True: + _api.warn_external(f'ignoring tight={tight!r} in get mode') + return self._xmargin, self._ymargin, self._zmargin + + if x is not None: + self.set_xmargin(x) + if y is not None: + self.set_ymargin(y) + if z is not None: + self.set_zmargin(z) + + self.autoscale_view( + tight=tight, scalex=(x is not None), scaley=(y is not None), + scalez=(z is not None) + ) + + def autoscale(self, enable=True, axis='both', tight=None): + """ + Convenience method for simple axis view autoscaling. + + See `.Axes.autoscale` for full documentation. Because this function + applies to 3D Axes, *axis* can also be set to 'z', and setting *axis* + to 'both' autoscales all three axes. + """ + if enable is None: + scalex = True + scaley = True + scalez = True + else: + if axis in ['x', 'both']: + self.set_autoscalex_on(enable) + scalex = self.get_autoscalex_on() + else: + scalex = False + if axis in ['y', 'both']: + self.set_autoscaley_on(enable) + scaley = self.get_autoscaley_on() + else: + scaley = False + if axis in ['z', 'both']: + self.set_autoscalez_on(enable) + scalez = self.get_autoscalez_on() + else: + scalez = False + if scalex: + self._request_autoscale_view("x", tight=tight) + if scaley: + self._request_autoscale_view("y", tight=tight) + if scalez: + self._request_autoscale_view("z", tight=tight) + + def auto_scale_xyz(self, X, Y, Z=None, had_data=None): + # This updates the bounding boxes as to keep a record as to what the + # minimum sized rectangular volume holds the data. + if np.shape(X) == np.shape(Y): + self.xy_dataLim.update_from_data_xy( + np.column_stack([np.ravel(X), np.ravel(Y)]), not had_data) + else: + self.xy_dataLim.update_from_data_x(X, not had_data) + self.xy_dataLim.update_from_data_y(Y, not had_data) + if Z is not None: + self.zz_dataLim.update_from_data_x(Z, not had_data) + # Let autoscale_view figure out how to use this data. + self.autoscale_view() + + def autoscale_view(self, tight=None, + scalex=True, scaley=True, scalez=True): + """ + Autoscale the view limits using the data limits. + + See `.Axes.autoscale_view` for full documentation. Because this + function applies to 3D Axes, it also takes a *scalez* argument. + """ + # This method looks at the rectangular volume (see above) + # of data and decides how to scale the view portal to fit it. + if tight is None: + _tight = self._tight + if not _tight: + # if image data only just use the datalim + for artist in self._children: + if isinstance(artist, mimage.AxesImage): + _tight = True + elif isinstance(artist, (mlines.Line2D, mpatches.Patch)): + _tight = False + break + else: + _tight = self._tight = bool(tight) + + if scalex and self.get_autoscalex_on(): + x0, x1 = self.xy_dataLim.intervalx + xlocator = self.xaxis.get_major_locator() + x0, x1 = xlocator.nonsingular(x0, x1) + if self._xmargin > 0: + delta = (x1 - x0) * self._xmargin + x0 -= delta + x1 += delta + if not _tight: + x0, x1 = xlocator.view_limits(x0, x1) + self.set_xbound(x0, x1, self._view_margin) + + if scaley and self.get_autoscaley_on(): + y0, y1 = self.xy_dataLim.intervaly + ylocator = self.yaxis.get_major_locator() + y0, y1 = ylocator.nonsingular(y0, y1) + if self._ymargin > 0: + delta = (y1 - y0) * self._ymargin + y0 -= delta + y1 += delta + if not _tight: + y0, y1 = ylocator.view_limits(y0, y1) + self.set_ybound(y0, y1, self._view_margin) + + if scalez and self.get_autoscalez_on(): + z0, z1 = self.zz_dataLim.intervalx + zlocator = self.zaxis.get_major_locator() + z0, z1 = zlocator.nonsingular(z0, z1) + if self._zmargin > 0: + delta = (z1 - z0) * self._zmargin + z0 -= delta + z1 += delta + if not _tight: + z0, z1 = zlocator.view_limits(z0, z1) + self.set_zbound(z0, z1, self._view_margin) + + def get_w_lims(self): + """Get 3D world limits.""" + minx, maxx = self.get_xlim3d() + miny, maxy = self.get_ylim3d() + minz, maxz = self.get_zlim3d() + return minx, maxx, miny, maxy, minz, maxz + + def _set_bound3d(self, get_bound, set_lim, axis_inverted, + lower=None, upper=None, view_margin=None): + """ + Set 3D axis bounds. + """ + if upper is None and np.iterable(lower): + lower, upper = lower + + old_lower, old_upper = get_bound() + if lower is None: + lower = old_lower + if upper is None: + upper = old_upper + + set_lim(sorted((lower, upper), reverse=bool(axis_inverted())), + auto=None, view_margin=view_margin) + + def set_xbound(self, lower=None, upper=None, view_margin=None): + """ + Set the lower and upper numerical bounds of the x-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscalex_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + view_margin : float or None + The margin to apply to the bounds. If *None*, the margin is handled + by `.set_xlim`. + + See Also + -------- + get_xbound + get_xlim, set_xlim + invert_xaxis, xaxis_inverted + """ + self._set_bound3d(self.get_xbound, self.set_xlim, self.xaxis_inverted, + lower, upper, view_margin) + + def set_ybound(self, lower=None, upper=None, view_margin=None): + """ + Set the lower and upper numerical bounds of the y-axis. + + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscaley_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + view_margin : float or None + The margin to apply to the bounds. If *None*, the margin is handled + by `.set_ylim`. + + See Also + -------- + get_ybound + get_ylim, set_ylim + invert_yaxis, yaxis_inverted + """ + self._set_bound3d(self.get_ybound, self.set_ylim, self.yaxis_inverted, + lower, upper, view_margin) + + def set_zbound(self, lower=None, upper=None, view_margin=None): + """ + Set the lower and upper numerical bounds of the z-axis. + This method will honor axis inversion regardless of parameter order. + It will not change the autoscaling setting (`.get_autoscaley_on()`). + + Parameters + ---------- + lower, upper : float or None + The lower and upper bounds. If *None*, the respective axis bound + is not modified. + view_margin : float or None + The margin to apply to the bounds. If *None*, the margin is handled + by `.set_zlim`. + + See Also + -------- + get_zbound + get_zlim, set_zlim + invert_zaxis, zaxis_inverted + """ + self._set_bound3d(self.get_zbound, self.set_zlim, self.zaxis_inverted, + lower, upper, view_margin) + + def _set_lim3d(self, axis, lower=None, upper=None, *, emit=True, + auto=False, view_margin=None, axmin=None, axmax=None): + """ + Set 3D axis limits. + """ + if upper is None: + if np.iterable(lower): + lower, upper = lower + elif axmax is None: + upper = axis.get_view_interval()[1] + if lower is None and axmin is None: + lower = axis.get_view_interval()[0] + if axmin is not None: + if lower is not None: + raise TypeError("Cannot pass both 'lower' and 'min'") + lower = axmin + if axmax is not None: + if upper is not None: + raise TypeError("Cannot pass both 'upper' and 'max'") + upper = axmax + if np.isinf(lower) or np.isinf(upper): + raise ValueError(f"Axis limits {lower}, {upper} cannot be infinite") + if view_margin is None: + if mpl.rcParams['axes3d.automargin']: + view_margin = self._view_margin + else: + view_margin = 0 + delta = (upper - lower) * view_margin + lower -= delta + upper += delta + return axis._set_lim(lower, upper, emit=emit, auto=auto) + + def set_xlim(self, left=None, right=None, *, emit=True, auto=False, + view_margin=None, xmin=None, xmax=None): + """ + Set the 3D x-axis view limits. + + Parameters + ---------- + left : float, optional + The left xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + The left and right xlims may also be passed as the tuple + (*left*, *right*) as the first positional argument (or as + the *left* keyword argument). + + .. ACCEPTS: (left: float, right: float) + + right : float, optional + The right xlim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the x-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + view_margin : float, optional + The additional margin to apply to the limits. + + xmin, xmax : float, optional + They are equivalent to left and right respectively, and it is an + error to pass both *xmin* and *left* or *xmax* and *right*. + + Returns + ------- + left, right : (float, float) + The new x-axis limits in data coordinates. + + See Also + -------- + get_xlim + set_xbound, get_xbound + invert_xaxis, xaxis_inverted + + Notes + ----- + The *left* value may be greater than the *right* value, in which + case the x-axis values will decrease from *left* to *right*. + + Examples + -------- + >>> set_xlim(left, right) + >>> set_xlim((left, right)) + >>> left, right = set_xlim(left, right) + + One limit may be left unchanged. + + >>> set_xlim(right=right_lim) + + Limits may be passed in reverse order to flip the direction of + the x-axis. For example, suppose ``x`` represents depth of the + ocean in m. The x-axis limits might be set like the following + so 5000 m depth is at the left of the plot and the surface, + 0 m, is at the right. + + >>> set_xlim(5000, 0) + """ + return self._set_lim3d(self.xaxis, left, right, emit=emit, auto=auto, + view_margin=view_margin, axmin=xmin, axmax=xmax) + + def set_ylim(self, bottom=None, top=None, *, emit=True, auto=False, + view_margin=None, ymin=None, ymax=None): + """ + Set the 3D y-axis view limits. + + Parameters + ---------- + bottom : float, optional + The bottom ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + The bottom and top ylims may also be passed as the tuple + (*bottom*, *top*) as the first positional argument (or as + the *bottom* keyword argument). + + .. ACCEPTS: (bottom: float, top: float) + + top : float, optional + The top ylim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the y-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + view_margin : float, optional + The additional margin to apply to the limits. + + ymin, ymax : float, optional + They are equivalent to bottom and top respectively, and it is an + error to pass both *ymin* and *bottom* or *ymax* and *top*. + + Returns + ------- + bottom, top : (float, float) + The new y-axis limits in data coordinates. + + See Also + -------- + get_ylim + set_ybound, get_ybound + invert_yaxis, yaxis_inverted + + Notes + ----- + The *bottom* value may be greater than the *top* value, in which + case the y-axis values will decrease from *bottom* to *top*. + + Examples + -------- + >>> set_ylim(bottom, top) + >>> set_ylim((bottom, top)) + >>> bottom, top = set_ylim(bottom, top) + + One limit may be left unchanged. + + >>> set_ylim(top=top_lim) + + Limits may be passed in reverse order to flip the direction of + the y-axis. For example, suppose ``y`` represents depth of the + ocean in m. The y-axis limits might be set like the following + so 5000 m depth is at the bottom of the plot and the surface, + 0 m, is at the top. + + >>> set_ylim(5000, 0) + """ + return self._set_lim3d(self.yaxis, bottom, top, emit=emit, auto=auto, + view_margin=view_margin, axmin=ymin, axmax=ymax) + + def set_zlim(self, bottom=None, top=None, *, emit=True, auto=False, + view_margin=None, zmin=None, zmax=None): + """ + Set the 3D z-axis view limits. + + Parameters + ---------- + bottom : float, optional + The bottom zlim in data coordinates. Passing *None* leaves the + limit unchanged. + + The bottom and top zlims may also be passed as the tuple + (*bottom*, *top*) as the first positional argument (or as + the *bottom* keyword argument). + + .. ACCEPTS: (bottom: float, top: float) + + top : float, optional + The top zlim in data coordinates. Passing *None* leaves the + limit unchanged. + + emit : bool, default: True + Whether to notify observers of limit change. + + auto : bool or None, default: False + Whether to turn on autoscaling of the z-axis. *True* turns on, + *False* turns off, *None* leaves unchanged. + + view_margin : float, optional + The additional margin to apply to the limits. + + zmin, zmax : float, optional + They are equivalent to bottom and top respectively, and it is an + error to pass both *zmin* and *bottom* or *zmax* and *top*. + + Returns + ------- + bottom, top : (float, float) + The new z-axis limits in data coordinates. + + See Also + -------- + get_zlim + set_zbound, get_zbound + invert_zaxis, zaxis_inverted + + Notes + ----- + The *bottom* value may be greater than the *top* value, in which + case the z-axis values will decrease from *bottom* to *top*. + + Examples + -------- + >>> set_zlim(bottom, top) + >>> set_zlim((bottom, top)) + >>> bottom, top = set_zlim(bottom, top) + + One limit may be left unchanged. + + >>> set_zlim(top=top_lim) + + Limits may be passed in reverse order to flip the direction of + the z-axis. For example, suppose ``z`` represents depth of the + ocean in m. The z-axis limits might be set like the following + so 5000 m depth is at the bottom of the plot and the surface, + 0 m, is at the top. + + >>> set_zlim(5000, 0) + """ + return self._set_lim3d(self.zaxis, bottom, top, emit=emit, auto=auto, + view_margin=view_margin, axmin=zmin, axmax=zmax) + + set_xlim3d = set_xlim + set_ylim3d = set_ylim + set_zlim3d = set_zlim + + def get_xlim(self): + # docstring inherited + return tuple(self.xy_viewLim.intervalx) + + def get_ylim(self): + # docstring inherited + return tuple(self.xy_viewLim.intervaly) + + def get_zlim(self): + """ + Return the 3D z-axis view limits. + + Returns + ------- + left, right : (float, float) + The current z-axis limits in data coordinates. + + See Also + -------- + set_zlim + set_zbound, get_zbound + invert_zaxis, zaxis_inverted + + Notes + ----- + The z-axis may be inverted, in which case the *left* value will + be greater than the *right* value. + """ + return tuple(self.zz_viewLim.intervalx) + + get_zscale = _axis_method_wrapper("zaxis", "get_scale") + + # Redefine all three methods to overwrite their docstrings. + set_xscale = _axis_method_wrapper("xaxis", "_set_axes_scale") + set_yscale = _axis_method_wrapper("yaxis", "_set_axes_scale") + set_zscale = _axis_method_wrapper("zaxis", "_set_axes_scale") + set_xscale.__doc__, set_yscale.__doc__, set_zscale.__doc__ = map( + """ + Set the {}-axis scale. + + Parameters + ---------- + value : {{"linear"}} + The axis scale type to apply. 3D Axes currently only support + linear scales; other scales yield nonsensical results. + + **kwargs + Keyword arguments are nominally forwarded to the scale class, but + none of them is applicable for linear scales. + """.format, + ["x", "y", "z"]) + + get_zticks = _axis_method_wrapper("zaxis", "get_ticklocs") + set_zticks = _axis_method_wrapper("zaxis", "set_ticks") + get_zmajorticklabels = _axis_method_wrapper("zaxis", "get_majorticklabels") + get_zminorticklabels = _axis_method_wrapper("zaxis", "get_minorticklabels") + get_zticklabels = _axis_method_wrapper("zaxis", "get_ticklabels") + set_zticklabels = _axis_method_wrapper( + "zaxis", "set_ticklabels", + doc_sub={"Axis.set_ticks": "Axes3D.set_zticks"}) + + zaxis_date = _axis_method_wrapper("zaxis", "axis_date") + if zaxis_date.__doc__: + zaxis_date.__doc__ += textwrap.dedent(""" + + Notes + ----- + This function is merely provided for completeness, but 3D Axes do not + support dates for ticks, and so this may not work as expected. + """) + + def clabel(self, *args, **kwargs): + """Currently not implemented for 3D Axes, and returns *None*.""" + return None + + def view_init(self, elev=None, azim=None, roll=None, vertical_axis="z", + share=False): + """ + Set the elevation and azimuth of the Axes in degrees (not radians). + + This can be used to rotate the Axes programmatically. + + To look normal to the primary planes, the following elevation and + azimuth angles can be used. A roll angle of 0, 90, 180, or 270 deg + will rotate these views while keeping the axes at right angles. + + ========== ==== ==== + view plane elev azim + ========== ==== ==== + XY 90 -90 + XZ 0 -90 + YZ 0 0 + -XY -90 90 + -XZ 0 90 + -YZ 0 180 + ========== ==== ==== + + Parameters + ---------- + elev : float, default: None + The elevation angle in degrees rotates the camera above the plane + pierced by the vertical axis, with a positive angle corresponding + to a location above that plane. For example, with the default + vertical axis of 'z', the elevation defines the angle of the camera + location above the x-y plane. + If None, then the initial value as specified in the `Axes3D` + constructor is used. + azim : float, default: None + The azimuthal angle in degrees rotates the camera about the + vertical axis, with a positive angle corresponding to a + right-handed rotation. For example, with the default vertical axis + of 'z', a positive azimuth rotates the camera about the origin from + its location along the +x axis towards the +y axis. + If None, then the initial value as specified in the `Axes3D` + constructor is used. + roll : float, default: None + The roll angle in degrees rotates the camera about the viewing + axis. A positive angle spins the camera clockwise, causing the + scene to rotate counter-clockwise. + If None, then the initial value as specified in the `Axes3D` + constructor is used. + vertical_axis : {"z", "x", "y"}, default: "z" + The axis to align vertically. *azim* rotates about this axis. + share : bool, default: False + If ``True``, apply the settings to all Axes with shared views. + """ + + self._dist = 10 # The camera distance from origin. Behaves like zoom + + if elev is None: + elev = self.initial_elev + if azim is None: + azim = self.initial_azim + if roll is None: + roll = self.initial_roll + vertical_axis = _api.check_getitem( + {name: idx for idx, name in enumerate(self._axis_names)}, + vertical_axis=vertical_axis, + ) + + if share: + axes = {sibling for sibling + in self._shared_axes['view'].get_siblings(self)} + else: + axes = [self] + + for ax in axes: + ax.elev = elev + ax.azim = azim + ax.roll = roll + ax._vertical_axis = vertical_axis + + def set_proj_type(self, proj_type, focal_length=None): + """ + Set the projection type. + + Parameters + ---------- + proj_type : {'persp', 'ortho'} + The projection type. + focal_length : float, default: None + For a projection type of 'persp', the focal length of the virtual + camera. Must be > 0. If None, defaults to 1. + The focal length can be computed from a desired Field Of View via + the equation: focal_length = 1/tan(FOV/2) + """ + _api.check_in_list(['persp', 'ortho'], proj_type=proj_type) + if proj_type == 'persp': + if focal_length is None: + focal_length = 1 + elif focal_length <= 0: + raise ValueError(f"focal_length = {focal_length} must be " + "greater than 0") + self._focal_length = focal_length + else: # 'ortho': + if focal_length not in (None, np.inf): + raise ValueError(f"focal_length = {focal_length} must be " + f"None for proj_type = {proj_type}") + self._focal_length = np.inf + + def _roll_to_vertical( + self, arr: "np.typing.ArrayLike", reverse: bool = False + ) -> np.ndarray: + """ + Roll arrays to match the different vertical axis. + + Parameters + ---------- + arr : ArrayLike + Array to roll. + reverse : bool, default: False + Reverse the direction of the roll. + """ + if reverse: + return np.roll(arr, (self._vertical_axis - 2) * -1) + else: + return np.roll(arr, (self._vertical_axis - 2)) + + def get_proj(self): + """Create the projection matrix from the current viewing position.""" + + # Transform to uniform world coordinates 0-1, 0-1, 0-1 + box_aspect = self._roll_to_vertical(self._box_aspect) + worldM = proj3d.world_transformation( + *self.get_xlim3d(), + *self.get_ylim3d(), + *self.get_zlim3d(), + pb_aspect=box_aspect, + ) + + # Look into the middle of the world coordinates: + R = 0.5 * box_aspect + + # elev: elevation angle in the z plane. + # azim: azimuth angle in the xy plane. + # Coordinates for a point that rotates around the box of data. + # p0, p1 corresponds to rotating the box only around the vertical axis. + # p2 corresponds to rotating the box only around the horizontal axis. + elev_rad = np.deg2rad(self.elev) + azim_rad = np.deg2rad(self.azim) + p0 = np.cos(elev_rad) * np.cos(azim_rad) + p1 = np.cos(elev_rad) * np.sin(azim_rad) + p2 = np.sin(elev_rad) + + # When changing vertical axis the coordinates changes as well. + # Roll the values to get the same behaviour as the default: + ps = self._roll_to_vertical([p0, p1, p2]) + + # The coordinates for the eye viewing point. The eye is looking + # towards the middle of the box of data from a distance: + eye = R + self._dist * ps + + # Calculate the viewing axes for the eye position + u, v, w = self._calc_view_axes(eye) + self._view_u = u # _view_u is towards the right of the screen + self._view_v = v # _view_v is towards the top of the screen + self._view_w = w # _view_w is out of the screen + + # Generate the view and projection transformation matrices + if self._focal_length == np.inf: + # Orthographic projection + viewM = proj3d._view_transformation_uvw(u, v, w, eye) + projM = proj3d._ortho_transformation(-self._dist, self._dist) + else: + # Perspective projection + # Scale the eye dist to compensate for the focal length zoom effect + eye_focal = R + self._dist * ps * self._focal_length + viewM = proj3d._view_transformation_uvw(u, v, w, eye_focal) + projM = proj3d._persp_transformation(-self._dist, + self._dist, + self._focal_length) + + # Combine all the transformation matrices to get the final projection + M0 = np.dot(viewM, worldM) + M = np.dot(projM, M0) + return M + + def mouse_init(self, rotate_btn=1, pan_btn=2, zoom_btn=3): + """ + Set the mouse buttons for 3D rotation and zooming. + + Parameters + ---------- + rotate_btn : int or list of int, default: 1 + The mouse button or buttons to use for 3D rotation of the Axes. + pan_btn : int or list of int, default: 2 + The mouse button or buttons to use to pan the 3D Axes. + zoom_btn : int or list of int, default: 3 + The mouse button or buttons to use to zoom the 3D Axes. + """ + self.button_pressed = None + # coerce scalars into array-like, then convert into + # a regular list to avoid comparisons against None + # which breaks in recent versions of numpy. + self._rotate_btn = np.atleast_1d(rotate_btn).tolist() + self._pan_btn = np.atleast_1d(pan_btn).tolist() + self._zoom_btn = np.atleast_1d(zoom_btn).tolist() + + def disable_mouse_rotation(self): + """Disable mouse buttons for 3D rotation, panning, and zooming.""" + self.mouse_init(rotate_btn=[], pan_btn=[], zoom_btn=[]) + + def can_zoom(self): + # doc-string inherited + return True + + def can_pan(self): + # doc-string inherited + return True + + def sharez(self, other): + """ + Share the z-axis with *other*. + + This is equivalent to passing ``sharez=other`` when constructing the + Axes, and cannot be used if the z-axis is already being shared with + another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(Axes3D, other=other) + if self._sharez is not None and other is not self._sharez: + raise ValueError("z-axis is already shared") + self._shared_axes["z"].join(self, other) + self._sharez = other + self.zaxis.major = other.zaxis.major # Ticker instances holding + self.zaxis.minor = other.zaxis.minor # locator and formatter. + z0, z1 = other.get_zlim() + self.set_zlim(z0, z1, emit=False, auto=other.get_autoscalez_on()) + self.zaxis._scale = other.zaxis._scale + + def shareview(self, other): + """ + Share the view angles with *other*. + + This is equivalent to passing ``shareview=other`` when constructing the + Axes, and cannot be used if the view angles are already being shared + with another Axes. Note that it is not possible to unshare axes. + """ + _api.check_isinstance(Axes3D, other=other) + if self._shareview is not None and other is not self._shareview: + raise ValueError("view angles are already shared") + self._shared_axes["view"].join(self, other) + self._shareview = other + vertical_axis = self._axis_names[other._vertical_axis] + self.view_init(elev=other.elev, azim=other.azim, roll=other.roll, + vertical_axis=vertical_axis, share=True) + + def clear(self): + # docstring inherited. + super().clear() + if self._focal_length == np.inf: + self._zmargin = mpl.rcParams['axes.zmargin'] + else: + self._zmargin = 0. + + xymargin = 0.05 * 10/11 # match mpl3.8 appearance + self.xy_dataLim = Bbox([[xymargin, xymargin], + [1 - xymargin, 1 - xymargin]]) + # z-limits are encoded in the x-component of the Bbox, y is un-used + self.zz_dataLim = Bbox.unit() + self._view_margin = 1/48 # default value to match mpl3.8 + self.autoscale_view() + + self.grid(mpl.rcParams['axes3d.grid']) + + def _button_press(self, event): + if event.inaxes == self: + self.button_pressed = event.button + self._sx, self._sy = event.xdata, event.ydata + toolbar = self.get_figure(root=True).canvas.toolbar + if toolbar and toolbar._nav_stack() is None: + toolbar.push_current() + if toolbar: + toolbar.set_message(toolbar._mouse_event_to_message(event)) + + def _button_release(self, event): + self.button_pressed = None + toolbar = self.get_figure(root=True).canvas.toolbar + # backend_bases.release_zoom and backend_bases.release_pan call + # push_current, so check the navigation mode so we don't call it twice + if toolbar and self.get_navigate_mode() is None: + toolbar.push_current() + if toolbar: + toolbar.set_message(toolbar._mouse_event_to_message(event)) + + def _get_view(self): + # docstring inherited + return { + "xlim": self.get_xlim(), "autoscalex_on": self.get_autoscalex_on(), + "ylim": self.get_ylim(), "autoscaley_on": self.get_autoscaley_on(), + "zlim": self.get_zlim(), "autoscalez_on": self.get_autoscalez_on(), + }, (self.elev, self.azim, self.roll) + + def _set_view(self, view): + # docstring inherited + props, (elev, azim, roll) = view + self.set(**props) + self.elev = elev + self.azim = azim + self.roll = roll + + def format_zdata(self, z): + """ + Return *z* string formatted. This function will use the + :attr:`fmt_zdata` attribute if it is callable, else will fall + back on the zaxis major formatter + """ + try: + return self.fmt_zdata(z) + except (AttributeError, TypeError): + func = self.zaxis.get_major_formatter().format_data_short + val = func(z) + return val + + def format_coord(self, xv, yv, renderer=None): + """ + Return a string giving the current view rotation angles, or the x, y, z + coordinates of the point on the nearest axis pane underneath the mouse + cursor, depending on the mouse button pressed. + """ + coords = '' + + if self.button_pressed in self._rotate_btn: + # ignore xv and yv and display angles instead + coords = self._rotation_coords() + + elif self.M is not None: + coords = self._location_coords(xv, yv, renderer) + + return coords + + def _rotation_coords(self): + """ + Return the rotation angles as a string. + """ + norm_elev = art3d._norm_angle(self.elev) + norm_azim = art3d._norm_angle(self.azim) + norm_roll = art3d._norm_angle(self.roll) + coords = (f"elevation={norm_elev:.0f}\N{DEGREE SIGN}, " + f"azimuth={norm_azim:.0f}\N{DEGREE SIGN}, " + f"roll={norm_roll:.0f}\N{DEGREE SIGN}" + ).replace("-", "\N{MINUS SIGN}") + return coords + + def _location_coords(self, xv, yv, renderer): + """ + Return the location on the axis pane underneath the cursor as a string. + """ + p1, pane_idx = self._calc_coord(xv, yv, renderer) + xs = self.format_xdata(p1[0]) + ys = self.format_ydata(p1[1]) + zs = self.format_zdata(p1[2]) + if pane_idx == 0: + coords = f'x pane={xs}, y={ys}, z={zs}' + elif pane_idx == 1: + coords = f'x={xs}, y pane={ys}, z={zs}' + elif pane_idx == 2: + coords = f'x={xs}, y={ys}, z pane={zs}' + return coords + + def _get_camera_loc(self): + """ + Returns the current camera location in data coordinates. + """ + cx, cy, cz, dx, dy, dz = self._get_w_centers_ranges() + c = np.array([cx, cy, cz]) + r = np.array([dx, dy, dz]) + + if self._focal_length == np.inf: # orthographic projection + focal_length = 1e9 # large enough to be effectively infinite + else: # perspective projection + focal_length = self._focal_length + eye = c + self._view_w * self._dist * r / self._box_aspect * focal_length + return eye + + def _calc_coord(self, xv, yv, renderer=None): + """ + Given the 2D view coordinates, find the point on the nearest axis pane + that lies directly below those coordinates. Returns a 3D point in data + coordinates. + """ + if self._focal_length == np.inf: # orthographic projection + zv = 1 + else: # perspective projection + zv = -1 / self._focal_length + + # Convert point on view plane to data coordinates + p1 = np.array(proj3d.inv_transform(xv, yv, zv, self.invM)).ravel() + + # Get the vector from the camera to the point on the view plane + vec = self._get_camera_loc() - p1 + + # Get the pane locations for each of the axes + pane_locs = [] + for axis in self._axis_map.values(): + xys, loc = axis.active_pane() + pane_locs.append(loc) + + # Find the distance to the nearest pane by projecting the view vector + scales = np.zeros(3) + for i in range(3): + if vec[i] == 0: + scales[i] = np.inf + else: + scales[i] = (p1[i] - pane_locs[i]) / vec[i] + pane_idx = np.argmin(abs(scales)) + scale = scales[pane_idx] + + # Calculate the point on the closest pane + p2 = p1 - scale*vec + return p2, pane_idx + + def _arcball(self, x: float, y: float) -> np.ndarray: + """ + Convert a point (x, y) to a point on a virtual trackball. + + This is Ken Shoemake's arcball (a sphere), modified + to soften the abrupt edge (optionally). + See: Ken Shoemake, "ARCBALL: A user interface for specifying + three-dimensional rotation using a mouse." in + Proceedings of Graphics Interface '92, 1992, pp. 151-156, + https://doi.org/10.20380/GI1992.18 + The smoothing of the edge is inspired by Gavin Bell's arcball + (a sphere combined with a hyperbola), but here, the sphere + is combined with a section of a cylinder, so it has finite support. + """ + s = mpl.rcParams['axes3d.trackballsize'] / 2 + b = mpl.rcParams['axes3d.trackballborder'] / s + x /= s + y /= s + r2 = x*x + y*y + r = np.sqrt(r2) + ra = 1 + b + a = b * (1 + b/2) + ri = 2/(ra + 1/ra) + if r < ri: + p = np.array([np.sqrt(1 - r2), x, y]) + elif r < ra: + dr = ra - r + p = np.array([a - np.sqrt((a + dr) * (a - dr)), x, y]) + p /= np.linalg.norm(p) + else: + p = np.array([0, x/r, y/r]) + return p + + def _on_move(self, event): + """ + Mouse moving. + + By default, button-1 rotates, button-2 pans, and button-3 zooms; + these buttons can be modified via `mouse_init`. + """ + + if not self.button_pressed: + return + + if self.get_navigate_mode() is not None: + # we don't want to rotate if we are zooming/panning + # from the toolbar + return + + if self.M is None: + return + + x, y = event.xdata, event.ydata + # In case the mouse is out of bounds. + if x is None or event.inaxes != self: + return + + dx, dy = x - self._sx, y - self._sy + w = self._pseudo_w + h = self._pseudo_h + + # Rotation + if self.button_pressed in self._rotate_btn: + # rotate viewing point + # get the x and y pixel coords + if dx == 0 and dy == 0: + return + + style = mpl.rcParams['axes3d.mouserotationstyle'] + if style == 'azel': + roll = np.deg2rad(self.roll) + delev = -(dy/h)*180*np.cos(roll) + (dx/w)*180*np.sin(roll) + dazim = -(dy/h)*180*np.sin(roll) - (dx/w)*180*np.cos(roll) + elev = self.elev + delev + azim = self.azim + dazim + roll = self.roll + else: + q = _Quaternion.from_cardan_angles( + *np.deg2rad((self.elev, self.azim, self.roll))) + + if style == 'trackball': + k = np.array([0, -dy/h, dx/w]) + nk = np.linalg.norm(k) + th = nk / mpl.rcParams['axes3d.trackballsize'] + dq = _Quaternion(np.cos(th), k*np.sin(th)/nk) + else: # 'sphere', 'arcball' + current_vec = self._arcball(self._sx/w, self._sy/h) + new_vec = self._arcball(x/w, y/h) + if style == 'sphere': + dq = _Quaternion.rotate_from_to(current_vec, new_vec) + else: # 'arcball' + dq = _Quaternion(0, new_vec) * _Quaternion(0, -current_vec) + + q = dq * q + elev, azim, roll = np.rad2deg(q.as_cardan_angles()) + + # update view + vertical_axis = self._axis_names[self._vertical_axis] + self.view_init( + elev=elev, + azim=azim, + roll=roll, + vertical_axis=vertical_axis, + share=True, + ) + self.stale = True + + # Pan + elif self.button_pressed in self._pan_btn: + # Start the pan event with pixel coordinates + px, py = self.transData.transform([self._sx, self._sy]) + self.start_pan(px, py, 2) + # pan view (takes pixel coordinate input) + self.drag_pan(2, None, event.x, event.y) + self.end_pan() + + # Zoom + elif self.button_pressed in self._zoom_btn: + # zoom view (dragging down zooms in) + scale = h/(h - dy) + self._scale_axis_limits(scale, scale, scale) + + # Store the event coordinates for the next time through. + self._sx, self._sy = x, y + # Always request a draw update at the end of interaction + self.get_figure(root=True).canvas.draw_idle() + + def drag_pan(self, button, key, x, y): + # docstring inherited + + # Get the coordinates from the move event + p = self._pan_start + (xdata, ydata), (xdata_start, ydata_start) = p.trans_inverse.transform( + [(x, y), (p.x, p.y)]) + self._sx, self._sy = xdata, ydata + # Calling start_pan() to set the x/y of this event as the starting + # move location for the next event + self.start_pan(x, y, button) + du, dv = xdata - xdata_start, ydata - ydata_start + dw = 0 + if key == 'x': + dv = 0 + elif key == 'y': + du = 0 + if du == 0 and dv == 0: + return + + # Transform the pan from the view axes to the data axes + R = np.array([self._view_u, self._view_v, self._view_w]) + R = -R / self._box_aspect * self._dist + duvw_projected = R.T @ np.array([du, dv, dw]) + + # Calculate pan distance + minx, maxx, miny, maxy, minz, maxz = self.get_w_lims() + dx = (maxx - minx) * duvw_projected[0] + dy = (maxy - miny) * duvw_projected[1] + dz = (maxz - minz) * duvw_projected[2] + + # Set the new axis limits + self.set_xlim3d(minx + dx, maxx + dx, auto=None) + self.set_ylim3d(miny + dy, maxy + dy, auto=None) + self.set_zlim3d(minz + dz, maxz + dz, auto=None) + + def _calc_view_axes(self, eye): + """ + Get the unit vectors for the viewing axes in data coordinates. + `u` is towards the right of the screen + `v` is towards the top of the screen + `w` is out of the screen + """ + elev_rad = np.deg2rad(art3d._norm_angle(self.elev)) + roll_rad = np.deg2rad(art3d._norm_angle(self.roll)) + + # Look into the middle of the world coordinates + R = 0.5 * self._roll_to_vertical(self._box_aspect) + + # Define which axis should be vertical. A negative value + # indicates the plot is upside down and therefore the values + # have been reversed: + V = np.zeros(3) + V[self._vertical_axis] = -1 if abs(elev_rad) > np.pi/2 else 1 + + u, v, w = proj3d._view_axes(eye, R, V, roll_rad) + return u, v, w + + def _set_view_from_bbox(self, bbox, direction='in', + mode=None, twinx=False, twiny=False): + """ + Zoom in or out of the bounding box. + + Will center the view in the center of the bounding box, and zoom by + the ratio of the size of the bounding box to the size of the Axes3D. + """ + (start_x, start_y, stop_x, stop_y) = bbox + if mode == 'x': + start_y = self.bbox.min[1] + stop_y = self.bbox.max[1] + elif mode == 'y': + start_x = self.bbox.min[0] + stop_x = self.bbox.max[0] + + # Clip to bounding box limits + start_x, stop_x = np.clip(sorted([start_x, stop_x]), + self.bbox.min[0], self.bbox.max[0]) + start_y, stop_y = np.clip(sorted([start_y, stop_y]), + self.bbox.min[1], self.bbox.max[1]) + + # Move the center of the view to the center of the bbox + zoom_center_x = (start_x + stop_x)/2 + zoom_center_y = (start_y + stop_y)/2 + + ax_center_x = (self.bbox.max[0] + self.bbox.min[0])/2 + ax_center_y = (self.bbox.max[1] + self.bbox.min[1])/2 + + self.start_pan(zoom_center_x, zoom_center_y, 2) + self.drag_pan(2, None, ax_center_x, ax_center_y) + self.end_pan() + + # Calculate zoom level + dx = abs(start_x - stop_x) + dy = abs(start_y - stop_y) + scale_u = dx / (self.bbox.max[0] - self.bbox.min[0]) + scale_v = dy / (self.bbox.max[1] - self.bbox.min[1]) + + # Keep aspect ratios equal + scale = max(scale_u, scale_v) + + # Zoom out + if direction == 'out': + scale = 1 / scale + + self._zoom_data_limits(scale, scale, scale) + + def _zoom_data_limits(self, scale_u, scale_v, scale_w): + """ + Zoom in or out of a 3D plot. + + Will scale the data limits by the scale factors. These will be + transformed to the x, y, z data axes based on the current view angles. + A scale factor > 1 zooms out and a scale factor < 1 zooms in. + + For an Axes that has had its aspect ratio set to 'equal', 'equalxy', + 'equalyz', or 'equalxz', the relevant axes are constrained to zoom + equally. + + Parameters + ---------- + scale_u : float + Scale factor for the u view axis (view screen horizontal). + scale_v : float + Scale factor for the v view axis (view screen vertical). + scale_w : float + Scale factor for the w view axis (view screen depth). + """ + scale = np.array([scale_u, scale_v, scale_w]) + + # Only perform frame conversion if unequal scale factors + if not np.allclose(scale, scale_u): + # Convert the scale factors from the view frame to the data frame + R = np.array([self._view_u, self._view_v, self._view_w]) + S = scale * np.eye(3) + scale = np.linalg.norm(R.T @ S, axis=1) + + # Set the constrained scale factors to the factor closest to 1 + if self._aspect in ('equal', 'equalxy', 'equalxz', 'equalyz'): + ax_idxs = self._equal_aspect_axis_indices(self._aspect) + min_ax_idxs = np.argmin(np.abs(scale[ax_idxs] - 1)) + scale[ax_idxs] = scale[ax_idxs][min_ax_idxs] + + self._scale_axis_limits(scale[0], scale[1], scale[2]) + + def _scale_axis_limits(self, scale_x, scale_y, scale_z): + """ + Keeping the center of the x, y, and z data axes fixed, scale their + limits by scale factors. A scale factor > 1 zooms out and a scale + factor < 1 zooms in. + + Parameters + ---------- + scale_x : float + Scale factor for the x data axis. + scale_y : float + Scale factor for the y data axis. + scale_z : float + Scale factor for the z data axis. + """ + # Get the axis centers and ranges + cx, cy, cz, dx, dy, dz = self._get_w_centers_ranges() + + # Set the scaled axis limits + self.set_xlim3d(cx - dx*scale_x/2, cx + dx*scale_x/2, auto=None) + self.set_ylim3d(cy - dy*scale_y/2, cy + dy*scale_y/2, auto=None) + self.set_zlim3d(cz - dz*scale_z/2, cz + dz*scale_z/2, auto=None) + + def _get_w_centers_ranges(self): + """Get 3D world centers and axis ranges.""" + # Calculate center of axis limits + minx, maxx, miny, maxy, minz, maxz = self.get_w_lims() + cx = (maxx + minx)/2 + cy = (maxy + miny)/2 + cz = (maxz + minz)/2 + + # Calculate range of axis limits + dx = (maxx - minx) + dy = (maxy - miny) + dz = (maxz - minz) + return cx, cy, cz, dx, dy, dz + + def set_zlabel(self, zlabel, fontdict=None, labelpad=None, **kwargs): + """ + Set zlabel. See doc for `.set_ylabel` for description. + """ + if labelpad is not None: + self.zaxis.labelpad = labelpad + return self.zaxis.set_label_text(zlabel, fontdict, **kwargs) + + def get_zlabel(self): + """ + Get the z-label text string. + """ + label = self.zaxis.label + return label.get_text() + + # Axes rectangle characteristics + + # The frame_on methods are not available for 3D axes. + # Python will raise a TypeError if they are called. + get_frame_on = None + set_frame_on = None + + def grid(self, visible=True, **kwargs): + """ + Set / unset 3D grid. + + .. note:: + + Currently, this function does not behave the same as + `.axes.Axes.grid`, but it is intended to eventually support that + behavior. + """ + # TODO: Operate on each axes separately + if len(kwargs): + visible = True + self._draw_grid = visible + self.stale = True + + def tick_params(self, axis='both', **kwargs): + """ + Convenience method for changing the appearance of ticks and + tick labels. + + See `.Axes.tick_params` for full documentation. Because this function + applies to 3D Axes, *axis* can also be set to 'z', and setting *axis* + to 'both' autoscales all three axes. + + Also, because of how Axes3D objects are drawn very differently + from regular 2D Axes, some of these settings may have + ambiguous meaning. For simplicity, the 'z' axis will + accept settings as if it was like the 'y' axis. + + .. note:: + Axes3D currently ignores some of these settings. + """ + _api.check_in_list(['x', 'y', 'z', 'both'], axis=axis) + if axis in ['x', 'y', 'both']: + super().tick_params(axis, **kwargs) + if axis in ['z', 'both']: + zkw = dict(kwargs) + zkw.pop('top', None) + zkw.pop('bottom', None) + zkw.pop('labeltop', None) + zkw.pop('labelbottom', None) + self.zaxis.set_tick_params(**zkw) + + # data limits, ticks, tick labels, and formatting + + def invert_zaxis(self): + """ + Invert the z-axis. + + See Also + -------- + zaxis_inverted + get_zlim, set_zlim + get_zbound, set_zbound + """ + bottom, top = self.get_zlim() + self.set_zlim(top, bottom, auto=None) + + zaxis_inverted = _axis_method_wrapper("zaxis", "get_inverted") + + def get_zbound(self): + """ + Return the lower and upper z-axis bounds, in increasing order. + + See Also + -------- + set_zbound + get_zlim, set_zlim + invert_zaxis, zaxis_inverted + """ + lower, upper = self.get_zlim() + if lower < upper: + return lower, upper + else: + return upper, lower + + def text(self, x, y, z, s, zdir=None, *, axlim_clip=False, **kwargs): + """ + Add the text *s* to the 3D Axes at location *x*, *y*, *z* in data coordinates. + + Parameters + ---------- + x, y, z : float + The position to place the text. + s : str + The text. + zdir : {'x', 'y', 'z', 3-tuple}, optional + The direction to be used as the z-direction. Default: 'z'. + See `.get_dir_vector` for a description of the values. + axlim_clip : bool, default: False + Whether to hide text that is outside the axes view limits. + + .. versionadded:: 3.10 + **kwargs + Other arguments are forwarded to `matplotlib.axes.Axes.text`. + + Returns + ------- + `.Text3D` + The created `.Text3D` instance. + """ + text = super().text(x, y, s, **kwargs) + art3d.text_2d_to_3d(text, z, zdir, axlim_clip) + return text + + text3D = text + text2D = Axes.text + + def plot(self, xs, ys, *args, zdir='z', axlim_clip=False, **kwargs): + """ + Plot 2D or 3D data. + + Parameters + ---------- + xs : 1D array-like + x coordinates of vertices. + ys : 1D array-like + y coordinates of vertices. + zs : float or 1D array-like + z coordinates of vertices; either one for all points or one for + each point. + zdir : {'x', 'y', 'z'}, default: 'z' + When plotting 2D data, the direction to use as z. + axlim_clip : bool, default: False + Whether to hide data that is outside the axes view limits. + + .. versionadded:: 3.10 + **kwargs + Other arguments are forwarded to `matplotlib.axes.Axes.plot`. + """ + had_data = self.has_data() + + # `zs` can be passed positionally or as keyword; checking whether + # args[0] is a string matches the behavior of 2D `plot` (via + # `_process_plot_var_args`). + if args and not isinstance(args[0], str): + zs, *args = args + if 'zs' in kwargs: + raise TypeError("plot() for multiple values for argument 'zs'") + else: + zs = kwargs.pop('zs', 0) + + xs, ys, zs = cbook._broadcast_with_masks(xs, ys, zs) + + lines = super().plot(xs, ys, *args, **kwargs) + for line in lines: + art3d.line_2d_to_3d(line, zs=zs, zdir=zdir, axlim_clip=axlim_clip) + + xs, ys, zs = art3d.juggle_axes(xs, ys, zs, zdir) + self.auto_scale_xyz(xs, ys, zs, had_data) + return lines + + plot3D = plot + + def fill_between(self, x1, y1, z1, x2, y2, z2, *, + where=None, mode='auto', facecolors=None, shade=None, + axlim_clip=False, **kwargs): + """ + Fill the area between two 3D curves. + + The curves are defined by the points (*x1*, *y1*, *z1*) and + (*x2*, *y2*, *z2*). This creates one or multiple quadrangle + polygons that are filled. All points must be the same length N, or a + single value to be used for all points. + + Parameters + ---------- + x1, y1, z1 : float or 1D array-like + x, y, and z coordinates of vertices for 1st line. + + x2, y2, z2 : float or 1D array-like + x, y, and z coordinates of vertices for 2nd line. + + where : array of bool (length N), optional + Define *where* to exclude some regions from being filled. The + filled regions are defined by the coordinates ``pts[where]``, + for all x, y, and z pts. More precisely, fill between ``pts[i]`` + and ``pts[i+1]`` if ``where[i] and where[i+1]``. Note that this + definition implies that an isolated *True* value between two + *False* values in *where* will not result in filling. Both sides of + the *True* position remain unfilled due to the adjacent *False* + values. + + mode : {'quad', 'polygon', 'auto'}, default: 'auto' + The fill mode. One of: + + - 'quad': A separate quadrilateral polygon is created for each + pair of subsequent points in the two lines. + - 'polygon': The two lines are connected to form a single polygon. + This is faster and can render more cleanly for simple shapes + (e.g. for filling between two lines that lie within a plane). + - 'auto': If the points all lie on the same 3D plane, 'polygon' is + used. Otherwise, 'quad' is used. + + facecolors : list of :mpltype:`color`, default: None + Colors of each individual patch, or a single color to be used for + all patches. + + shade : bool, default: None + Whether to shade the facecolors. If *None*, then defaults to *True* + for 'quad' mode and *False* for 'polygon' mode. + + axlim_clip : bool, default: False + Whether to hide data that is outside the axes view limits. + + .. versionadded:: 3.10 + + **kwargs + All other keyword arguments are passed on to `.Poly3DCollection`. + + Returns + ------- + `.Poly3DCollection` + A `.Poly3DCollection` containing the plotted polygons. + + """ + _api.check_in_list(['auto', 'quad', 'polygon'], mode=mode) + + had_data = self.has_data() + x1, y1, z1, x2, y2, z2 = cbook._broadcast_with_masks(x1, y1, z1, x2, y2, z2) + + if facecolors is None: + facecolors = [self._get_patches_for_fill.get_next_color()] + facecolors = list(mcolors.to_rgba_array(facecolors)) + + if where is None: + where = True + else: + where = np.asarray(where, dtype=bool) + if where.size != x1.size: + raise ValueError(f"where size ({where.size}) does not match " + f"size ({x1.size})") + where = where & ~np.isnan(x1) # NaNs were broadcast in _broadcast_with_masks + + if mode == 'auto': + if art3d._all_points_on_plane(np.concatenate((x1[where], x2[where])), + np.concatenate((y1[where], y2[where])), + np.concatenate((z1[where], z2[where])), + atol=1e-12): + mode = 'polygon' + else: + mode = 'quad' + + if shade is None: + if mode == 'quad': + shade = True + else: + shade = False + + polys = [] + for idx0, idx1 in cbook.contiguous_regions(where): + x1i = x1[idx0:idx1] + y1i = y1[idx0:idx1] + z1i = z1[idx0:idx1] + x2i = x2[idx0:idx1] + y2i = y2[idx0:idx1] + z2i = z2[idx0:idx1] + + if not len(x1i): + continue + + if mode == 'quad': + # Preallocate the array for the region's vertices, and fill it in + n_polys_i = len(x1i) - 1 + polys_i = np.empty((n_polys_i, 4, 3)) + polys_i[:, 0, :] = np.column_stack((x1i[:-1], y1i[:-1], z1i[:-1])) + polys_i[:, 1, :] = np.column_stack((x1i[1:], y1i[1:], z1i[1:])) + polys_i[:, 2, :] = np.column_stack((x2i[1:], y2i[1:], z2i[1:])) + polys_i[:, 3, :] = np.column_stack((x2i[:-1], y2i[:-1], z2i[:-1])) + polys = polys + [*polys_i] + elif mode == 'polygon': + line1 = np.column_stack((x1i, y1i, z1i)) + line2 = np.column_stack((x2i[::-1], y2i[::-1], z2i[::-1])) + poly = np.concatenate((line1, line2), axis=0) + polys.append(poly) + + polyc = art3d.Poly3DCollection(polys, facecolors=facecolors, shade=shade, + axlim_clip=axlim_clip, **kwargs) + self.add_collection(polyc) + + self.auto_scale_xyz([x1, x2], [y1, y2], [z1, z2], had_data) + return polyc + + def plot_surface(self, X, Y, Z, *, norm=None, vmin=None, + vmax=None, lightsource=None, axlim_clip=False, **kwargs): + """ + Create a surface plot. + + By default, it will be colored in shades of a solid color, but it also + supports colormapping by supplying the *cmap* argument. + + .. note:: + + The *rcount* and *ccount* kwargs, which both default to 50, + determine the maximum number of samples used in each direction. If + the input data is larger, it will be downsampled (by slicing) to + these numbers of points. + + .. note:: + + To maximize rendering speed consider setting *rstride* and *cstride* + to divisors of the number of rows minus 1 and columns minus 1 + respectively. For example, given 51 rows rstride can be any of the + divisors of 50. + + Similarly, a setting of *rstride* and *cstride* equal to 1 (or + *rcount* and *ccount* equal the number of rows and columns) can use + the optimized path. + + Parameters + ---------- + X, Y, Z : 2D arrays + Data values. + + rcount, ccount : int + Maximum number of samples used in each direction. If the input + data is larger, it will be downsampled (by slicing) to these + numbers of points. Defaults to 50. + + rstride, cstride : int + Downsampling stride in each direction. These arguments are + mutually exclusive with *rcount* and *ccount*. If only one of + *rstride* or *cstride* is set, the other defaults to 10. + + 'classic' mode uses a default of ``rstride = cstride = 10`` instead + of the new default of ``rcount = ccount = 50``. + + color : :mpltype:`color` + Color of the surface patches. + + cmap : Colormap, optional + Colormap of the surface patches. + + facecolors : list of :mpltype:`color` + Colors of each individual patch. + + norm : `~matplotlib.colors.Normalize`, optional + Normalization for the colormap. + + vmin, vmax : float, optional + Bounds for the normalization. + + shade : bool, default: True + Whether to shade the facecolors. Shading is always disabled when + *cmap* is specified. + + lightsource : `~matplotlib.colors.LightSource`, optional + The lightsource to use when *shade* is True. + + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + + **kwargs + Other keyword arguments are forwarded to `.Poly3DCollection`. + """ + + had_data = self.has_data() + + if Z.ndim != 2: + raise ValueError("Argument Z must be 2-dimensional.") + + Z = cbook._to_unmasked_float_array(Z) + X, Y, Z = np.broadcast_arrays(X, Y, Z) + rows, cols = Z.shape + + has_stride = 'rstride' in kwargs or 'cstride' in kwargs + has_count = 'rcount' in kwargs or 'ccount' in kwargs + + if has_stride and has_count: + raise ValueError("Cannot specify both stride and count arguments") + + rstride = kwargs.pop('rstride', 10) + cstride = kwargs.pop('cstride', 10) + rcount = kwargs.pop('rcount', 50) + ccount = kwargs.pop('ccount', 50) + + if mpl.rcParams['_internal.classic_mode']: + # Strides have priority over counts in classic mode. + # So, only compute strides from counts + # if counts were explicitly given + compute_strides = has_count + else: + # If the strides are provided then it has priority. + # Otherwise, compute the strides from the counts. + compute_strides = not has_stride + + if compute_strides: + rstride = int(max(np.ceil(rows / rcount), 1)) + cstride = int(max(np.ceil(cols / ccount), 1)) + + fcolors = kwargs.pop('facecolors', None) + + cmap = kwargs.get('cmap', None) + shade = kwargs.pop('shade', cmap is None) + if shade is None: + raise ValueError("shade cannot be None.") + + colset = [] # the sampled facecolor + if (rows - 1) % rstride == 0 and \ + (cols - 1) % cstride == 0 and \ + fcolors is None: + polys = np.stack( + [cbook._array_patch_perimeters(a, rstride, cstride) + for a in (X, Y, Z)], + axis=-1) + else: + # evenly spaced, and including both endpoints + row_inds = list(range(0, rows-1, rstride)) + [rows-1] + col_inds = list(range(0, cols-1, cstride)) + [cols-1] + + polys = [] + for rs, rs_next in itertools.pairwise(row_inds): + for cs, cs_next in itertools.pairwise(col_inds): + ps = [ + # +1 ensures we share edges between polygons + cbook._array_perimeter(a[rs:rs_next+1, cs:cs_next+1]) + for a in (X, Y, Z) + ] + # ps = np.stack(ps, axis=-1) + ps = np.array(ps).T + polys.append(ps) + + if fcolors is not None: + colset.append(fcolors[rs][cs]) + + # In cases where there are non-finite values in the data (possibly NaNs from + # masked arrays), artifacts can be introduced. Here check whether such values + # are present and remove them. + if not isinstance(polys, np.ndarray) or not np.isfinite(polys).all(): + new_polys = [] + new_colset = [] + + # Depending on fcolors, colset is either an empty list or has as + # many elements as polys. In the former case new_colset results in + # a list with None entries, that is discarded later. + for p, col in itertools.zip_longest(polys, colset): + new_poly = np.array(p)[np.isfinite(p).all(axis=1)] + if len(new_poly): + new_polys.append(new_poly) + new_colset.append(col) + + # Replace previous polys and, if fcolors is not None, colset + polys = new_polys + if fcolors is not None: + colset = new_colset + + # note that the striding causes some polygons to have more coordinates + # than others + + if fcolors is not None: + polyc = art3d.Poly3DCollection( + polys, edgecolors=colset, facecolors=colset, shade=shade, + lightsource=lightsource, axlim_clip=axlim_clip, **kwargs) + elif cmap: + polyc = art3d.Poly3DCollection(polys, axlim_clip=axlim_clip, **kwargs) + # can't always vectorize, because polys might be jagged + if isinstance(polys, np.ndarray): + avg_z = polys[..., 2].mean(axis=-1) + else: + avg_z = np.array([ps[:, 2].mean() for ps in polys]) + polyc.set_array(avg_z) + if vmin is not None or vmax is not None: + polyc.set_clim(vmin, vmax) + if norm is not None: + polyc.set_norm(norm) + else: + color = kwargs.pop('color', None) + if color is None: + color = self._get_lines.get_next_color() + color = np.array(mcolors.to_rgba(color)) + + polyc = art3d.Poly3DCollection( + polys, facecolors=color, shade=shade, lightsource=lightsource, + axlim_clip=axlim_clip, **kwargs) + + self.add_collection(polyc) + self.auto_scale_xyz(X, Y, Z, had_data) + + return polyc + + def plot_wireframe(self, X, Y, Z, *, axlim_clip=False, **kwargs): + """ + Plot a 3D wireframe. + + .. note:: + + The *rcount* and *ccount* kwargs, which both default to 50, + determine the maximum number of samples used in each direction. If + the input data is larger, it will be downsampled (by slicing) to + these numbers of points. + + Parameters + ---------- + X, Y, Z : 2D arrays + Data values. + + axlim_clip : bool, default: False + Whether to hide lines and patches with vertices outside the axes + view limits. + + .. versionadded:: 3.10 + + rcount, ccount : int + Maximum number of samples used in each direction. If the input + data is larger, it will be downsampled (by slicing) to these + numbers of points. Setting a count to zero causes the data to be + not sampled in the corresponding direction, producing a 3D line + plot rather than a wireframe plot. Defaults to 50. + + rstride, cstride : int + Downsampling stride in each direction. These arguments are + mutually exclusive with *rcount* and *ccount*. If only one of + *rstride* or *cstride* is set, the other defaults to 1. Setting a + stride to zero causes the data to be not sampled in the + corresponding direction, producing a 3D line plot rather than a + wireframe plot. + + 'classic' mode uses a default of ``rstride = cstride = 1`` instead + of the new default of ``rcount = ccount = 50``. + + **kwargs + Other keyword arguments are forwarded to `.Line3DCollection`. + """ + + had_data = self.has_data() + if Z.ndim != 2: + raise ValueError("Argument Z must be 2-dimensional.") + # FIXME: Support masked arrays + X, Y, Z = np.broadcast_arrays(X, Y, Z) + rows, cols = Z.shape + + has_stride = 'rstride' in kwargs or 'cstride' in kwargs + has_count = 'rcount' in kwargs or 'ccount' in kwargs + + if has_stride and has_count: + raise ValueError("Cannot specify both stride and count arguments") + + rstride = kwargs.pop('rstride', 1) + cstride = kwargs.pop('cstride', 1) + rcount = kwargs.pop('rcount', 50) + ccount = kwargs.pop('ccount', 50) + + if mpl.rcParams['_internal.classic_mode']: + # Strides have priority over counts in classic mode. + # So, only compute strides from counts + # if counts were explicitly given + if has_count: + rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0 + cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0 + else: + # If the strides are provided then it has priority. + # Otherwise, compute the strides from the counts. + if not has_stride: + rstride = int(max(np.ceil(rows / rcount), 1)) if rcount else 0 + cstride = int(max(np.ceil(cols / ccount), 1)) if ccount else 0 + + # We want two sets of lines, one running along the "rows" of + # Z and another set of lines running along the "columns" of Z. + # This transpose will make it easy to obtain the columns. + tX, tY, tZ = np.transpose(X), np.transpose(Y), np.transpose(Z) + + if rstride: + rii = list(range(0, rows, rstride)) + # Add the last index only if needed + if rows > 0 and rii[-1] != (rows - 1): + rii += [rows-1] + else: + rii = [] + if cstride: + cii = list(range(0, cols, cstride)) + # Add the last index only if needed + if cols > 0 and cii[-1] != (cols - 1): + cii += [cols-1] + else: + cii = [] + + if rstride == 0 and cstride == 0: + raise ValueError("Either rstride or cstride must be non zero") + + # If the inputs were empty, then just + # reset everything. + if Z.size == 0: + rii = [] + cii = [] + + xlines = [X[i] for i in rii] + ylines = [Y[i] for i in rii] + zlines = [Z[i] for i in rii] + + txlines = [tX[i] for i in cii] + tylines = [tY[i] for i in cii] + tzlines = [tZ[i] for i in cii] + + lines = ([list(zip(xl, yl, zl)) + for xl, yl, zl in zip(xlines, ylines, zlines)] + + [list(zip(xl, yl, zl)) + for xl, yl, zl in zip(txlines, tylines, tzlines)]) + + linec = art3d.Line3DCollection(lines, axlim_clip=axlim_clip, **kwargs) + self.add_collection(linec) + self.auto_scale_xyz(X, Y, Z, had_data) + + return linec + + def plot_trisurf(self, *args, color=None, norm=None, vmin=None, vmax=None, + lightsource=None, axlim_clip=False, **kwargs): + """ + Plot a triangulated surface. + + The (optional) triangulation can be specified in one of two ways; + either:: + + plot_trisurf(triangulation, ...) + + where triangulation is a `~matplotlib.tri.Triangulation` object, or:: + + plot_trisurf(X, Y, ...) + plot_trisurf(X, Y, triangles, ...) + plot_trisurf(X, Y, triangles=triangles, ...) + + in which case a Triangulation object will be created. See + `.Triangulation` for an explanation of these possibilities. + + The remaining arguments are:: + + plot_trisurf(..., Z) + + where *Z* is the array of values to contour, one per point + in the triangulation. + + Parameters + ---------- + X, Y, Z : array-like + Data values as 1D arrays. + color + Color of the surface patches. + cmap + A colormap for the surface patches. + norm : `~matplotlib.colors.Normalize`, optional + An instance of Normalize to map values to colors. + vmin, vmax : float, optional + Minimum and maximum value to map. + shade : bool, default: True + Whether to shade the facecolors. Shading is always disabled when + *cmap* is specified. + lightsource : `~matplotlib.colors.LightSource`, optional + The lightsource to use when *shade* is True. + axlim_clip : bool, default: False + Whether to hide patches with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + **kwargs + All other keyword arguments are passed on to + :class:`~mpl_toolkits.mplot3d.art3d.Poly3DCollection` + + Examples + -------- + .. plot:: gallery/mplot3d/trisurf3d.py + .. plot:: gallery/mplot3d/trisurf3d_2.py + """ + + had_data = self.has_data() + + # TODO: Support custom face colours + if color is None: + color = self._get_lines.get_next_color() + color = np.array(mcolors.to_rgba(color)) + + cmap = kwargs.get('cmap', None) + shade = kwargs.pop('shade', cmap is None) + + tri, args, kwargs = \ + Triangulation.get_from_args_and_kwargs(*args, **kwargs) + try: + z = kwargs.pop('Z') + except KeyError: + # We do this so Z doesn't get passed as an arg to PolyCollection + z, *args = args + z = np.asarray(z) + + triangles = tri.get_masked_triangles() + xt = tri.x[triangles] + yt = tri.y[triangles] + zt = z[triangles] + verts = np.stack((xt, yt, zt), axis=-1) + + if cmap: + polyc = art3d.Poly3DCollection(verts, *args, + axlim_clip=axlim_clip, **kwargs) + # average over the three points of each triangle + avg_z = verts[:, :, 2].mean(axis=1) + polyc.set_array(avg_z) + if vmin is not None or vmax is not None: + polyc.set_clim(vmin, vmax) + if norm is not None: + polyc.set_norm(norm) + else: + polyc = art3d.Poly3DCollection( + verts, *args, shade=shade, lightsource=lightsource, + facecolors=color, axlim_clip=axlim_clip, **kwargs) + + self.add_collection(polyc) + self.auto_scale_xyz(tri.x, tri.y, z, had_data) + + return polyc + + def _3d_extend_contour(self, cset, stride=5): + """ + Extend a contour in 3D by creating + """ + + dz = (cset.levels[1] - cset.levels[0]) / 2 + polyverts = [] + colors = [] + for idx, level in enumerate(cset.levels): + path = cset.get_paths()[idx] + subpaths = [*path._iter_connected_components()] + color = cset.get_edgecolor()[idx] + top = art3d._paths_to_3d_segments(subpaths, level - dz) + bot = art3d._paths_to_3d_segments(subpaths, level + dz) + if not len(top[0]): + continue + nsteps = max(round(len(top[0]) / stride), 2) + stepsize = (len(top[0]) - 1) / (nsteps - 1) + polyverts.extend([ + (top[0][round(i * stepsize)], top[0][round((i + 1) * stepsize)], + bot[0][round((i + 1) * stepsize)], bot[0][round(i * stepsize)]) + for i in range(round(nsteps) - 1)]) + colors.extend([color] * (round(nsteps) - 1)) + self.add_collection3d(art3d.Poly3DCollection( + np.array(polyverts), # All polygons have 4 vertices, so vectorize. + facecolors=colors, edgecolors=colors, shade=True)) + cset.remove() + + def add_contour_set( + self, cset, extend3d=False, stride=5, zdir='z', offset=None, + axlim_clip=False): + zdir = '-' + zdir + if extend3d: + self._3d_extend_contour(cset, stride) + else: + art3d.collection_2d_to_3d( + cset, zs=offset if offset is not None else cset.levels, zdir=zdir, + axlim_clip=axlim_clip) + + def add_contourf_set(self, cset, zdir='z', offset=None, *, axlim_clip=False): + self._add_contourf_set(cset, zdir=zdir, offset=offset, + axlim_clip=axlim_clip) + + def _add_contourf_set(self, cset, zdir='z', offset=None, axlim_clip=False): + """ + Returns + ------- + levels : `numpy.ndarray` + Levels at which the filled contours are added. + """ + zdir = '-' + zdir + + midpoints = cset.levels[:-1] + np.diff(cset.levels) / 2 + # Linearly interpolate to get levels for any extensions + if cset._extend_min: + min_level = cset.levels[0] - np.diff(cset.levels[:2]) / 2 + midpoints = np.insert(midpoints, 0, min_level) + if cset._extend_max: + max_level = cset.levels[-1] + np.diff(cset.levels[-2:]) / 2 + midpoints = np.append(midpoints, max_level) + + art3d.collection_2d_to_3d( + cset, zs=offset if offset is not None else midpoints, zdir=zdir, + axlim_clip=axlim_clip) + return midpoints + + @_preprocess_data() + def contour(self, X, Y, Z, *args, + extend3d=False, stride=5, zdir='z', offset=None, axlim_clip=False, + **kwargs): + """ + Create a 3D contour plot. + + Parameters + ---------- + X, Y, Z : array-like, + Input data. See `.Axes.contour` for supported data shapes. + extend3d : bool, default: False + Whether to extend contour in 3D. + stride : int, default: 5 + Step size for extending contour. + zdir : {'x', 'y', 'z'}, default: 'z' + The direction to use. + offset : float, optional + If specified, plot a projection of the contour lines at this + position in a plane normal to *zdir*. + axlim_clip : bool, default: False + Whether to hide lines with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + *args, **kwargs + Other arguments are forwarded to `matplotlib.axes.Axes.contour`. + + Returns + ------- + matplotlib.contour.QuadContourSet + """ + had_data = self.has_data() + + jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) + cset = super().contour(jX, jY, jZ, *args, **kwargs) + self.add_contour_set(cset, extend3d, stride, zdir, offset, axlim_clip) + + self.auto_scale_xyz(X, Y, Z, had_data) + return cset + + contour3D = contour + + @_preprocess_data() + def tricontour(self, *args, + extend3d=False, stride=5, zdir='z', offset=None, axlim_clip=False, + **kwargs): + """ + Create a 3D contour plot. + + .. note:: + This method currently produces incorrect output due to a + longstanding bug in 3D PolyCollection rendering. + + Parameters + ---------- + X, Y, Z : array-like + Input data. See `.Axes.tricontour` for supported data shapes. + extend3d : bool, default: False + Whether to extend contour in 3D. + stride : int, default: 5 + Step size for extending contour. + zdir : {'x', 'y', 'z'}, default: 'z' + The direction to use. + offset : float, optional + If specified, plot a projection of the contour lines at this + position in a plane normal to *zdir*. + axlim_clip : bool, default: False + Whether to hide lines with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + *args, **kwargs + Other arguments are forwarded to `matplotlib.axes.Axes.tricontour`. + + Returns + ------- + matplotlib.tri._tricontour.TriContourSet + """ + had_data = self.has_data() + + tri, args, kwargs = Triangulation.get_from_args_and_kwargs( + *args, **kwargs) + X = tri.x + Y = tri.y + if 'Z' in kwargs: + Z = kwargs.pop('Z') + else: + # We do this so Z doesn't get passed as an arg to Axes.tricontour + Z, *args = args + + jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) + tri = Triangulation(jX, jY, tri.triangles, tri.mask) + + cset = super().tricontour(tri, jZ, *args, **kwargs) + self.add_contour_set(cset, extend3d, stride, zdir, offset, axlim_clip) + + self.auto_scale_xyz(X, Y, Z, had_data) + return cset + + def _auto_scale_contourf(self, X, Y, Z, zdir, levels, had_data): + # Autoscale in the zdir based on the levels added, which are + # different from data range if any contour extensions are present + dim_vals = {'x': X, 'y': Y, 'z': Z, zdir: levels} + # Input data and levels have different sizes, but auto_scale_xyz + # expected same-size input, so manually take min/max limits + limits = [(np.nanmin(dim_vals[dim]), np.nanmax(dim_vals[dim])) + for dim in ['x', 'y', 'z']] + self.auto_scale_xyz(*limits, had_data) + + @_preprocess_data() + def contourf(self, X, Y, Z, *args, + zdir='z', offset=None, axlim_clip=False, **kwargs): + """ + Create a 3D filled contour plot. + + Parameters + ---------- + X, Y, Z : array-like + Input data. See `.Axes.contourf` for supported data shapes. + zdir : {'x', 'y', 'z'}, default: 'z' + The direction to use. + offset : float, optional + If specified, plot a projection of the contour lines at this + position in a plane normal to *zdir*. + axlim_clip : bool, default: False + Whether to hide lines with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + *args, **kwargs + Other arguments are forwarded to `matplotlib.axes.Axes.contourf`. + + Returns + ------- + matplotlib.contour.QuadContourSet + """ + had_data = self.has_data() + + jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) + cset = super().contourf(jX, jY, jZ, *args, **kwargs) + levels = self._add_contourf_set(cset, zdir, offset, axlim_clip) + + self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data) + return cset + + contourf3D = contourf + + @_preprocess_data() + def tricontourf(self, *args, zdir='z', offset=None, axlim_clip=False, **kwargs): + """ + Create a 3D filled contour plot. + + .. note:: + This method currently produces incorrect output due to a + longstanding bug in 3D PolyCollection rendering. + + Parameters + ---------- + X, Y, Z : array-like + Input data. See `.Axes.tricontourf` for supported data shapes. + zdir : {'x', 'y', 'z'}, default: 'z' + The direction to use. + offset : float, optional + If specified, plot a projection of the contour lines at this + position in a plane normal to zdir. + axlim_clip : bool, default: False + Whether to hide lines with a vertex outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + *args, **kwargs + Other arguments are forwarded to + `matplotlib.axes.Axes.tricontourf`. + + Returns + ------- + matplotlib.tri._tricontour.TriContourSet + """ + had_data = self.has_data() + + tri, args, kwargs = Triangulation.get_from_args_and_kwargs( + *args, **kwargs) + X = tri.x + Y = tri.y + if 'Z' in kwargs: + Z = kwargs.pop('Z') + else: + # We do this so Z doesn't get passed as an arg to Axes.tricontourf + Z, *args = args + + jX, jY, jZ = art3d.rotate_axes(X, Y, Z, zdir) + tri = Triangulation(jX, jY, tri.triangles, tri.mask) + + cset = super().tricontourf(tri, jZ, *args, **kwargs) + levels = self._add_contourf_set(cset, zdir, offset, axlim_clip) + + self._auto_scale_contourf(X, Y, Z, zdir, levels, had_data) + return cset + + def add_collection3d(self, col, zs=0, zdir='z', autolim=True, *, + axlim_clip=False): + """ + Add a 3D collection object to the plot. + + 2D collection types are converted to a 3D version by + modifying the object and adding z coordinate information, + *zs* and *zdir*. + + Supported 2D collection types are: + + - `.PolyCollection` + - `.LineCollection` + - `.PatchCollection` (currently not supporting *autolim*) + + Parameters + ---------- + col : `.Collection` + A 2D collection object. + zs : float or array-like, default: 0 + The z-positions to be used for the 2D objects. + zdir : {'x', 'y', 'z'}, default: 'z' + The direction to use for the z-positions. + autolim : bool, default: True + Whether to update the data limits. + axlim_clip : bool, default: False + Whether to hide the scatter points outside the axes view limits. + + .. versionadded:: 3.10 + """ + had_data = self.has_data() + + zvals = np.atleast_1d(zs) + zsortval = (np.min(zvals) if zvals.size + else 0) # FIXME: arbitrary default + + # FIXME: use issubclass() (although, then a 3D collection + # object would also pass.) Maybe have a collection3d + # abstract class to test for and exclude? + if type(col) is mcoll.PolyCollection: + art3d.poly_collection_2d_to_3d(col, zs=zs, zdir=zdir, + axlim_clip=axlim_clip) + col.set_sort_zpos(zsortval) + elif type(col) is mcoll.LineCollection: + art3d.line_collection_2d_to_3d(col, zs=zs, zdir=zdir, + axlim_clip=axlim_clip) + col.set_sort_zpos(zsortval) + elif type(col) is mcoll.PatchCollection: + art3d.patch_collection_2d_to_3d(col, zs=zs, zdir=zdir, + axlim_clip=axlim_clip) + col.set_sort_zpos(zsortval) + + if autolim: + if isinstance(col, art3d.Line3DCollection): + self.auto_scale_xyz(*np.array(col._segments3d).transpose(), + had_data=had_data) + elif isinstance(col, art3d.Poly3DCollection): + self.auto_scale_xyz(*col._vec[:-1], had_data=had_data) + elif isinstance(col, art3d.Patch3DCollection): + pass + # FIXME: Implement auto-scaling function for Patch3DCollection + # Currently unable to do so due to issues with Patch3DCollection + # See https://github.com/matplotlib/matplotlib/issues/14298 for details + + collection = super().add_collection(col) + return collection + + @_preprocess_data(replace_names=["xs", "ys", "zs", "s", + "edgecolors", "c", "facecolor", + "facecolors", "color"]) + def scatter(self, xs, ys, + zs=0, zdir='z', s=20, c=None, depthshade=True, *args, + axlim_clip=False, **kwargs): + """ + Create a scatter plot. + + Parameters + ---------- + xs, ys : array-like + The data positions. + zs : float or array-like, default: 0 + The z-positions. Either an array of the same length as *xs* and + *ys* or a single value to place all points in the same plane. + zdir : {'x', 'y', 'z', '-x', '-y', '-z'}, default: 'z' + The axis direction for the *zs*. This is useful when plotting 2D + data on a 3D Axes. The data must be passed as *xs*, *ys*. Setting + *zdir* to 'y' then plots the data to the x-z-plane. + + See also :doc:`/gallery/mplot3d/2dcollections3d`. + + s : float or array-like, default: 20 + The marker size in points**2. Either an array of the same length + as *xs* and *ys* or a single value to make all markers the same + size. + c : :mpltype:`color`, sequence, or sequence of colors, optional + The marker color. Possible values: + + - A single color format string. + - A sequence of colors of length n. + - A sequence of n numbers to be mapped to colors using *cmap* and + *norm*. + - A 2D array in which the rows are RGB or RGBA. + + For more details see the *c* argument of `~.axes.Axes.scatter`. + depthshade : bool, default: True + Whether to shade the scatter markers to give the appearance of + depth. Each call to ``scatter()`` will perform its depthshading + independently. + axlim_clip : bool, default: False + Whether to hide the scatter points outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs + All other keyword arguments are passed on to `~.axes.Axes.scatter`. + + Returns + ------- + paths : `~matplotlib.collections.PathCollection` + """ + + had_data = self.has_data() + zs_orig = zs + + xs, ys, zs = cbook._broadcast_with_masks(xs, ys, zs) + s = np.ma.ravel(s) # This doesn't have to match x, y in size. + + xs, ys, zs, s, c, color = cbook.delete_masked_points( + xs, ys, zs, s, c, kwargs.get('color', None) + ) + if kwargs.get("color") is not None: + kwargs['color'] = color + + # For xs and ys, 2D scatter() will do the copying. + if np.may_share_memory(zs_orig, zs): # Avoid unnecessary copies. + zs = zs.copy() + + patches = super().scatter(xs, ys, s=s, c=c, *args, **kwargs) + art3d.patch_collection_2d_to_3d(patches, zs=zs, zdir=zdir, + depthshade=depthshade, + axlim_clip=axlim_clip) + + if self._zmargin < 0.05 and xs.size > 0: + self.set_zmargin(0.05) + + self.auto_scale_xyz(xs, ys, zs, had_data) + + return patches + + scatter3D = scatter + + @_preprocess_data() + def bar(self, left, height, zs=0, zdir='z', *args, + axlim_clip=False, **kwargs): + """ + Add 2D bar(s). + + Parameters + ---------- + left : 1D array-like + The x coordinates of the left sides of the bars. + height : 1D array-like + The height of the bars. + zs : float or 1D array-like, default: 0 + Z coordinate of bars; if a single value is specified, it will be + used for all bars. + zdir : {'x', 'y', 'z'}, default: 'z' + When plotting 2D data, the direction to use as z ('x', 'y' or 'z'). + axlim_clip : bool, default: False + Whether to hide bars with points outside the axes view limits. + + .. versionadded:: 3.10 + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + **kwargs + Other keyword arguments are forwarded to + `matplotlib.axes.Axes.bar`. + + Returns + ------- + mpl_toolkits.mplot3d.art3d.Patch3DCollection + """ + had_data = self.has_data() + + patches = super().bar(left, height, *args, **kwargs) + + zs = np.broadcast_to(zs, len(left), subok=True) + + verts = [] + verts_zs = [] + for p, z in zip(patches, zs): + vs = art3d._get_patch_verts(p) + verts += vs.tolist() + verts_zs += [z] * len(vs) + art3d.patch_2d_to_3d(p, z, zdir, axlim_clip) + if 'alpha' in kwargs: + p.set_alpha(kwargs['alpha']) + + if len(verts) > 0: + # the following has to be skipped if verts is empty + # NOTE: Bugs could still occur if len(verts) > 0, + # but the "2nd dimension" is empty. + xs, ys = zip(*verts) + else: + xs, ys = [], [] + + xs, ys, verts_zs = art3d.juggle_axes(xs, ys, verts_zs, zdir) + self.auto_scale_xyz(xs, ys, verts_zs, had_data) + + return patches + + @_preprocess_data() + def bar3d(self, x, y, z, dx, dy, dz, color=None, + zsort='average', shade=True, lightsource=None, *args, + axlim_clip=False, **kwargs): + """ + Generate a 3D barplot. + + This method creates three-dimensional barplot where the width, + depth, height, and color of the bars can all be uniquely set. + + Parameters + ---------- + x, y, z : array-like + The coordinates of the anchor point of the bars. + + dx, dy, dz : float or array-like + The width, depth, and height of the bars, respectively. + + color : sequence of colors, optional + The color of the bars can be specified globally or + individually. This parameter can be: + + - A single color, to color all bars the same color. + - An array of colors of length N bars, to color each bar + independently. + - An array of colors of length 6, to color the faces of the + bars similarly. + - An array of colors of length 6 * N bars, to color each face + independently. + + When coloring the faces of the boxes specifically, this is + the order of the coloring: + + 1. -Z (bottom of box) + 2. +Z (top of box) + 3. -Y + 4. +Y + 5. -X + 6. +X + + zsort : {'average', 'min', 'max'}, default: 'average' + The z-axis sorting scheme passed onto `~.art3d.Poly3DCollection` + + shade : bool, default: True + When true, this shades the dark sides of the bars (relative + to the plot's source of light). + + lightsource : `~matplotlib.colors.LightSource`, optional + The lightsource to use when *shade* is True. + + axlim_clip : bool, default: False + Whether to hide the bars with points outside the axes view limits. + + .. versionadded:: 3.10 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Any additional keyword arguments are passed onto + `~.art3d.Poly3DCollection`. + + Returns + ------- + collection : `~.art3d.Poly3DCollection` + A collection of three-dimensional polygons representing the bars. + """ + + had_data = self.has_data() + + x, y, z, dx, dy, dz = np.broadcast_arrays( + np.atleast_1d(x), y, z, dx, dy, dz) + minx = np.min(x) + maxx = np.max(x + dx) + miny = np.min(y) + maxy = np.max(y + dy) + minz = np.min(z) + maxz = np.max(z + dz) + + # shape (6, 4, 3) + # All faces are oriented facing outwards - when viewed from the + # outside, their vertices are in a counterclockwise ordering. + cuboid = np.array([ + # -z + ( + (0, 0, 0), + (0, 1, 0), + (1, 1, 0), + (1, 0, 0), + ), + # +z + ( + (0, 0, 1), + (1, 0, 1), + (1, 1, 1), + (0, 1, 1), + ), + # -y + ( + (0, 0, 0), + (1, 0, 0), + (1, 0, 1), + (0, 0, 1), + ), + # +y + ( + (0, 1, 0), + (0, 1, 1), + (1, 1, 1), + (1, 1, 0), + ), + # -x + ( + (0, 0, 0), + (0, 0, 1), + (0, 1, 1), + (0, 1, 0), + ), + # +x + ( + (1, 0, 0), + (1, 1, 0), + (1, 1, 1), + (1, 0, 1), + ), + ]) + + # indexed by [bar, face, vertex, coord] + polys = np.empty(x.shape + cuboid.shape) + + # handle each coordinate separately + for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]: + p = p[..., np.newaxis, np.newaxis] + dp = dp[..., np.newaxis, np.newaxis] + polys[..., i] = p + dp * cuboid[..., i] + + # collapse the first two axes + polys = polys.reshape((-1,) + polys.shape[2:]) + + facecolors = [] + if color is None: + color = [self._get_patches_for_fill.get_next_color()] + + color = list(mcolors.to_rgba_array(color)) + + if len(color) == len(x): + # bar colors specified, need to expand to number of faces + for c in color: + facecolors.extend([c] * 6) + else: + # a single color specified, or face colors specified explicitly + facecolors = color + if len(facecolors) < len(x): + facecolors *= (6 * len(x)) + + col = art3d.Poly3DCollection(polys, + zsort=zsort, + facecolors=facecolors, + shade=shade, + lightsource=lightsource, + axlim_clip=axlim_clip, + *args, **kwargs) + self.add_collection(col) + + self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data) + + return col + + def set_title(self, label, fontdict=None, loc='center', **kwargs): + # docstring inherited + ret = super().set_title(label, fontdict=fontdict, loc=loc, **kwargs) + (x, y) = self.title.get_position() + self.title.set_y(0.92 * y) + return ret + + @_preprocess_data() + def quiver(self, X, Y, Z, U, V, W, *, + length=1, arrow_length_ratio=.3, pivot='tail', normalize=False, + axlim_clip=False, **kwargs): + """ + Plot a 3D field of arrows. + + The arguments can be array-like or scalars, so long as they can be + broadcast together. The arguments can also be masked arrays. If an + element in any of argument is masked, then that corresponding quiver + element will not be plotted. + + Parameters + ---------- + X, Y, Z : array-like + The x, y and z coordinates of the arrow locations (default is + tail of arrow; see *pivot* kwarg). + + U, V, W : array-like + The x, y and z components of the arrow vectors. + + length : float, default: 1 + The length of each quiver. + + arrow_length_ratio : float, default: 0.3 + The ratio of the arrow head with respect to the quiver. + + pivot : {'tail', 'middle', 'tip'}, default: 'tail' + The part of the arrow that is at the grid point; the arrow + rotates about this point, hence the name *pivot*. + + normalize : bool, default: False + Whether all arrows are normalized to have the same length, or keep + the lengths defined by *u*, *v*, and *w*. + + axlim_clip : bool, default: False + Whether to hide arrows with points outside the axes view limits. + + .. versionadded:: 3.10 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + Any additional keyword arguments are delegated to + :class:`.Line3DCollection` + """ + + def calc_arrows(UVW): + # get unit direction vector perpendicular to (u, v, w) + x = UVW[:, 0] + y = UVW[:, 1] + norm = np.linalg.norm(UVW[:, :2], axis=1) + x_p = np.divide(y, norm, where=norm != 0, out=np.zeros_like(x)) + y_p = np.divide(-x, norm, where=norm != 0, out=np.ones_like(x)) + # compute the two arrowhead direction unit vectors + rangle = math.radians(15) + c = math.cos(rangle) + s = math.sin(rangle) + # construct the rotation matrices of shape (3, 3, n) + r13 = y_p * s + r32 = x_p * s + r12 = x_p * y_p * (1 - c) + Rpos = np.array( + [[c + (x_p ** 2) * (1 - c), r12, r13], + [r12, c + (y_p ** 2) * (1 - c), -r32], + [-r13, r32, np.full_like(x_p, c)]]) + # opposite rotation negates all the sin terms + Rneg = Rpos.copy() + Rneg[[0, 1, 2, 2], [2, 2, 0, 1]] *= -1 + # Batch n (3, 3) x (3) matrix multiplications ((3, 3, n) x (n, 3)). + Rpos_vecs = np.einsum("ij...,...j->...i", Rpos, UVW) + Rneg_vecs = np.einsum("ij...,...j->...i", Rneg, UVW) + # Stack into (n, 2, 3) result. + return np.stack([Rpos_vecs, Rneg_vecs], axis=1) + + had_data = self.has_data() + + input_args = cbook._broadcast_with_masks(X, Y, Z, U, V, W, + compress=True) + + if any(len(v) == 0 for v in input_args): + # No quivers, so just make an empty collection and return early + linec = art3d.Line3DCollection([], **kwargs) + self.add_collection(linec) + return linec + + shaft_dt = np.array([0., length], dtype=float) + arrow_dt = shaft_dt * arrow_length_ratio + + _api.check_in_list(['tail', 'middle', 'tip'], pivot=pivot) + if pivot == 'tail': + shaft_dt -= length + elif pivot == 'middle': + shaft_dt -= length / 2 + + XYZ = np.column_stack(input_args[:3]) + UVW = np.column_stack(input_args[3:]).astype(float) + + # Normalize rows of UVW + if normalize: + norm = np.linalg.norm(UVW, axis=1) + norm[norm == 0] = 1 + UVW = UVW / norm.reshape((-1, 1)) + + if len(XYZ) > 0: + # compute the shaft lines all at once with an outer product + shafts = (XYZ - np.multiply.outer(shaft_dt, UVW)).swapaxes(0, 1) + # compute head direction vectors, n heads x 2 sides x 3 dimensions + head_dirs = calc_arrows(UVW) + # compute all head lines at once, starting from the shaft ends + heads = shafts[:, :1] - np.multiply.outer(arrow_dt, head_dirs) + # stack left and right head lines together + heads = heads.reshape((len(arrow_dt), -1, 3)) + # transpose to get a list of lines + heads = heads.swapaxes(0, 1) + + lines = [*shafts, *heads[::2], *heads[1::2]] + else: + lines = [] + + linec = art3d.Line3DCollection(lines, axlim_clip=axlim_clip, **kwargs) + self.add_collection(linec) + + self.auto_scale_xyz(XYZ[:, 0], XYZ[:, 1], XYZ[:, 2], had_data) + + return linec + + quiver3D = quiver + + def voxels(self, *args, facecolors=None, edgecolors=None, shade=True, + lightsource=None, axlim_clip=False, **kwargs): + """ + ax.voxels([x, y, z,] /, filled, facecolors=None, edgecolors=None, \ +**kwargs) + + Plot a set of filled voxels + + All voxels are plotted as 1x1x1 cubes on the axis, with + ``filled[0, 0, 0]`` placed with its lower corner at the origin. + Occluded faces are not plotted. + + Parameters + ---------- + filled : 3D np.array of bool + A 3D array of values, with truthy values indicating which voxels + to fill + + x, y, z : 3D np.array, optional + The coordinates of the corners of the voxels. This should broadcast + to a shape one larger in every dimension than the shape of + *filled*. These can be used to plot non-cubic voxels. + + If not specified, defaults to increasing integers along each axis, + like those returned by :func:`~numpy.indices`. + As indicated by the ``/`` in the function signature, these + arguments can only be passed positionally. + + facecolors, edgecolors : array-like, optional + The color to draw the faces and edges of the voxels. Can only be + passed as keyword arguments. + These parameters can be: + + - A single color value, to color all voxels the same color. This + can be either a string, or a 1D RGB/RGBA array + - ``None``, the default, to use a single color for the faces, and + the style default for the edges. + - A 3D `~numpy.ndarray` of color names, with each item the color + for the corresponding voxel. The size must match the voxels. + - A 4D `~numpy.ndarray` of RGB/RGBA data, with the components + along the last axis. + + shade : bool, default: True + Whether to shade the facecolors. + + lightsource : `~matplotlib.colors.LightSource`, optional + The lightsource to use when *shade* is True. + + axlim_clip : bool, default: False + Whether to hide voxels with points outside the axes view limits. + + .. versionadded:: 3.10 + + **kwargs + Additional keyword arguments to pass onto + `~mpl_toolkits.mplot3d.art3d.Poly3DCollection`. + + Returns + ------- + faces : dict + A dictionary indexed by coordinate, where ``faces[i, j, k]`` is a + `.Poly3DCollection` of the faces drawn for the voxel + ``filled[i, j, k]``. If no faces were drawn for a given voxel, + either because it was not asked to be drawn, or it is fully + occluded, then ``(i, j, k) not in faces``. + + Examples + -------- + .. plot:: gallery/mplot3d/voxels.py + .. plot:: gallery/mplot3d/voxels_rgb.py + .. plot:: gallery/mplot3d/voxels_torus.py + .. plot:: gallery/mplot3d/voxels_numpy_logo.py + """ + + # work out which signature we should be using, and use it to parse + # the arguments. Name must be voxels for the correct error message + if len(args) >= 3: + # underscores indicate position only + def voxels(__x, __y, __z, filled, **kwargs): + return (__x, __y, __z), filled, kwargs + else: + def voxels(filled, **kwargs): + return None, filled, kwargs + + xyz, filled, kwargs = voxels(*args, **kwargs) + + # check dimensions + if filled.ndim != 3: + raise ValueError("Argument filled must be 3-dimensional") + size = np.array(filled.shape, dtype=np.intp) + + # check xyz coordinates, which are one larger than the filled shape + coord_shape = tuple(size + 1) + if xyz is None: + x, y, z = np.indices(coord_shape) + else: + x, y, z = (np.broadcast_to(c, coord_shape) for c in xyz) + + def _broadcast_color_arg(color, name): + if np.ndim(color) in (0, 1): + # single color, like "red" or [1, 0, 0] + return np.broadcast_to(color, filled.shape + np.shape(color)) + elif np.ndim(color) in (3, 4): + # 3D array of strings, or 4D array with last axis rgb + if np.shape(color)[:3] != filled.shape: + raise ValueError( + f"When multidimensional, {name} must match the shape " + "of filled") + return color + else: + raise ValueError(f"Invalid {name} argument") + + # broadcast and default on facecolors + if facecolors is None: + facecolors = self._get_patches_for_fill.get_next_color() + facecolors = _broadcast_color_arg(facecolors, 'facecolors') + + # broadcast but no default on edgecolors + edgecolors = _broadcast_color_arg(edgecolors, 'edgecolors') + + # scale to the full array, even if the data is only in the center + self.auto_scale_xyz(x, y, z) + + # points lying on corners of a square + square = np.array([ + [0, 0, 0], + [1, 0, 0], + [1, 1, 0], + [0, 1, 0], + ], dtype=np.intp) + + voxel_faces = defaultdict(list) + + def permutation_matrices(n): + """Generate cyclic permutation matrices.""" + mat = np.eye(n, dtype=np.intp) + for i in range(n): + yield mat + mat = np.roll(mat, 1, axis=0) + + # iterate over each of the YZ, ZX, and XY orientations, finding faces + # to render + for permute in permutation_matrices(3): + # find the set of ranges to iterate over + pc, qc, rc = permute.T.dot(size) + pinds = np.arange(pc) + qinds = np.arange(qc) + rinds = np.arange(rc) + + square_rot_pos = square.dot(permute.T) + square_rot_neg = square_rot_pos[::-1] + + # iterate within the current plane + for p in pinds: + for q in qinds: + # iterate perpendicularly to the current plane, handling + # boundaries. We only draw faces between a voxel and an + # empty space, to avoid drawing internal faces. + + # draw lower faces + p0 = permute.dot([p, q, 0]) + i0 = tuple(p0) + if filled[i0]: + voxel_faces[i0].append(p0 + square_rot_neg) + + # draw middle faces + for r1, r2 in itertools.pairwise(rinds): + p1 = permute.dot([p, q, r1]) + p2 = permute.dot([p, q, r2]) + + i1 = tuple(p1) + i2 = tuple(p2) + + if filled[i1] and not filled[i2]: + voxel_faces[i1].append(p2 + square_rot_pos) + elif not filled[i1] and filled[i2]: + voxel_faces[i2].append(p2 + square_rot_neg) + + # draw upper faces + pk = permute.dot([p, q, rc-1]) + pk2 = permute.dot([p, q, rc]) + ik = tuple(pk) + if filled[ik]: + voxel_faces[ik].append(pk2 + square_rot_pos) + + # iterate over the faces, and generate a Poly3DCollection for each + # voxel + polygons = {} + for coord, faces_inds in voxel_faces.items(): + # convert indices into 3D positions + if xyz is None: + faces = faces_inds + else: + faces = [] + for face_inds in faces_inds: + ind = face_inds[:, 0], face_inds[:, 1], face_inds[:, 2] + face = np.empty(face_inds.shape) + face[:, 0] = x[ind] + face[:, 1] = y[ind] + face[:, 2] = z[ind] + faces.append(face) + + # shade the faces + facecolor = facecolors[coord] + edgecolor = edgecolors[coord] + + poly = art3d.Poly3DCollection( + faces, facecolors=facecolor, edgecolors=edgecolor, + shade=shade, lightsource=lightsource, axlim_clip=axlim_clip, + **kwargs) + self.add_collection3d(poly) + polygons[coord] = poly + + return polygons + + @_preprocess_data(replace_names=["x", "y", "z", "xerr", "yerr", "zerr"]) + def errorbar(self, x, y, z, zerr=None, yerr=None, xerr=None, fmt='', + barsabove=False, errorevery=1, ecolor=None, elinewidth=None, + capsize=None, capthick=None, xlolims=False, xuplims=False, + ylolims=False, yuplims=False, zlolims=False, zuplims=False, + axlim_clip=False, + **kwargs): + """ + Plot lines and/or markers with errorbars around them. + + *x*/*y*/*z* define the data locations, and *xerr*/*yerr*/*zerr* define + the errorbar sizes. By default, this draws the data markers/lines as + well the errorbars. Use fmt='none' to draw errorbars only. + + Parameters + ---------- + x, y, z : float or array-like + The data positions. + + xerr, yerr, zerr : float or array-like, shape (N,) or (2, N), optional + The errorbar sizes: + + - scalar: Symmetric +/- values for all data points. + - shape(N,): Symmetric +/-values for each data point. + - shape(2, N): Separate - and + values for each bar. First row + contains the lower errors, the second row contains the upper + errors. + - *None*: No errorbar. + + Note that all error arrays should have *positive* values. + + fmt : str, default: '' + The format for the data points / data lines. See `.plot` for + details. + + Use 'none' (case-insensitive) to plot errorbars without any data + markers. + + ecolor : :mpltype:`color`, default: None + The color of the errorbar lines. If None, use the color of the + line connecting the markers. + + elinewidth : float, default: None + The linewidth of the errorbar lines. If None, the linewidth of + the current style is used. + + capsize : float, default: :rc:`errorbar.capsize` + The length of the error bar caps in points. + + capthick : float, default: None + An alias to the keyword argument *markeredgewidth* (a.k.a. *mew*). + This setting is a more sensible name for the property that + controls the thickness of the error bar cap in points. For + backwards compatibility, if *mew* or *markeredgewidth* are given, + then they will over-ride *capthick*. This may change in future + releases. + + barsabove : bool, default: False + If True, will plot the errorbars above the plot + symbols. Default is below. + + xlolims, ylolims, zlolims : bool, default: False + These arguments can be used to indicate that a value gives only + lower limits. In that case a caret symbol is used to indicate + this. *lims*-arguments may be scalars, or array-likes of the same + length as the errors. To use limits with inverted axes, + `~.set_xlim`, `~.set_ylim`, or `~.set_zlim` must be + called before `errorbar`. Note the tricky parameter names: setting + e.g. *ylolims* to True means that the y-value is a *lower* limit of + the True value, so, only an *upward*-pointing arrow will be drawn! + + xuplims, yuplims, zuplims : bool, default: False + Same as above, but for controlling the upper limits. + + errorevery : int or (int, int), default: 1 + draws error bars on a subset of the data. *errorevery* =N draws + error bars on the points (x[::N], y[::N], z[::N]). + *errorevery* =(start, N) draws error bars on the points + (x[start::N], y[start::N], z[start::N]). e.g. *errorevery* =(6, 3) + adds error bars to the data at (x[6], x[9], x[12], x[15], ...). + Used to avoid overlapping error bars when two series share x-axis + values. + + axlim_clip : bool, default: False + Whether to hide error bars that are outside the axes limits. + + .. versionadded:: 3.10 + + Returns + ------- + errlines : list + List of `~mpl_toolkits.mplot3d.art3d.Line3DCollection` instances + each containing an errorbar line. + caplines : list + List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each + containing a capline object. + limmarks : list + List of `~mpl_toolkits.mplot3d.art3d.Line3D` instances each + containing a marker with an upper or lower limit. + + Other Parameters + ---------------- + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + **kwargs + All other keyword arguments for styling errorbar lines are passed + `~mpl_toolkits.mplot3d.art3d.Line3DCollection`. + + Examples + -------- + .. plot:: gallery/mplot3d/errorbar3d.py + """ + had_data = self.has_data() + + kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D) + # Drop anything that comes in as None to use the default instead. + kwargs = {k: v for k, v in kwargs.items() if v is not None} + kwargs.setdefault('zorder', 2) + + self._process_unit_info([("x", x), ("y", y), ("z", z)], kwargs, + convert=False) + + # make sure all the args are iterable; use lists not arrays to + # preserve units + x = x if np.iterable(x) else [x] + y = y if np.iterable(y) else [y] + z = z if np.iterable(z) else [z] + + if not len(x) == len(y) == len(z): + raise ValueError("'x', 'y', and 'z' must have the same size") + + everymask = self._errorevery_to_mask(x, errorevery) + + label = kwargs.pop("label", None) + kwargs['label'] = '_nolegend_' + + # Create the main line and determine overall kwargs for child artists. + # We avoid calling self.plot() directly, or self._get_lines(), because + # that would call self._process_unit_info again, and do other indirect + # data processing. + (data_line, base_style), = self._get_lines._plot_args( + self, (x, y) if fmt == '' else (x, y, fmt), kwargs, return_kwargs=True) + art3d.line_2d_to_3d(data_line, zs=z, axlim_clip=axlim_clip) + + # Do this after creating `data_line` to avoid modifying `base_style`. + if barsabove: + data_line.set_zorder(kwargs['zorder'] - .1) + else: + data_line.set_zorder(kwargs['zorder'] + .1) + + # Add line to plot, or throw it away and use it to determine kwargs. + if fmt.lower() != 'none': + self.add_line(data_line) + else: + data_line = None + # Remove alpha=0 color that _process_plot_format returns. + base_style.pop('color') + + if 'color' not in base_style: + base_style['color'] = 'C0' + if ecolor is None: + ecolor = base_style['color'] + + # Eject any line-specific information from format string, as it's not + # needed for bars or caps. + for key in ['marker', 'markersize', 'markerfacecolor', + 'markeredgewidth', 'markeredgecolor', 'markevery', + 'linestyle', 'fillstyle', 'drawstyle', 'dash_capstyle', + 'dash_joinstyle', 'solid_capstyle', 'solid_joinstyle']: + base_style.pop(key, None) + + # Make the style dict for the line collections (the bars). + eb_lines_style = {**base_style, 'color': ecolor} + + if elinewidth: + eb_lines_style['linewidth'] = elinewidth + elif 'linewidth' in kwargs: + eb_lines_style['linewidth'] = kwargs['linewidth'] + + for key in ('transform', 'alpha', 'zorder', 'rasterized'): + if key in kwargs: + eb_lines_style[key] = kwargs[key] + + # Make the style dict for caps (the "hats"). + eb_cap_style = {**base_style, 'linestyle': 'None'} + if capsize is None: + capsize = mpl.rcParams["errorbar.capsize"] + if capsize > 0: + eb_cap_style['markersize'] = 2. * capsize + if capthick is not None: + eb_cap_style['markeredgewidth'] = capthick + eb_cap_style['color'] = ecolor + + def _apply_mask(arrays, mask): + # Return, for each array in *arrays*, the elements for which *mask* + # is True, without using fancy indexing. + return [[*itertools.compress(array, mask)] for array in arrays] + + def _extract_errs(err, data, lomask, himask): + # For separate +/- error values we need to unpack err + if len(err.shape) == 2: + low_err, high_err = err + else: + low_err, high_err = err, err + + lows = np.where(lomask | ~everymask, data, data - low_err) + highs = np.where(himask | ~everymask, data, data + high_err) + + return lows, highs + + # collect drawn items while looping over the three coordinates + errlines, caplines, limmarks = [], [], [] + + # list of endpoint coordinates, used for auto-scaling + coorderrs = [] + + # define the markers used for errorbar caps and limits below + # the dictionary key is mapped by the `i_xyz` helper dictionary + capmarker = {0: '|', 1: '|', 2: '_'} + i_xyz = {'x': 0, 'y': 1, 'z': 2} + + # Calculate marker size from points to quiver length. Because these are + # not markers, and 3D Axes do not use the normal transform stack, this + # is a bit involved. Since the quiver arrows will change size as the + # scene is rotated, they are given a standard size based on viewing + # them directly in planar form. + quiversize = eb_cap_style.get('markersize', + mpl.rcParams['lines.markersize']) ** 2 + quiversize *= self.get_figure(root=True).dpi / 72 + quiversize = self.transAxes.inverted().transform([ + (0, 0), (quiversize, quiversize)]) + quiversize = np.mean(np.diff(quiversize, axis=0)) + # quiversize is now in Axes coordinates, and to convert back to data + # coordinates, we need to run it through the inverse 3D transform. For + # consistency, this uses a fixed elevation, azimuth, and roll. + with cbook._setattr_cm(self, elev=0, azim=0, roll=0): + invM = np.linalg.inv(self.get_proj()) + # elev=azim=roll=0 produces the Y-Z plane, so quiversize in 2D 'x' is + # 'y' in 3D, hence the 1 index. + quiversize = np.dot(invM, [quiversize, 0, 0, 0])[1] + # Quivers use a fixed 15-degree arrow head, so scale up the length so + # that the size corresponds to the base. In other words, this constant + # corresponds to the equation tan(15) = (base / 2) / (arrow length). + quiversize *= 1.8660254037844388 + eb_quiver_style = {**eb_cap_style, + 'length': quiversize, 'arrow_length_ratio': 1} + eb_quiver_style.pop('markersize', None) + + # loop over x-, y-, and z-direction and draw relevant elements + for zdir, data, err, lolims, uplims in zip( + ['x', 'y', 'z'], [x, y, z], [xerr, yerr, zerr], + [xlolims, ylolims, zlolims], [xuplims, yuplims, zuplims]): + + dir_vector = art3d.get_dir_vector(zdir) + i_zdir = i_xyz[zdir] + + if err is None: + continue + + if not np.iterable(err): + err = [err] * len(data) + + err = np.atleast_1d(err) + + # arrays fine here, they are booleans and hence not units + lolims = np.broadcast_to(lolims, len(data)).astype(bool) + uplims = np.broadcast_to(uplims, len(data)).astype(bool) + + # a nested list structure that expands to (xl,xh),(yl,yh),(zl,zh), + # where x/y/z and l/h correspond to dimensions and low/high + # positions of errorbars in a dimension we're looping over + coorderr = [ + _extract_errs(err * dir_vector[i], coord, lolims, uplims) + for i, coord in enumerate([x, y, z])] + (xl, xh), (yl, yh), (zl, zh) = coorderr + + # draws capmarkers - flat caps orthogonal to the error bars + nolims = ~(lolims | uplims) + if nolims.any() and capsize > 0: + lo_caps_xyz = _apply_mask([xl, yl, zl], nolims & everymask) + hi_caps_xyz = _apply_mask([xh, yh, zh], nolims & everymask) + + # setting '_' for z-caps and '|' for x- and y-caps; + # these markers will rotate as the viewing angle changes + cap_lo = art3d.Line3D(*lo_caps_xyz, ls='', + marker=capmarker[i_zdir], + axlim_clip=axlim_clip, + **eb_cap_style) + cap_hi = art3d.Line3D(*hi_caps_xyz, ls='', + marker=capmarker[i_zdir], + axlim_clip=axlim_clip, + **eb_cap_style) + self.add_line(cap_lo) + self.add_line(cap_hi) + caplines.append(cap_lo) + caplines.append(cap_hi) + + if lolims.any(): + xh0, yh0, zh0 = _apply_mask([xh, yh, zh], lolims & everymask) + self.quiver(xh0, yh0, zh0, *dir_vector, **eb_quiver_style) + if uplims.any(): + xl0, yl0, zl0 = _apply_mask([xl, yl, zl], uplims & everymask) + self.quiver(xl0, yl0, zl0, *-dir_vector, **eb_quiver_style) + + errline = art3d.Line3DCollection(np.array(coorderr).T, + axlim_clip=axlim_clip, + **eb_lines_style) + self.add_collection(errline) + errlines.append(errline) + coorderrs.append(coorderr) + + coorderrs = np.array(coorderrs) + + def _digout_minmax(err_arr, coord_label): + return (np.nanmin(err_arr[:, i_xyz[coord_label], :, :]), + np.nanmax(err_arr[:, i_xyz[coord_label], :, :])) + + minx, maxx = _digout_minmax(coorderrs, 'x') + miny, maxy = _digout_minmax(coorderrs, 'y') + minz, maxz = _digout_minmax(coorderrs, 'z') + self.auto_scale_xyz((minx, maxx), (miny, maxy), (minz, maxz), had_data) + + # Adapting errorbar containers for 3d case, assuming z-axis points "up" + errorbar_container = mcontainer.ErrorbarContainer( + (data_line, tuple(caplines), tuple(errlines)), + has_xerr=(xerr is not None or yerr is not None), + has_yerr=(zerr is not None), + label=label) + self.containers.append(errorbar_container) + + return errlines, caplines, limmarks + + def get_tightbbox(self, renderer=None, *, call_axes_locator=True, + bbox_extra_artists=None, for_layout_only=False): + ret = super().get_tightbbox(renderer, + call_axes_locator=call_axes_locator, + bbox_extra_artists=bbox_extra_artists, + for_layout_only=for_layout_only) + batch = [ret] + if self._axis3don: + for axis in self._axis_map.values(): + if axis.get_visible(): + axis_bb = martist._get_tightbbox_for_layout_only( + axis, renderer) + if axis_bb: + batch.append(axis_bb) + return mtransforms.Bbox.union(batch) + + @_preprocess_data() + def stem(self, x, y, z, *, linefmt='C0-', markerfmt='C0o', basefmt='C3-', + bottom=0, label=None, orientation='z', axlim_clip=False): + """ + Create a 3D stem plot. + + A stem plot draws lines perpendicular to a baseline, and places markers + at the heads. By default, the baseline is defined by *x* and *y*, and + stems are drawn vertically from *bottom* to *z*. + + Parameters + ---------- + x, y, z : array-like + The positions of the heads of the stems. The stems are drawn along + the *orientation*-direction from the baseline at *bottom* (in the + *orientation*-coordinate) to the heads. By default, the *x* and *y* + positions are used for the baseline and *z* for the head position, + but this can be changed by *orientation*. + + linefmt : str, default: 'C0-' + A string defining the properties of the vertical lines. Usually, + this will be a color or a color and a linestyle: + + ========= ============= + Character Line Style + ========= ============= + ``'-'`` solid line + ``'--'`` dashed line + ``'-.'`` dash-dot line + ``':'`` dotted line + ========= ============= + + Note: While it is technically possible to specify valid formats + other than color or color and linestyle (e.g. 'rx' or '-.'), this + is beyond the intention of the method and will most likely not + result in a reasonable plot. + + markerfmt : str, default: 'C0o' + A string defining the properties of the markers at the stem heads. + + basefmt : str, default: 'C3-' + A format string defining the properties of the baseline. + + bottom : float, default: 0 + The position of the baseline, in *orientation*-coordinates. + + label : str, optional + The label to use for the stems in legends. + + orientation : {'x', 'y', 'z'}, default: 'z' + The direction along which stems are drawn. + + axlim_clip : bool, default: False + Whether to hide stems that are outside the axes limits. + + .. versionadded:: 3.10 + + data : indexable object, optional + DATA_PARAMETER_PLACEHOLDER + + Returns + ------- + `.StemContainer` + The container may be treated like a tuple + (*markerline*, *stemlines*, *baseline*) + + Examples + -------- + .. plot:: gallery/mplot3d/stem3d_demo.py + """ + + from matplotlib.container import StemContainer + + had_data = self.has_data() + + _api.check_in_list(['x', 'y', 'z'], orientation=orientation) + + xlim = (np.min(x), np.max(x)) + ylim = (np.min(y), np.max(y)) + zlim = (np.min(z), np.max(z)) + + # Determine the appropriate plane for the baseline and the direction of + # stemlines based on the value of orientation. + if orientation == 'x': + basex, basexlim = y, ylim + basey, baseylim = z, zlim + lines = [[(bottom, thisy, thisz), (thisx, thisy, thisz)] + for thisx, thisy, thisz in zip(x, y, z)] + elif orientation == 'y': + basex, basexlim = x, xlim + basey, baseylim = z, zlim + lines = [[(thisx, bottom, thisz), (thisx, thisy, thisz)] + for thisx, thisy, thisz in zip(x, y, z)] + else: + basex, basexlim = x, xlim + basey, baseylim = y, ylim + lines = [[(thisx, thisy, bottom), (thisx, thisy, thisz)] + for thisx, thisy, thisz in zip(x, y, z)] + + # Determine style for stem lines. + linestyle, linemarker, linecolor = _process_plot_format(linefmt) + if linestyle is None: + linestyle = mpl.rcParams['lines.linestyle'] + + # Plot everything in required order. + baseline, = self.plot(basex, basey, basefmt, zs=bottom, + zdir=orientation, label='_nolegend_') + stemlines = art3d.Line3DCollection( + lines, linestyles=linestyle, colors=linecolor, label='_nolegend_', + axlim_clip=axlim_clip) + self.add_collection(stemlines) + markerline, = self.plot(x, y, z, markerfmt, label='_nolegend_') + + stem_container = StemContainer((markerline, stemlines, baseline), + label=label) + self.add_container(stem_container) + + jx, jy, jz = art3d.juggle_axes(basexlim, baseylim, [bottom, bottom], + orientation) + self.auto_scale_xyz([*jx, *xlim], [*jy, *ylim], [*jz, *zlim], had_data) + + return stem_container + + stem3D = stem + + +def get_test_data(delta=0.05): + """Return a tuple X, Y, Z with a test data set.""" + x = y = np.arange(-3.0, 3.0, delta) + X, Y = np.meshgrid(x, y) + + Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi) + Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) / + (2 * np.pi * 0.5 * 1.5)) + Z = Z2 - Z1 + + X = X * 10 + Y = Y * 10 + Z = Z * 500 + return X, Y, Z + + +class _Quaternion: + """ + Quaternions + consisting of scalar, along 1, and vector, with components along i, j, k + """ + + def __init__(self, scalar, vector): + self.scalar = scalar + self.vector = np.array(vector) + + def __neg__(self): + return self.__class__(-self.scalar, -self.vector) + + def __mul__(self, other): + """ + Product of two quaternions + i*i = j*j = k*k = i*j*k = -1 + Quaternion multiplication can be expressed concisely + using scalar and vector parts, + see + """ + return self.__class__( + self.scalar*other.scalar - np.dot(self.vector, other.vector), + self.scalar*other.vector + self.vector*other.scalar + + np.cross(self.vector, other.vector)) + + def conjugate(self): + """The conjugate quaternion -(1/2)*(q+i*q*i+j*q*j+k*q*k)""" + return self.__class__(self.scalar, -self.vector) + + @property + def norm(self): + """The 2-norm, q*q', a scalar""" + return self.scalar*self.scalar + np.dot(self.vector, self.vector) + + def normalize(self): + """Scaling such that norm equals 1""" + n = np.sqrt(self.norm) + return self.__class__(self.scalar/n, self.vector/n) + + def reciprocal(self): + """The reciprocal, 1/q = q'/(q*q') = q' / norm(q)""" + n = self.norm + return self.__class__(self.scalar/n, -self.vector/n) + + def __div__(self, other): + return self*other.reciprocal() + + __truediv__ = __div__ + + def rotate(self, v): + # Rotate the vector v by the quaternion q, i.e., + # calculate (the vector part of) q*v/q + v = self.__class__(0, v) + v = self*v/self + return v.vector + + def __eq__(self, other): + return (self.scalar == other.scalar) and (self.vector == other.vector).all + + def __repr__(self): + return "_Quaternion({}, {})".format(repr(self.scalar), repr(self.vector)) + + @classmethod + def rotate_from_to(cls, r1, r2): + """ + The quaternion for the shortest rotation from vector r1 to vector r2 + i.e., q = sqrt(r2*r1'), normalized. + If r1 and r2 are antiparallel, then the result is ambiguous; + a normal vector will be returned, and a warning will be issued. + """ + k = np.cross(r1, r2) + nk = np.linalg.norm(k) + th = np.arctan2(nk, np.dot(r1, r2)) + th /= 2 + if nk == 0: # r1 and r2 are parallel or anti-parallel + if np.dot(r1, r2) < 0: + warnings.warn("Rotation defined by anti-parallel vectors is ambiguous") + k = np.zeros(3) + k[np.argmin(r1*r1)] = 1 # basis vector most perpendicular to r1-r2 + k = np.cross(r1, k) + k = k / np.linalg.norm(k) # unit vector normal to r1-r2 + q = cls(0, k) + else: + q = cls(1, [0, 0, 0]) # = 1, no rotation + else: + q = cls(np.cos(th), k*np.sin(th)/nk) + return q + + @classmethod + def from_cardan_angles(cls, elev, azim, roll): + """ + Converts the angles to a quaternion + q = exp((roll/2)*e_x)*exp((elev/2)*e_y)*exp((-azim/2)*e_z) + i.e., the angles are a kind of Tait-Bryan angles, -z,y',x". + The angles should be given in radians, not degrees. + """ + ca, sa = np.cos(azim/2), np.sin(azim/2) + ce, se = np.cos(elev/2), np.sin(elev/2) + cr, sr = np.cos(roll/2), np.sin(roll/2) + + qw = ca*ce*cr + sa*se*sr + qx = ca*ce*sr - sa*se*cr + qy = ca*se*cr + sa*ce*sr + qz = ca*se*sr - sa*ce*cr + return cls(qw, [qx, qy, qz]) + + def as_cardan_angles(self): + """ + The inverse of `from_cardan_angles()`. + Note that the angles returned are in radians, not degrees. + The angles are not sensitive to the quaternion's norm(). + """ + qw = self.scalar + qx, qy, qz = self.vector[..., :] + azim = np.arctan2(2*(-qw*qz+qx*qy), qw*qw+qx*qx-qy*qy-qz*qz) + elev = np.arcsin(np.clip(2*(qw*qy+qz*qx)/(qw*qw+qx*qx+qy*qy+qz*qz), -1, 1)) + roll = np.arctan2(2*(qw*qx-qy*qz), qw*qw-qx*qx-qy*qy+qz*qz) + return elev, azim, roll diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axis3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axis3d.py new file mode 100644 index 0000000000000000000000000000000000000000..4da5031b990ca742eb0d303003af5c6a821c4db9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/axis3d.py @@ -0,0 +1,750 @@ +# axis3d.py, original mplot3d version by John Porter +# Created: 23 Sep 2005 +# Parts rewritten by Reinier Heeres + +import inspect + +import numpy as np + +import matplotlib as mpl +from matplotlib import ( + _api, artist, lines as mlines, axis as maxis, patches as mpatches, + transforms as mtransforms, colors as mcolors) +from . import art3d, proj3d + + +def _move_from_center(coord, centers, deltas, axmask=(True, True, True)): + """ + For each coordinate where *axmask* is True, move *coord* away from + *centers* by *deltas*. + """ + coord = np.asarray(coord) + return coord + axmask * np.copysign(1, coord - centers) * deltas + + +def _tick_update_position(tick, tickxs, tickys, labelpos): + """Update tick line and label position and style.""" + + tick.label1.set_position(labelpos) + tick.label2.set_position(labelpos) + tick.tick1line.set_visible(True) + tick.tick2line.set_visible(False) + tick.tick1line.set_linestyle('-') + tick.tick1line.set_marker('') + tick.tick1line.set_data(tickxs, tickys) + tick.gridline.set_data([0], [0]) + + +class Axis(maxis.XAxis): + """An Axis class for the 3D plots.""" + # These points from the unit cube make up the x, y and z-planes + _PLANES = ( + (0, 3, 7, 4), (1, 2, 6, 5), # yz planes + (0, 1, 5, 4), (3, 2, 6, 7), # xz planes + (0, 1, 2, 3), (4, 5, 6, 7), # xy planes + ) + + # Some properties for the axes + _AXINFO = { + 'x': {'i': 0, 'tickdir': 1, 'juggled': (1, 0, 2)}, + 'y': {'i': 1, 'tickdir': 0, 'juggled': (0, 1, 2)}, + 'z': {'i': 2, 'tickdir': 0, 'juggled': (0, 2, 1)}, + } + + def _old_init(self, adir, v_intervalx, d_intervalx, axes, *args, + rotate_label=None, **kwargs): + return locals() + + def _new_init(self, axes, *, rotate_label=None, **kwargs): + return locals() + + def __init__(self, *args, **kwargs): + params = _api.select_matching_signature( + [self._old_init, self._new_init], *args, **kwargs) + if "adir" in params: + _api.warn_deprecated( + "3.6", message=f"The signature of 3D Axis constructors has " + f"changed in %(since)s; the new signature is " + f"{inspect.signature(type(self).__init__)}", pending=True) + if params["adir"] != self.axis_name: + raise ValueError(f"Cannot instantiate {type(self).__name__} " + f"with adir={params['adir']!r}") + axes = params["axes"] + rotate_label = params["rotate_label"] + args = params.get("args", ()) + kwargs = params["kwargs"] + + name = self.axis_name + + self._label_position = 'default' + self._tick_position = 'default' + + # This is a temporary member variable. + # Do not depend on this existing in future releases! + self._axinfo = self._AXINFO[name].copy() + # Common parts + self._axinfo.update({ + 'label': {'va': 'center', 'ha': 'center', + 'rotation_mode': 'anchor'}, + 'color': mpl.rcParams[f'axes3d.{name}axis.panecolor'], + 'tick': { + 'inward_factor': 0.2, + 'outward_factor': 0.1, + }, + }) + + if mpl.rcParams['_internal.classic_mode']: + self._axinfo.update({ + 'axisline': {'linewidth': 0.75, 'color': (0, 0, 0, 1)}, + 'grid': { + 'color': (0.9, 0.9, 0.9, 1), + 'linewidth': 1.0, + 'linestyle': '-', + }, + }) + self._axinfo['tick'].update({ + 'linewidth': { + True: mpl.rcParams['lines.linewidth'], # major + False: mpl.rcParams['lines.linewidth'], # minor + } + }) + else: + self._axinfo.update({ + 'axisline': { + 'linewidth': mpl.rcParams['axes.linewidth'], + 'color': mpl.rcParams['axes.edgecolor'], + }, + 'grid': { + 'color': mpl.rcParams['grid.color'], + 'linewidth': mpl.rcParams['grid.linewidth'], + 'linestyle': mpl.rcParams['grid.linestyle'], + }, + }) + self._axinfo['tick'].update({ + 'linewidth': { + True: ( # major + mpl.rcParams['xtick.major.width'] if name in 'xz' + else mpl.rcParams['ytick.major.width']), + False: ( # minor + mpl.rcParams['xtick.minor.width'] if name in 'xz' + else mpl.rcParams['ytick.minor.width']), + } + }) + + super().__init__(axes, *args, **kwargs) + + # data and viewing intervals for this direction + if "d_intervalx" in params: + self.set_data_interval(*params["d_intervalx"]) + if "v_intervalx" in params: + self.set_view_interval(*params["v_intervalx"]) + self.set_rotate_label(rotate_label) + self._init3d() # Inline after init3d deprecation elapses. + + __init__.__signature__ = inspect.signature(_new_init) + adir = _api.deprecated("3.6", pending=True)( + property(lambda self: self.axis_name)) + + def _init3d(self): + self.line = mlines.Line2D( + xdata=(0, 0), ydata=(0, 0), + linewidth=self._axinfo['axisline']['linewidth'], + color=self._axinfo['axisline']['color'], + antialiased=True) + + # Store dummy data in Polygon object + self.pane = mpatches.Polygon([[0, 0], [0, 1]], closed=False) + self.set_pane_color(self._axinfo['color']) + + self.axes._set_artist_props(self.line) + self.axes._set_artist_props(self.pane) + self.gridlines = art3d.Line3DCollection([]) + self.axes._set_artist_props(self.gridlines) + self.axes._set_artist_props(self.label) + self.axes._set_artist_props(self.offsetText) + # Need to be able to place the label at the correct location + self.label._transform = self.axes.transData + self.offsetText._transform = self.axes.transData + + @_api.deprecated("3.6", pending=True) + def init3d(self): # After deprecation elapses, inline _init3d to __init__. + self._init3d() + + def get_major_ticks(self, numticks=None): + ticks = super().get_major_ticks(numticks) + for t in ticks: + for obj in [ + t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: + obj.set_transform(self.axes.transData) + return ticks + + def get_minor_ticks(self, numticks=None): + ticks = super().get_minor_ticks(numticks) + for t in ticks: + for obj in [ + t.tick1line, t.tick2line, t.gridline, t.label1, t.label2]: + obj.set_transform(self.axes.transData) + return ticks + + def set_ticks_position(self, position): + """ + Set the ticks position. + + Parameters + ---------- + position : {'lower', 'upper', 'both', 'default', 'none'} + The position of the bolded axis lines, ticks, and tick labels. + """ + _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], + position=position) + self._tick_position = position + + def get_ticks_position(self): + """ + Get the ticks position. + + Returns + ------- + str : {'lower', 'upper', 'both', 'default', 'none'} + The position of the bolded axis lines, ticks, and tick labels. + """ + return self._tick_position + + def set_label_position(self, position): + """ + Set the label position. + + Parameters + ---------- + position : {'lower', 'upper', 'both', 'default', 'none'} + The position of the axis label. + """ + _api.check_in_list(['lower', 'upper', 'both', 'default', 'none'], + position=position) + self._label_position = position + + def get_label_position(self): + """ + Get the label position. + + Returns + ------- + str : {'lower', 'upper', 'both', 'default', 'none'} + The position of the axis label. + """ + return self._label_position + + def set_pane_color(self, color, alpha=None): + """ + Set pane color. + + Parameters + ---------- + color : :mpltype:`color` + Color for axis pane. + alpha : float, optional + Alpha value for axis pane. If None, base it on *color*. + """ + color = mcolors.to_rgba(color, alpha) + self._axinfo['color'] = color + self.pane.set_edgecolor(color) + self.pane.set_facecolor(color) + self.pane.set_alpha(color[-1]) + self.stale = True + + def set_rotate_label(self, val): + """ + Whether to rotate the axis label: True, False or None. + If set to None the label will be rotated if longer than 4 chars. + """ + self._rotate_label = val + self.stale = True + + def get_rotate_label(self, text): + if self._rotate_label is not None: + return self._rotate_label + else: + return len(text) > 4 + + def _get_coord_info(self): + mins, maxs = np.array([ + self.axes.get_xbound(), + self.axes.get_ybound(), + self.axes.get_zbound(), + ]).T + + # Project the bounds along the current position of the cube: + bounds = mins[0], maxs[0], mins[1], maxs[1], mins[2], maxs[2] + bounds_proj = self.axes._transformed_cube(bounds) + + # Determine which one of the parallel planes are higher up: + means_z0 = np.zeros(3) + means_z1 = np.zeros(3) + for i in range(3): + means_z0[i] = np.mean(bounds_proj[self._PLANES[2 * i], 2]) + means_z1[i] = np.mean(bounds_proj[self._PLANES[2 * i + 1], 2]) + highs = means_z0 < means_z1 + + # Special handling for edge-on views + equals = np.abs(means_z0 - means_z1) <= np.finfo(float).eps + if np.sum(equals) == 2: + vertical = np.where(~equals)[0][0] + if vertical == 2: # looking at XY plane + highs = np.array([True, True, highs[2]]) + elif vertical == 1: # looking at XZ plane + highs = np.array([True, highs[1], False]) + elif vertical == 0: # looking at YZ plane + highs = np.array([highs[0], False, False]) + + return mins, maxs, bounds_proj, highs + + def _calc_centers_deltas(self, maxs, mins): + centers = 0.5 * (maxs + mins) + # In mpl3.8, the scale factor was 1/12. mpl3.9 changes this to + # 1/12 * 24/25 = 0.08 to compensate for the change in automargin + # behavior and keep appearance the same. The 24/25 factor is from the + # 1/48 padding added to each side of the axis in mpl3.8. + scale = 0.08 + deltas = (maxs - mins) * scale + return centers, deltas + + def _get_axis_line_edge_points(self, minmax, maxmin, position=None): + """Get the edge points for the black bolded axis line.""" + # When changing vertical axis some of the axes has to be + # moved to the other plane so it looks the same as if the z-axis + # was the vertical axis. + mb = [minmax, maxmin] # line from origin to nearest corner to camera + mb_rev = mb[::-1] + mm = [[mb, mb_rev, mb_rev], [mb_rev, mb_rev, mb], [mb, mb, mb]] + mm = mm[self.axes._vertical_axis][self._axinfo["i"]] + + juggled = self._axinfo["juggled"] + edge_point_0 = mm[0].copy() # origin point + + if ((position == 'lower' and mm[1][juggled[-1]] < mm[0][juggled[-1]]) or + (position == 'upper' and mm[1][juggled[-1]] > mm[0][juggled[-1]])): + edge_point_0[juggled[-1]] = mm[1][juggled[-1]] + else: + edge_point_0[juggled[0]] = mm[1][juggled[0]] + + edge_point_1 = edge_point_0.copy() + edge_point_1[juggled[1]] = mm[1][juggled[1]] + + return edge_point_0, edge_point_1 + + def _get_all_axis_line_edge_points(self, minmax, maxmin, axis_position=None): + # Determine edge points for the axis lines + edgep1s = [] + edgep2s = [] + position = [] + if axis_position in (None, 'default'): + edgep1, edgep2 = self._get_axis_line_edge_points(minmax, maxmin) + edgep1s = [edgep1] + edgep2s = [edgep2] + position = ['default'] + else: + edgep1_l, edgep2_l = self._get_axis_line_edge_points(minmax, maxmin, + position='lower') + edgep1_u, edgep2_u = self._get_axis_line_edge_points(minmax, maxmin, + position='upper') + if axis_position in ('lower', 'both'): + edgep1s.append(edgep1_l) + edgep2s.append(edgep2_l) + position.append('lower') + if axis_position in ('upper', 'both'): + edgep1s.append(edgep1_u) + edgep2s.append(edgep2_u) + position.append('upper') + return edgep1s, edgep2s, position + + def _get_tickdir(self, position): + """ + Get the direction of the tick. + + Parameters + ---------- + position : str, optional : {'upper', 'lower', 'default'} + The position of the axis. + + Returns + ------- + tickdir : int + Index which indicates which coordinate the tick line will + align with. + """ + _api.check_in_list(('upper', 'lower', 'default'), position=position) + + # TODO: Move somewhere else where it's triggered less: + tickdirs_base = [v["tickdir"] for v in self._AXINFO.values()] # default + elev_mod = np.mod(self.axes.elev + 180, 360) - 180 + azim_mod = np.mod(self.axes.azim, 360) + if position == 'upper': + if elev_mod >= 0: + tickdirs_base = [2, 2, 0] + else: + tickdirs_base = [1, 0, 0] + if 0 <= azim_mod < 180: + tickdirs_base[2] = 1 + elif position == 'lower': + if elev_mod >= 0: + tickdirs_base = [1, 0, 1] + else: + tickdirs_base = [2, 2, 1] + if 0 <= azim_mod < 180: + tickdirs_base[2] = 0 + info_i = [v["i"] for v in self._AXINFO.values()] + + i = self._axinfo["i"] + vert_ax = self.axes._vertical_axis + j = vert_ax - 2 + # default: tickdir = [[1, 2, 1], [2, 2, 0], [1, 0, 0]][vert_ax][i] + tickdir = np.roll(info_i, -j)[np.roll(tickdirs_base, j)][i] + return tickdir + + def active_pane(self): + mins, maxs, tc, highs = self._get_coord_info() + info = self._axinfo + index = info['i'] + if not highs[index]: + loc = mins[index] + plane = self._PLANES[2 * index] + else: + loc = maxs[index] + plane = self._PLANES[2 * index + 1] + xys = np.array([tc[p] for p in plane]) + return xys, loc + + def draw_pane(self, renderer): + """ + Draw pane. + + Parameters + ---------- + renderer : `~matplotlib.backend_bases.RendererBase` subclass + """ + renderer.open_group('pane3d', gid=self.get_gid()) + xys, loc = self.active_pane() + self.pane.xy = xys[:, :2] + self.pane.draw(renderer) + renderer.close_group('pane3d') + + def _axmask(self): + axmask = [True, True, True] + axmask[self._axinfo["i"]] = False + return axmask + + def _draw_ticks(self, renderer, edgep1, centers, deltas, highs, + deltas_per_point, pos): + ticks = self._update_ticks() + info = self._axinfo + index = info["i"] + juggled = info["juggled"] + + mins, maxs, tc, highs = self._get_coord_info() + centers, deltas = self._calc_centers_deltas(maxs, mins) + + # Draw ticks: + tickdir = self._get_tickdir(pos) + tickdelta = deltas[tickdir] if highs[tickdir] else -deltas[tickdir] + + tick_info = info['tick'] + tick_out = tick_info['outward_factor'] * tickdelta + tick_in = tick_info['inward_factor'] * tickdelta + tick_lw = tick_info['linewidth'] + edgep1_tickdir = edgep1[tickdir] + out_tickdir = edgep1_tickdir + tick_out + in_tickdir = edgep1_tickdir - tick_in + + default_label_offset = 8. # A rough estimate + points = deltas_per_point * deltas + for tick in ticks: + # Get tick line positions + pos = edgep1.copy() + pos[index] = tick.get_loc() + pos[tickdir] = out_tickdir + x1, y1, z1 = proj3d.proj_transform(*pos, self.axes.M) + pos[tickdir] = in_tickdir + x2, y2, z2 = proj3d.proj_transform(*pos, self.axes.M) + + # Get position of label + labeldeltas = (tick.get_pad() + default_label_offset) * points + + pos[tickdir] = edgep1_tickdir + pos = _move_from_center(pos, centers, labeldeltas, self._axmask()) + lx, ly, lz = proj3d.proj_transform(*pos, self.axes.M) + + _tick_update_position(tick, (x1, x2), (y1, y2), (lx, ly)) + tick.tick1line.set_linewidth(tick_lw[tick._major]) + tick.draw(renderer) + + def _draw_offset_text(self, renderer, edgep1, edgep2, labeldeltas, centers, + highs, pep, dx, dy): + # Get general axis information: + info = self._axinfo + index = info["i"] + juggled = info["juggled"] + tickdir = info["tickdir"] + + # Which of the two edge points do we want to + # use for locating the offset text? + if juggled[2] == 2: + outeredgep = edgep1 + outerindex = 0 + else: + outeredgep = edgep2 + outerindex = 1 + + pos = _move_from_center(outeredgep, centers, labeldeltas, + self._axmask()) + olx, oly, olz = proj3d.proj_transform(*pos, self.axes.M) + self.offsetText.set_text(self.major.formatter.get_offset()) + self.offsetText.set_position((olx, oly)) + angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) + self.offsetText.set_rotation(angle) + # Must set rotation mode to "anchor" so that + # the alignment point is used as the "fulcrum" for rotation. + self.offsetText.set_rotation_mode('anchor') + + # ---------------------------------------------------------------------- + # Note: the following statement for determining the proper alignment of + # the offset text. This was determined entirely by trial-and-error + # and should not be in any way considered as "the way". There are + # still some edge cases where alignment is not quite right, but this + # seems to be more of a geometry issue (in other words, I might be + # using the wrong reference points). + # + # (TT, FF, TF, FT) are the shorthand for the tuple of + # (centpt[tickdir] <= pep[tickdir, outerindex], + # centpt[index] <= pep[index, outerindex]) + # + # Three-letters (e.g., TFT, FTT) are short-hand for the array of bools + # from the variable 'highs'. + # --------------------------------------------------------------------- + centpt = proj3d.proj_transform(*centers, self.axes.M) + if centpt[tickdir] > pep[tickdir, outerindex]: + # if FT and if highs has an even number of Trues + if (centpt[index] <= pep[index, outerindex] + and np.count_nonzero(highs) % 2 == 0): + # Usually, this means align right, except for the FTT case, + # in which offset for axis 1 and 2 are aligned left. + if highs.tolist() == [False, True, True] and index in (1, 2): + align = 'left' + else: + align = 'right' + else: + # The FF case + align = 'left' + else: + # if TF and if highs has an even number of Trues + if (centpt[index] > pep[index, outerindex] + and np.count_nonzero(highs) % 2 == 0): + # Usually mean align left, except if it is axis 2 + align = 'right' if index == 2 else 'left' + else: + # The TT case + align = 'right' + + self.offsetText.set_va('center') + self.offsetText.set_ha(align) + self.offsetText.draw(renderer) + + def _draw_labels(self, renderer, edgep1, edgep2, labeldeltas, centers, dx, dy): + label = self._axinfo["label"] + + # Draw labels + lxyz = 0.5 * (edgep1 + edgep2) + lxyz = _move_from_center(lxyz, centers, labeldeltas, self._axmask()) + tlx, tly, tlz = proj3d.proj_transform(*lxyz, self.axes.M) + self.label.set_position((tlx, tly)) + if self.get_rotate_label(self.label.get_text()): + angle = art3d._norm_text_angle(np.rad2deg(np.arctan2(dy, dx))) + self.label.set_rotation(angle) + self.label.set_va(label['va']) + self.label.set_ha(label['ha']) + self.label.set_rotation_mode(label['rotation_mode']) + self.label.draw(renderer) + + @artist.allow_rasterization + def draw(self, renderer): + self.label._transform = self.axes.transData + self.offsetText._transform = self.axes.transData + renderer.open_group("axis3d", gid=self.get_gid()) + + # Get general axis information: + mins, maxs, tc, highs = self._get_coord_info() + centers, deltas = self._calc_centers_deltas(maxs, mins) + + # Calculate offset distances + # A rough estimate; points are ambiguous since 3D plots rotate + reltoinches = self.get_figure(root=False).dpi_scale_trans.inverted() + ax_inches = reltoinches.transform(self.axes.bbox.size) + ax_points_estimate = sum(72. * ax_inches) + deltas_per_point = 48 / ax_points_estimate + default_offset = 21. + labeldeltas = (self.labelpad + default_offset) * deltas_per_point * deltas + + # Determine edge points for the axis lines + minmax = np.where(highs, maxs, mins) # "origin" point + maxmin = np.where(~highs, maxs, mins) # "opposite" corner near camera + + for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points( + minmax, maxmin, self._tick_position)): + # Project the edge points along the current position + pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) + pep = np.asarray(pep) + + # The transAxes transform is used because the Text object + # rotates the text relative to the display coordinate system. + # Therefore, if we want the labels to remain parallel to the + # axis regardless of the aspect ratio, we need to convert the + # edge points of the plane to display coordinates and calculate + # an angle from that. + # TODO: Maybe Text objects should handle this themselves? + dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) - + self.axes.transAxes.transform([pep[0:2, 0]]))[0] + + # Draw the lines + self.line.set_data(pep[0], pep[1]) + self.line.draw(renderer) + + # Draw ticks + self._draw_ticks(renderer, edgep1, centers, deltas, highs, + deltas_per_point, pos) + + # Draw Offset text + self._draw_offset_text(renderer, edgep1, edgep2, labeldeltas, + centers, highs, pep, dx, dy) + + for edgep1, edgep2, pos in zip(*self._get_all_axis_line_edge_points( + minmax, maxmin, self._label_position)): + # See comments above + pep = proj3d._proj_trans_points([edgep1, edgep2], self.axes.M) + pep = np.asarray(pep) + dx, dy = (self.axes.transAxes.transform([pep[0:2, 1]]) - + self.axes.transAxes.transform([pep[0:2, 0]]))[0] + + # Draw labels + self._draw_labels(renderer, edgep1, edgep2, labeldeltas, centers, dx, dy) + + renderer.close_group('axis3d') + self.stale = False + + @artist.allow_rasterization + def draw_grid(self, renderer): + if not self.axes._draw_grid: + return + + renderer.open_group("grid3d", gid=self.get_gid()) + + ticks = self._update_ticks() + if len(ticks): + # Get general axis information: + info = self._axinfo + index = info["i"] + + mins, maxs, tc, highs = self._get_coord_info() + + minmax = np.where(highs, maxs, mins) + maxmin = np.where(~highs, maxs, mins) + + # Grid points where the planes meet + xyz0 = np.tile(minmax, (len(ticks), 1)) + xyz0[:, index] = [tick.get_loc() for tick in ticks] + + # Grid lines go from the end of one plane through the plane + # intersection (at xyz0) to the end of the other plane. The first + # point (0) differs along dimension index-2 and the last (2) along + # dimension index-1. + lines = np.stack([xyz0, xyz0, xyz0], axis=1) + lines[:, 0, index - 2] = maxmin[index - 2] + lines[:, 2, index - 1] = maxmin[index - 1] + self.gridlines.set_segments(lines) + gridinfo = info['grid'] + self.gridlines.set_color(gridinfo['color']) + self.gridlines.set_linewidth(gridinfo['linewidth']) + self.gridlines.set_linestyle(gridinfo['linestyle']) + self.gridlines.do_3d_projection() + self.gridlines.draw(renderer) + + renderer.close_group('grid3d') + + # TODO: Get this to work (more) properly when mplot3d supports the + # transforms framework. + def get_tightbbox(self, renderer=None, *, for_layout_only=False): + # docstring inherited + if not self.get_visible(): + return + # We have to directly access the internal data structures + # (and hope they are up to date) because at draw time we + # shift the ticks and their labels around in (x, y) space + # based on the projection, the current view port, and their + # position in 3D space. If we extend the transforms framework + # into 3D we would not need to do this different book keeping + # than we do in the normal axis + major_locs = self.get_majorticklocs() + minor_locs = self.get_minorticklocs() + + ticks = [*self.get_minor_ticks(len(minor_locs)), + *self.get_major_ticks(len(major_locs))] + view_low, view_high = self.get_view_interval() + if view_low > view_high: + view_low, view_high = view_high, view_low + interval_t = self.get_transform().transform([view_low, view_high]) + + ticks_to_draw = [] + for tick in ticks: + try: + loc_t = self.get_transform().transform(tick.get_loc()) + except AssertionError: + # Transform.transform doesn't allow masked values but + # some scales might make them, so we need this try/except. + pass + else: + if mtransforms._interval_contains_close(interval_t, loc_t): + ticks_to_draw.append(tick) + + ticks = ticks_to_draw + + bb_1, bb_2 = self._get_ticklabel_bboxes(ticks, renderer) + other = [] + + if self.line.get_visible(): + other.append(self.line.get_window_extent(renderer)) + if (self.label.get_visible() and not for_layout_only and + self.label.get_text()): + other.append(self.label.get_window_extent(renderer)) + + return mtransforms.Bbox.union([*bb_1, *bb_2, *other]) + + d_interval = _api.deprecated( + "3.6", alternative="get_data_interval", pending=True)( + property(lambda self: self.get_data_interval(), + lambda self, minmax: self.set_data_interval(*minmax))) + v_interval = _api.deprecated( + "3.6", alternative="get_view_interval", pending=True)( + property(lambda self: self.get_view_interval(), + lambda self, minmax: self.set_view_interval(*minmax))) + + +class XAxis(Axis): + axis_name = "x" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "xy_viewLim", "intervalx") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "xy_dataLim", "intervalx") + + +class YAxis(Axis): + axis_name = "y" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "xy_viewLim", "intervaly") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "xy_dataLim", "intervaly") + + +class ZAxis(Axis): + axis_name = "z" + get_view_interval, set_view_interval = maxis._make_getset_interval( + "view", "zz_viewLim", "intervalx") + get_data_interval, set_data_interval = maxis._make_getset_interval( + "data", "zz_dataLim", "intervalx") diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/proj3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/proj3d.py new file mode 100644 index 0000000000000000000000000000000000000000..923bd32c9ce032ad27379f8d8c6436564ec16d75 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/proj3d.py @@ -0,0 +1,219 @@ +""" +Various transforms used for by the 3D code +""" + +import numpy as np + +from matplotlib import _api + + +def world_transformation(xmin, xmax, + ymin, ymax, + zmin, zmax, pb_aspect=None): + """ + Produce a matrix that scales homogeneous coords in the specified ranges + to [0, 1], or [0, pb_aspect[i]] if the plotbox aspect ratio is specified. + """ + dx = xmax - xmin + dy = ymax - ymin + dz = zmax - zmin + if pb_aspect is not None: + ax, ay, az = pb_aspect + dx /= ax + dy /= ay + dz /= az + + return np.array([[1/dx, 0, 0, -xmin/dx], + [ 0, 1/dy, 0, -ymin/dy], + [ 0, 0, 1/dz, -zmin/dz], + [ 0, 0, 0, 1]]) + + +def _rotation_about_vector(v, angle): + """ + Produce a rotation matrix for an angle in radians about a vector. + """ + vx, vy, vz = v / np.linalg.norm(v) + s = np.sin(angle) + c = np.cos(angle) + t = 2*np.sin(angle/2)**2 # more numerically stable than t = 1-c + + R = np.array([ + [t*vx*vx + c, t*vx*vy - vz*s, t*vx*vz + vy*s], + [t*vy*vx + vz*s, t*vy*vy + c, t*vy*vz - vx*s], + [t*vz*vx - vy*s, t*vz*vy + vx*s, t*vz*vz + c]]) + + return R + + +def _view_axes(E, R, V, roll): + """ + Get the unit viewing axes in data coordinates. + + Parameters + ---------- + E : 3-element numpy array + The coordinates of the eye/camera. + R : 3-element numpy array + The coordinates of the center of the view box. + V : 3-element numpy array + Unit vector in the direction of the vertical axis. + roll : float + The roll angle in radians. + + Returns + ------- + u : 3-element numpy array + Unit vector pointing towards the right of the screen. + v : 3-element numpy array + Unit vector pointing towards the top of the screen. + w : 3-element numpy array + Unit vector pointing out of the screen. + """ + w = (E - R) + w = w/np.linalg.norm(w) + u = np.cross(V, w) + u = u/np.linalg.norm(u) + v = np.cross(w, u) # Will be a unit vector + + # Save some computation for the default roll=0 + if roll != 0: + # A positive rotation of the camera is a negative rotation of the world + Rroll = _rotation_about_vector(w, -roll) + u = np.dot(Rroll, u) + v = np.dot(Rroll, v) + return u, v, w + + +def _view_transformation_uvw(u, v, w, E): + """ + Return the view transformation matrix. + + Parameters + ---------- + u : 3-element numpy array + Unit vector pointing towards the right of the screen. + v : 3-element numpy array + Unit vector pointing towards the top of the screen. + w : 3-element numpy array + Unit vector pointing out of the screen. + E : 3-element numpy array + The coordinates of the eye/camera. + """ + Mr = np.eye(4) + Mt = np.eye(4) + Mr[:3, :3] = [u, v, w] + Mt[:3, -1] = -E + M = np.dot(Mr, Mt) + return M + + +def _persp_transformation(zfront, zback, focal_length): + e = focal_length + a = 1 # aspect ratio + b = (zfront+zback)/(zfront-zback) + c = -2*(zfront*zback)/(zfront-zback) + proj_matrix = np.array([[e, 0, 0, 0], + [0, e/a, 0, 0], + [0, 0, b, c], + [0, 0, -1, 0]]) + return proj_matrix + + +def _ortho_transformation(zfront, zback): + # note: w component in the resulting vector will be (zback-zfront), not 1 + a = -(zfront + zback) + b = -(zfront - zback) + proj_matrix = np.array([[2, 0, 0, 0], + [0, 2, 0, 0], + [0, 0, -2, 0], + [0, 0, a, b]]) + return proj_matrix + + +def _proj_transform_vec(vec, M): + vecw = np.dot(M, vec.data) + w = vecw[3] + txs, tys, tzs = vecw[0]/w, vecw[1]/w, vecw[2]/w + if np.ma.isMA(vec[0]): # we check each to protect for scalars + txs = np.ma.array(txs, mask=vec[0].mask) + if np.ma.isMA(vec[1]): + tys = np.ma.array(tys, mask=vec[1].mask) + if np.ma.isMA(vec[2]): + tzs = np.ma.array(tzs, mask=vec[2].mask) + return txs, tys, tzs + + +def _proj_transform_vec_clip(vec, M, focal_length): + vecw = np.dot(M, vec.data) + w = vecw[3] + txs, tys, tzs = vecw[0] / w, vecw[1] / w, vecw[2] / w + if np.isinf(focal_length): # don't clip orthographic projection + tis = np.ones(txs.shape, dtype=bool) + else: + tis = (-1 <= txs) & (txs <= 1) & (-1 <= tys) & (tys <= 1) & (tzs <= 0) + if np.ma.isMA(vec[0]): + tis = tis & ~vec[0].mask + if np.ma.isMA(vec[1]): + tis = tis & ~vec[1].mask + if np.ma.isMA(vec[2]): + tis = tis & ~vec[2].mask + + txs = np.ma.masked_array(txs, ~tis) + tys = np.ma.masked_array(tys, ~tis) + tzs = np.ma.masked_array(tzs, ~tis) + return txs, tys, tzs, tis + + +def inv_transform(xs, ys, zs, invM): + """ + Transform the points by the inverse of the projection matrix, *invM*. + """ + vec = _vec_pad_ones(xs, ys, zs) + vecr = np.dot(invM, vec) + if vecr.shape == (4,): + vecr = vecr.reshape((4, 1)) + for i in range(vecr.shape[1]): + if vecr[3][i] != 0: + vecr[:, i] = vecr[:, i] / vecr[3][i] + return vecr[0], vecr[1], vecr[2] + + +def _vec_pad_ones(xs, ys, zs): + if np.ma.isMA(xs) or np.ma.isMA(ys) or np.ma.isMA(zs): + return np.ma.array([xs, ys, zs, np.ones_like(xs)]) + else: + return np.array([xs, ys, zs, np.ones_like(xs)]) + + +def proj_transform(xs, ys, zs, M): + """ + Transform the points by the projection matrix *M*. + """ + vec = _vec_pad_ones(xs, ys, zs) + return _proj_transform_vec(vec, M) + + +@_api.deprecated("3.10") +def proj_transform_clip(xs, ys, zs, M): + return _proj_transform_clip(xs, ys, zs, M, focal_length=np.inf) + + +def _proj_transform_clip(xs, ys, zs, M, focal_length): + """ + Transform the points by the projection matrix + and return the clipping result + returns txs, tys, tzs, tis + """ + vec = _vec_pad_ones(xs, ys, zs) + return _proj_transform_vec_clip(vec, M, focal_length) + + +def _proj_points(points, M): + return np.column_stack(_proj_trans_points(points, M)) + + +def _proj_trans_points(points, M): + points = np.asanyarray(points) + xs, ys, zs = points[:, 0], points[:, 1], points[:, 2] + return proj_transform(xs, ys, zs, M) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__init__.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ea4d8ed16a6a24a8c15ab2956ef678a7f256cd80 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__init__.py @@ -0,0 +1,10 @@ +from pathlib import Path + + +# Check that the test directories exist +if not (Path(__file__).parent / "baseline_images").exists(): + raise OSError( + 'The baseline image directory does not exist. ' + 'This is most likely because the test data is not installed. ' + 'You may need to install matplotlib from source to get the ' + 'test data.') diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc6d48d0f86ec3b54003bd3d90b3554b8daa7505 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/conftest.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/conftest.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93ece931bda3511ca886bde2f0f3da8997d2b1b6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/conftest.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_art3d.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_art3d.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5dcf86a25b1406a0de6694c24bc43452395182c9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_art3d.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_legend3d.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_legend3d.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d35a3e1fe7ed5a887ee05ad0f4cbfd9016b05ee5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/__pycache__/test_legend3d.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/conftest.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..61c2de3e07bac4db323f8704961264d123e01544 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/conftest.py @@ -0,0 +1,2 @@ +from matplotlib.testing.conftest import (mpl_test_settings, # noqa + pytest_configure, pytest_unconfigure) diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_art3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_art3d.py new file mode 100644 index 0000000000000000000000000000000000000000..174c12608ae933c1b918f45e57abfe6a2fb552bd --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_art3d.py @@ -0,0 +1,102 @@ +import numpy as np + +import matplotlib.pyplot as plt + +from matplotlib.backend_bases import MouseEvent +from mpl_toolkits.mplot3d.art3d import ( + Line3DCollection, + Poly3DCollection, + _all_points_on_plane, +) + + +def test_scatter_3d_projection_conservation(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + # fix axes3d projection + ax.roll = 0 + ax.elev = 0 + ax.azim = -45 + ax.stale = True + + x = [0, 1, 2, 3, 4] + scatter_collection = ax.scatter(x, x, x) + fig.canvas.draw_idle() + + # Get scatter location on canvas and freeze the data + scatter_offset = scatter_collection.get_offsets() + scatter_location = ax.transData.transform(scatter_offset) + + # Yaw -44 and -46 are enough to produce two set of scatter + # with opposite z-order without moving points too far + for azim in (-44, -46): + ax.azim = azim + ax.stale = True + fig.canvas.draw_idle() + + for i in range(5): + # Create a mouse event used to locate and to get index + # from each dots + event = MouseEvent("button_press_event", fig.canvas, + *scatter_location[i, :]) + contains, ind = scatter_collection.contains(event) + assert contains is True + assert len(ind["ind"]) == 1 + assert ind["ind"][0] == i + + +def test_zordered_error(): + # Smoke test for https://github.com/matplotlib/matplotlib/issues/26497 + lc = [(np.fromiter([0.0, 0.0, 0.0], dtype="float"), + np.fromiter([1.0, 1.0, 1.0], dtype="float"))] + pc = [np.fromiter([0.0, 0.0], dtype="float"), + np.fromiter([0.0, 1.0], dtype="float"), + np.fromiter([1.0, 1.0], dtype="float")] + + fig = plt.figure() + ax = fig.add_subplot(projection="3d") + ax.add_collection(Line3DCollection(lc)) + ax.scatter(*pc, visible=False) + plt.draw() + + +def test_all_points_on_plane(): + # Non-coplanar points + points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1]]) + assert not _all_points_on_plane(*points.T) + + # Duplicate points + points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 0]]) + assert _all_points_on_plane(*points.T) + + # NaN values + points = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, np.nan]]) + assert _all_points_on_plane(*points.T) + + # Less than 3 unique points + points = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 0]]) + assert _all_points_on_plane(*points.T) + + # All points lie on a line + points = np.array([[0, 0, 0], [0, 1, 0], [0, 2, 0], [0, 3, 0]]) + assert _all_points_on_plane(*points.T) + + # All points lie on two lines, with antiparallel vectors + points = np.array([[-2, 2, 0], [-1, 1, 0], [1, -1, 0], + [0, 0, 0], [2, 0, 0], [1, 0, 0]]) + assert _all_points_on_plane(*points.T) + + # All points lie on a plane + points = np.array([[0, 0, 0], [0, 1, 0], [1, 0, 0], [1, 1, 0], [1, 2, 0]]) + assert _all_points_on_plane(*points.T) + + +def test_generate_normals(): + # Smoke test for https://github.com/matplotlib/matplotlib/issues/29156 + vertices = ((0, 0, 0), (0, 5, 0), (5, 5, 0), (5, 0, 0)) + shape = Poly3DCollection([vertices], edgecolors='r', shade=True) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.add_collection3d(shape) + plt.draw() diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_axes3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_axes3d.py new file mode 100644 index 0000000000000000000000000000000000000000..b30c2556b105e70e3e08fa3877c712f78f09d95c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_axes3d.py @@ -0,0 +1,2688 @@ +import functools +import itertools +import platform +import sys + +import pytest + +from mpl_toolkits.mplot3d import Axes3D, axes3d, proj3d, art3d +from mpl_toolkits.mplot3d.axes3d import _Quaternion as Quaternion +import matplotlib as mpl +from matplotlib.backend_bases import (MouseButton, MouseEvent, + NavigationToolbar2) +from matplotlib import cm +from matplotlib import colors as mcolors, patches as mpatch +from matplotlib.testing.decorators import image_comparison, check_figures_equal +from matplotlib.testing.widgets import mock_event +from matplotlib.collections import LineCollection, PolyCollection +from matplotlib.patches import Circle, PathPatch +from matplotlib.path import Path +from matplotlib.text import Text + +import matplotlib.pyplot as plt +import numpy as np + + +mpl3d_image_comparison = functools.partial( + image_comparison, remove_text=True, style='default') + + +def plot_cuboid(ax, scale): + # plot a rectangular cuboid with side lengths given by scale (x, y, z) + r = [0, 1] + pts = itertools.combinations(np.array(list(itertools.product(r, r, r))), 2) + for start, end in pts: + if np.sum(np.abs(start - end)) == r[1] - r[0]: + ax.plot3D(*zip(start*np.array(scale), end*np.array(scale))) + + +@check_figures_equal(extensions=["png"]) +def test_invisible_axes(fig_test, fig_ref): + ax = fig_test.subplots(subplot_kw=dict(projection='3d')) + ax.set_visible(False) + + +@mpl3d_image_comparison(['grid_off.png'], style='mpl20') +def test_grid_off(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.grid(False) + + +@mpl3d_image_comparison(['invisible_ticks_axis.png'], style='mpl20') +def test_invisible_ticks_axis(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.set_xticks([]) + ax.set_yticks([]) + ax.set_zticks([]) + for axis in [ax.xaxis, ax.yaxis, ax.zaxis]: + axis.line.set_visible(False) + + +@mpl3d_image_comparison(['axis_positions.png'], remove_text=False, style='mpl20') +def test_axis_positions(): + positions = ['upper', 'lower', 'both', 'none'] + fig, axs = plt.subplots(2, 2, subplot_kw={'projection': '3d'}) + for ax, pos in zip(axs.flatten(), positions): + for axis in ax.xaxis, ax.yaxis, ax.zaxis: + axis.set_label_position(pos) + axis.set_ticks_position(pos) + title = f'{pos}' + ax.set(xlabel='x', ylabel='y', zlabel='z', title=title) + + +@mpl3d_image_comparison(['aspects.png'], remove_text=False, style='mpl20') +def test_aspects(): + aspects = ('auto', 'equal', 'equalxy', 'equalyz', 'equalxz', 'equal') + _, axs = plt.subplots(2, 3, subplot_kw={'projection': '3d'}) + + for ax in axs.flatten()[0:-1]: + plot_cuboid(ax, scale=[1, 1, 5]) + # plot a cube as well to cover github #25443 + plot_cuboid(axs[1][2], scale=[1, 1, 1]) + + for i, ax in enumerate(axs.flatten()): + ax.set_title(aspects[i]) + ax.set_box_aspect((3, 4, 5)) + ax.set_aspect(aspects[i], adjustable='datalim') + axs[1][2].set_title('equal (cube)') + + +@mpl3d_image_comparison(['aspects_adjust_box.png'], + remove_text=False, style='mpl20') +def test_aspects_adjust_box(): + aspects = ('auto', 'equal', 'equalxy', 'equalyz', 'equalxz') + fig, axs = plt.subplots(1, len(aspects), subplot_kw={'projection': '3d'}, + figsize=(11, 3)) + + for i, ax in enumerate(axs): + plot_cuboid(ax, scale=[4, 3, 5]) + ax.set_title(aspects[i]) + ax.set_aspect(aspects[i], adjustable='box') + + +def test_axes3d_repr(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.set_label('label') + ax.set_title('title') + ax.set_xlabel('x') + ax.set_ylabel('y') + ax.set_zlabel('z') + assert repr(ax) == ( + "") + + +@mpl3d_image_comparison(['axes3d_primary_views.png'], style='mpl20', + tol=0.05 if sys.platform == "darwin" else 0) +def test_axes3d_primary_views(): + # (elev, azim, roll) + views = [(90, -90, 0), # XY + (0, -90, 0), # XZ + (0, 0, 0), # YZ + (-90, 90, 0), # -XY + (0, 90, 0), # -XZ + (0, 180, 0)] # -YZ + # When viewing primary planes, draw the two visible axes so they intersect + # at their low values + fig, axs = plt.subplots(2, 3, subplot_kw={'projection': '3d'}) + for i, ax in enumerate(axs.flat): + ax.set_xlabel('x') + ax.set_ylabel('y') + ax.set_zlabel('z') + ax.set_proj_type('ortho') + ax.view_init(elev=views[i][0], azim=views[i][1], roll=views[i][2]) + plt.tight_layout() + + +@mpl3d_image_comparison(['bar3d.png'], style='mpl20') +def test_bar3d(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + for c, z in zip(['r', 'g', 'b', 'y'], [30, 20, 10, 0]): + xs = np.arange(20) + ys = np.arange(20) + cs = [c] * len(xs) + cs[0] = 'c' + ax.bar(xs, ys, zs=z, zdir='y', align='edge', color=cs, alpha=0.8) + + +def test_bar3d_colors(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + for c in ['red', 'green', 'blue', 'yellow']: + xs = np.arange(len(c)) + ys = np.zeros_like(xs) + zs = np.zeros_like(ys) + # Color names with same length as xs/ys/zs should not be split into + # individual letters. + ax.bar3d(xs, ys, zs, 1, 1, 1, color=c) + + +@mpl3d_image_comparison(['bar3d_shaded.png'], style='mpl20') +def test_bar3d_shaded(): + x = np.arange(4) + y = np.arange(5) + x2d, y2d = np.meshgrid(x, y) + x2d, y2d = x2d.ravel(), y2d.ravel() + z = x2d + y2d + 1 # Avoid triggering bug with zero-depth boxes. + + views = [(30, -60, 0), (30, 30, 30), (-30, 30, -90), (300, -30, 0)] + fig = plt.figure(figsize=plt.figaspect(1 / len(views))) + axs = fig.subplots( + 1, len(views), + subplot_kw=dict(projection='3d') + ) + for ax, (elev, azim, roll) in zip(axs, views): + ax.bar3d(x2d, y2d, x2d * 0, 1, 1, z, shade=True) + ax.view_init(elev=elev, azim=azim, roll=roll) + fig.canvas.draw() + + +@mpl3d_image_comparison(['bar3d_notshaded.png'], style='mpl20') +def test_bar3d_notshaded(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + x = np.arange(4) + y = np.arange(5) + x2d, y2d = np.meshgrid(x, y) + x2d, y2d = x2d.ravel(), y2d.ravel() + z = x2d + y2d + ax.bar3d(x2d, y2d, x2d * 0, 1, 1, z, shade=False) + fig.canvas.draw() + + +def test_bar3d_lightsource(): + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection="3d") + + ls = mcolors.LightSource(azdeg=0, altdeg=90) + + length, width = 3, 4 + area = length * width + + x, y = np.meshgrid(np.arange(length), np.arange(width)) + x = x.ravel() + y = y.ravel() + dz = x + y + + color = [cm.coolwarm(i/area) for i in range(area)] + + collection = ax.bar3d(x=x, y=y, z=0, + dx=1, dy=1, dz=dz, + color=color, shade=True, lightsource=ls) + + # Testing that the custom 90° lightsource produces different shading on + # the top facecolors compared to the default, and that those colors are + # precisely (within floating point rounding errors of 4 ULP) the colors + # from the colormap, due to the illumination parallel to the z-axis. + np.testing.assert_array_max_ulp(color, collection._facecolor3d[1::6], 4) + + +@mpl3d_image_comparison(['contour3d.png'], style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.002) +def test_contour3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) + ax.contour(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) + ax.contour(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) + ax.axis(xmin=-40, xmax=40, ymin=-40, ymax=40, zmin=-100, zmax=100) + + +@mpl3d_image_comparison(['contour3d_extend3d.png'], style='mpl20') +def test_contour3d_extend3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.contour(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm, extend3d=True) + ax.set_xlim(-30, 30) + ax.set_ylim(-20, 40) + ax.set_zlim(-80, 80) + + +@mpl3d_image_comparison(['contourf3d.png'], style='mpl20') +def test_contourf3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.contourf(X, Y, Z, zdir='z', offset=-100, cmap=cm.coolwarm) + ax.contourf(X, Y, Z, zdir='x', offset=-40, cmap=cm.coolwarm) + ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm) + ax.set_xlim(-40, 40) + ax.set_ylim(-40, 40) + ax.set_zlim(-100, 100) + + +@mpl3d_image_comparison(['contourf3d_fill.png'], style='mpl20') +def test_contourf3d_fill(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y = np.meshgrid(np.arange(-2, 2, 0.25), np.arange(-2, 2, 0.25)) + Z = X.clip(0, 0) + # This produces holes in the z=0 surface that causes rendering errors if + # the Poly3DCollection is not aware of path code information (issue #4784) + Z[::5, ::5] = 0.1 + ax.contourf(X, Y, Z, offset=0, levels=[-0.1, 0], cmap=cm.coolwarm) + ax.set_xlim(-2, 2) + ax.set_ylim(-2, 2) + ax.set_zlim(-1, 1) + + +@pytest.mark.parametrize('extend, levels', [['both', [2, 4, 6]], + ['min', [2, 4, 6, 8]], + ['max', [0, 2, 4, 6]]]) +@check_figures_equal(extensions=["png"]) +def test_contourf3d_extend(fig_test, fig_ref, extend, levels): + X, Y = np.meshgrid(np.arange(-2, 2, 0.25), np.arange(-2, 2, 0.25)) + # Z is in the range [0, 8] + Z = X**2 + Y**2 + + # Manually set the over/under colors to be the end of the colormap + cmap = mpl.colormaps['viridis'].copy() + cmap.set_under(cmap(0)) + cmap.set_over(cmap(255)) + # Set vmin/max to be the min/max values plotted on the reference image + kwargs = {'vmin': 1, 'vmax': 7, 'cmap': cmap} + + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.contourf(X, Y, Z, levels=[0, 2, 4, 6, 8], **kwargs) + + ax_test = fig_test.add_subplot(projection='3d') + ax_test.contourf(X, Y, Z, levels, extend=extend, **kwargs) + + for ax in [ax_ref, ax_test]: + ax.set_xlim(-2, 2) + ax.set_ylim(-2, 2) + ax.set_zlim(-10, 10) + + +@mpl3d_image_comparison(['tricontour.png'], tol=0.02, style='mpl20') +def test_tricontour(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + + np.random.seed(19680801) + x = np.random.rand(1000) - 0.5 + y = np.random.rand(1000) - 0.5 + z = -(x**2 + y**2) + + ax = fig.add_subplot(1, 2, 1, projection='3d') + ax.tricontour(x, y, z) + ax = fig.add_subplot(1, 2, 2, projection='3d') + ax.tricontourf(x, y, z) + + +def test_contour3d_1d_input(): + # Check that 1D sequences of different length for {x, y} doesn't error + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + nx, ny = 30, 20 + x = np.linspace(-10, 10, nx) + y = np.linspace(-10, 10, ny) + z = np.random.randint(0, 2, [ny, nx]) + ax.contour(x, y, z, [0.5]) + + +@mpl3d_image_comparison(['lines3d.png'], style='mpl20') +def test_lines3d(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) + z = np.linspace(-2, 2, 100) + r = z ** 2 + 1 + x = r * np.sin(theta) + y = r * np.cos(theta) + ax.plot(x, y, z) + + +@check_figures_equal(extensions=["png"]) +def test_plot_scalar(fig_test, fig_ref): + ax1 = fig_test.add_subplot(projection='3d') + ax1.plot([1], [1], "o") + ax2 = fig_ref.add_subplot(projection='3d') + ax2.plot(1, 1, "o") + + +def test_invalid_line_data(): + with pytest.raises(RuntimeError, match='x must be'): + art3d.Line3D(0, [], []) + with pytest.raises(RuntimeError, match='y must be'): + art3d.Line3D([], 0, []) + with pytest.raises(RuntimeError, match='z must be'): + art3d.Line3D([], [], 0) + + line = art3d.Line3D([], [], []) + with pytest.raises(RuntimeError, match='x must be'): + line.set_data_3d(0, [], []) + with pytest.raises(RuntimeError, match='y must be'): + line.set_data_3d([], 0, []) + with pytest.raises(RuntimeError, match='z must be'): + line.set_data_3d([], [], 0) + + +@mpl3d_image_comparison(['mixedsubplot.png'], style='mpl20') +def test_mixedsubplots(): + def f(t): + return np.cos(2*np.pi*t) * np.exp(-t) + + t1 = np.arange(0.0, 5.0, 0.1) + t2 = np.arange(0.0, 5.0, 0.02) + + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure(figsize=plt.figaspect(2.)) + ax = fig.add_subplot(2, 1, 1) + ax.plot(t1, f(t1), 'bo', t2, f(t2), 'k--', markerfacecolor='green') + ax.grid(True) + + ax = fig.add_subplot(2, 1, 2, projection='3d') + X, Y = np.meshgrid(np.arange(-5, 5, 0.25), np.arange(-5, 5, 0.25)) + R = np.hypot(X, Y) + Z = np.sin(R) + + ax.plot_surface(X, Y, Z, rcount=40, ccount=40, + linewidth=0, antialiased=False) + + ax.set_zlim3d(-1, 1) + + +@check_figures_equal(extensions=['png']) +def test_tight_layout_text(fig_test, fig_ref): + # text is currently ignored in tight layout. So the order of text() and + # tight_layout() calls should not influence the result. + ax1 = fig_test.add_subplot(projection='3d') + ax1.text(.5, .5, .5, s='some string') + fig_test.tight_layout() + + ax2 = fig_ref.add_subplot(projection='3d') + fig_ref.tight_layout() + ax2.text(.5, .5, .5, s='some string') + + +@mpl3d_image_comparison(['scatter3d.png'], style='mpl20') +def test_scatter3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.scatter(np.arange(10), np.arange(10), np.arange(10), + c='r', marker='o') + x = y = z = np.arange(10, 20) + ax.scatter(x, y, z, c='b', marker='^') + z[-1] = 0 # Check that scatter() copies the data. + # Ensure empty scatters do not break. + ax.scatter([], [], [], c='r', marker='X') + + +@mpl3d_image_comparison(['scatter3d_color.png'], style='mpl20') +def test_scatter3d_color(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + # Check that 'none' color works; these two should overlay to produce the + # same as setting just `color`. + ax.scatter(np.arange(10), np.arange(10), np.arange(10), + facecolor='r', edgecolor='none', marker='o') + ax.scatter(np.arange(10), np.arange(10), np.arange(10), + facecolor='none', edgecolor='r', marker='o') + + ax.scatter(np.arange(10, 20), np.arange(10, 20), np.arange(10, 20), + color='b', marker='s') + + +@mpl3d_image_comparison(['scatter3d_linewidth.png'], style='mpl20') +def test_scatter3d_linewidth(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + # Check that array-like linewidth can be set + ax.scatter(np.arange(10), np.arange(10), np.arange(10), + marker='o', linewidth=np.arange(10)) + + +@check_figures_equal(extensions=['png']) +def test_scatter3d_linewidth_modification(fig_ref, fig_test): + # Changing Path3DCollection linewidths with array-like post-creation + # should work correctly. + ax_test = fig_test.add_subplot(projection='3d') + c = ax_test.scatter(np.arange(10), np.arange(10), np.arange(10), + marker='o') + c.set_linewidths(np.arange(10)) + + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.scatter(np.arange(10), np.arange(10), np.arange(10), marker='o', + linewidths=np.arange(10)) + + +@check_figures_equal(extensions=['png']) +def test_scatter3d_modification(fig_ref, fig_test): + # Changing Path3DCollection properties post-creation should work correctly. + ax_test = fig_test.add_subplot(projection='3d') + c = ax_test.scatter(np.arange(10), np.arange(10), np.arange(10), + marker='o') + c.set_facecolor('C1') + c.set_edgecolor('C2') + c.set_alpha([0.3, 0.7] * 5) + assert c.get_depthshade() + c.set_depthshade(False) + assert not c.get_depthshade() + c.set_sizes(np.full(10, 75)) + c.set_linewidths(3) + + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.scatter(np.arange(10), np.arange(10), np.arange(10), marker='o', + facecolor='C1', edgecolor='C2', alpha=[0.3, 0.7] * 5, + depthshade=False, s=75, linewidths=3) + + +@pytest.mark.parametrize('depthshade', [True, False]) +@check_figures_equal(extensions=['png']) +def test_scatter3d_sorting(fig_ref, fig_test, depthshade): + """Test that marker properties are correctly sorted.""" + + y, x = np.mgrid[:10, :10] + z = np.arange(x.size).reshape(x.shape) + + sizes = np.full(z.shape, 25) + sizes[0::2, 0::2] = 100 + sizes[1::2, 1::2] = 100 + + facecolors = np.full(z.shape, 'C0') + facecolors[:5, :5] = 'C1' + facecolors[6:, :4] = 'C2' + facecolors[6:, 6:] = 'C3' + + edgecolors = np.full(z.shape, 'C4') + edgecolors[1:5, 1:5] = 'C5' + edgecolors[5:9, 1:5] = 'C6' + edgecolors[5:9, 5:9] = 'C7' + + linewidths = np.full(z.shape, 2) + linewidths[0::2, 0::2] = 5 + linewidths[1::2, 1::2] = 5 + + x, y, z, sizes, facecolors, edgecolors, linewidths = ( + a.flatten() + for a in [x, y, z, sizes, facecolors, edgecolors, linewidths] + ) + + ax_ref = fig_ref.add_subplot(projection='3d') + sets = (np.unique(a) for a in [sizes, facecolors, edgecolors, linewidths]) + for s, fc, ec, lw in itertools.product(*sets): + subset = ( + (sizes != s) | + (facecolors != fc) | + (edgecolors != ec) | + (linewidths != lw) + ) + subset = np.ma.masked_array(z, subset, dtype=float) + + # When depth shading is disabled, the colors are passed through as + # single-item lists; this triggers single path optimization. The + # following reshaping is a hack to disable that, since the optimization + # would not occur for the full scatter which has multiple colors. + fc = np.repeat(fc, sum(~subset.mask)) + + ax_ref.scatter(x, y, subset, s=s, fc=fc, ec=ec, lw=lw, alpha=1, + depthshade=depthshade) + + ax_test = fig_test.add_subplot(projection='3d') + ax_test.scatter(x, y, z, s=sizes, fc=facecolors, ec=edgecolors, + lw=linewidths, alpha=1, depthshade=depthshade) + + +@pytest.mark.parametrize('azim', [-50, 130]) # yellow first, blue first +@check_figures_equal(extensions=['png']) +def test_marker_draw_order_data_reversed(fig_test, fig_ref, azim): + """ + Test that the draw order does not depend on the data point order. + + For the given viewing angle at azim=-50, the yellow marker should be in + front. For azim=130, the blue marker should be in front. + """ + x = [-1, 1] + y = [1, -1] + z = [0, 0] + color = ['b', 'y'] + ax = fig_test.add_subplot(projection='3d') + ax.scatter(x, y, z, s=3500, c=color) + ax.view_init(elev=0, azim=azim, roll=0) + ax = fig_ref.add_subplot(projection='3d') + ax.scatter(x[::-1], y[::-1], z[::-1], s=3500, c=color[::-1]) + ax.view_init(elev=0, azim=azim, roll=0) + + +@check_figures_equal(extensions=['png']) +def test_marker_draw_order_view_rotated(fig_test, fig_ref): + """ + Test that the draw order changes with the direction. + + If we rotate *azim* by 180 degrees and exchange the colors, the plot + plot should look the same again. + """ + azim = 130 + x = [-1, 1] + y = [1, -1] + z = [0, 0] + color = ['b', 'y'] + ax = fig_test.add_subplot(projection='3d') + # axis are not exactly invariant under 180 degree rotation -> deactivate + ax.set_axis_off() + ax.scatter(x, y, z, s=3500, c=color) + ax.view_init(elev=0, azim=azim, roll=0) + ax = fig_ref.add_subplot(projection='3d') + ax.set_axis_off() + ax.scatter(x, y, z, s=3500, c=color[::-1]) # color reversed + ax.view_init(elev=0, azim=azim - 180, roll=0) # view rotated by 180 deg + + +@mpl3d_image_comparison(['plot_3d_from_2d.png'], tol=0.019, style='mpl20') +def test_plot_3d_from_2d(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + xs = np.arange(0, 5) + ys = np.arange(5, 10) + ax.plot(xs, ys, zs=0, zdir='x') + ax.plot(xs, ys, zs=0, zdir='y') + + +@mpl3d_image_comparison(['fill_between_quad.png'], style='mpl20') +def test_fill_between_quad(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + theta = np.linspace(0, 2*np.pi, 50) + + x1 = np.cos(theta) + y1 = np.sin(theta) + z1 = 0.1 * np.sin(6 * theta) + + x2 = 0.6 * np.cos(theta) + y2 = 0.6 * np.sin(theta) + z2 = 2 + + where = (theta < np.pi/2) | (theta > 3*np.pi/2) + + # Since none of x1 == x2, y1 == y2, or z1 == z2 is True, the fill_between + # mode will map to 'quad' + ax.fill_between(x1, y1, z1, x2, y2, z2, + where=where, mode='auto', alpha=0.5, edgecolor='k') + + +@mpl3d_image_comparison(['fill_between_polygon.png'], style='mpl20') +def test_fill_between_polygon(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + theta = np.linspace(0, 2*np.pi, 50) + + x1 = x2 = theta + y1 = y2 = 0 + z1 = np.cos(theta) + z2 = z1 + 1 + + where = (theta < np.pi/2) | (theta > 3*np.pi/2) + + # Since x1 == x2 and y1 == y2, the fill_between mode will be 'polygon' + ax.fill_between(x1, y1, z1, x2, y2, z2, + where=where, mode='auto', edgecolor='k') + + +@mpl3d_image_comparison(['surface3d.png'], style='mpl20') +def test_surface3d(): + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X = np.arange(-5, 5, 0.25) + Y = np.arange(-5, 5, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.hypot(X, Y) + Z = np.sin(R) + surf = ax.plot_surface(X, Y, Z, rcount=40, ccount=40, cmap=cm.coolwarm, + lw=0, antialiased=False) + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_zlim(-1.01, 1.01) + fig.colorbar(surf, shrink=0.5, aspect=5) + + +@image_comparison(['surface3d_label_offset_tick_position.png'], style='mpl20') +def test_surface3d_label_offset_tick_position(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax = plt.figure().add_subplot(projection="3d") + + x, y = np.mgrid[0:6 * np.pi:0.25, 0:4 * np.pi:0.25] + z = np.sqrt(np.abs(np.cos(x) + np.cos(y))) + + ax.plot_surface(x * 1e5, y * 1e6, z * 1e8, cmap='autumn', cstride=2, rstride=2) + ax.set_xlabel("X label") + ax.set_ylabel("Y label") + ax.set_zlabel("Z label") + + +@mpl3d_image_comparison(['surface3d_shaded.png'], style='mpl20') +def test_surface3d_shaded(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X = np.arange(-5, 5, 0.25) + Y = np.arange(-5, 5, 0.25) + X, Y = np.meshgrid(X, Y) + R = np.sqrt(X ** 2 + Y ** 2) + Z = np.sin(R) + ax.plot_surface(X, Y, Z, rstride=5, cstride=5, + color=[0.25, 1, 0.25], lw=1, antialiased=False) + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_zlim(-1.01, 1.01) + + +@mpl3d_image_comparison(['surface3d_masked.png'], style='mpl20') +def test_surface3d_masked(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] + y = [1, 2, 3, 4, 5, 6, 7, 8] + + x, y = np.meshgrid(x, y) + matrix = np.array( + [ + [-1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], + [-1, 1, 2, 3, 4, 4, 4, 3, 2, 1, 1], + [-1, -1., 4, 5, 6, 8, 6, 5, 4, 3, -1.], + [-1, -1., 7, 8, 11, 12, 11, 8, 7, -1., -1.], + [-1, -1., 8, 9, 10, 16, 10, 9, 10, 7, -1.], + [-1, -1., -1., 12, 16, 20, 16, 12, 11, -1., -1.], + [-1, -1., -1., -1., 22, 24, 22, 20, 18, -1., -1.], + [-1, -1., -1., -1., -1., 28, 26, 25, -1., -1., -1.], + ] + ) + z = np.ma.masked_less(matrix, 0) + norm = mcolors.Normalize(vmax=z.max(), vmin=z.min()) + colors = mpl.colormaps["plasma"](norm(z)) + ax.plot_surface(x, y, z, facecolors=colors) + ax.view_init(30, -80, 0) + + +@check_figures_equal(extensions=["png"]) +def test_plot_scatter_masks(fig_test, fig_ref): + x = np.linspace(0, 10, 100) + y = np.linspace(0, 10, 100) + z = np.sin(x) * np.cos(y) + mask = z > 0 + + z_masked = np.ma.array(z, mask=mask) + ax_test = fig_test.add_subplot(projection='3d') + ax_test.scatter(x, y, z_masked) + ax_test.plot(x, y, z_masked) + + x[mask] = y[mask] = z[mask] = np.nan + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.scatter(x, y, z) + ax_ref.plot(x, y, z) + + +@check_figures_equal(extensions=["png"]) +def test_plot_surface_None_arg(fig_test, fig_ref): + x, y = np.meshgrid(np.arange(5), np.arange(5)) + z = x + y + ax_test = fig_test.add_subplot(projection='3d') + ax_test.plot_surface(x, y, z, facecolors=None) + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.plot_surface(x, y, z) + + +@mpl3d_image_comparison(['surface3d_masked_strides.png'], style='mpl20') +def test_surface3d_masked_strides(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + x, y = np.mgrid[-6:6.1:1, -6:6.1:1] + z = np.ma.masked_less(x * y, 2) + + ax.plot_surface(x, y, z, rstride=4, cstride=4) + ax.view_init(60, -45, 0) + + +@mpl3d_image_comparison(['text3d.png'], remove_text=False, style='mpl20') +def test_text3d(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1)) + xs = (2, 6, 4, 9, 7, 2) + ys = (6, 4, 8, 7, 2, 2) + zs = (4, 2, 5, 6, 1, 7) + + for zdir, x, y, z in zip(zdirs, xs, ys, zs): + label = '(%d, %d, %d), dir=%s' % (x, y, z, zdir) + ax.text(x, y, z, label, zdir) + + ax.text(1, 1, 1, "red", color='red') + ax.text2D(0.05, 0.95, "2D Text", transform=ax.transAxes) + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_xlim3d(0, 10) + ax.set_ylim3d(0, 10) + ax.set_zlim3d(0, 10) + ax.set_xlabel('X axis') + ax.set_ylabel('Y axis') + ax.set_zlabel('Z axis') + + +@check_figures_equal(extensions=['png']) +def test_text3d_modification(fig_ref, fig_test): + # Modifying the Text position after the fact should work the same as + # setting it directly. + zdirs = (None, 'x', 'y', 'z', (1, 1, 0), (1, 1, 1)) + xs = (2, 6, 4, 9, 7, 2) + ys = (6, 4, 8, 7, 2, 2) + zs = (4, 2, 5, 6, 1, 7) + + ax_test = fig_test.add_subplot(projection='3d') + ax_test.set_xlim3d(0, 10) + ax_test.set_ylim3d(0, 10) + ax_test.set_zlim3d(0, 10) + for zdir, x, y, z in zip(zdirs, xs, ys, zs): + t = ax_test.text(0, 0, 0, f'({x}, {y}, {z}), dir={zdir}') + t.set_position_3d((x, y, z), zdir=zdir) + + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.set_xlim3d(0, 10) + ax_ref.set_ylim3d(0, 10) + ax_ref.set_zlim3d(0, 10) + for zdir, x, y, z in zip(zdirs, xs, ys, zs): + ax_ref.text(x, y, z, f'({x}, {y}, {z}), dir={zdir}', zdir=zdir) + + +@mpl3d_image_comparison(['trisurf3d.png'], tol=0.061, style='mpl20') +def test_trisurf3d(): + n_angles = 36 + n_radii = 8 + radii = np.linspace(0.125, 1.0, n_radii) + angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) + angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) + angles[:, 1::2] += np.pi/n_angles + + x = np.append(0, (radii*np.cos(angles)).flatten()) + y = np.append(0, (radii*np.sin(angles)).flatten()) + z = np.sin(-x*y) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.plot_trisurf(x, y, z, cmap=cm.jet, linewidth=0.2) + + +@mpl3d_image_comparison(['trisurf3d_shaded.png'], tol=0.03, style='mpl20') +def test_trisurf3d_shaded(): + n_angles = 36 + n_radii = 8 + radii = np.linspace(0.125, 1.0, n_radii) + angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False) + angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1) + angles[:, 1::2] += np.pi/n_angles + + x = np.append(0, (radii*np.cos(angles)).flatten()) + y = np.append(0, (radii*np.sin(angles)).flatten()) + z = np.sin(-x*y) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.plot_trisurf(x, y, z, color=[1, 0.5, 0], linewidth=0.2) + + +@mpl3d_image_comparison(['wireframe3d.png'], style='mpl20') +def test_wireframe3d(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.plot_wireframe(X, Y, Z, rcount=13, ccount=13) + + +@mpl3d_image_comparison(['wireframe3dzerocstride.png'], style='mpl20') +def test_wireframe3dzerocstride(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.plot_wireframe(X, Y, Z, rcount=13, ccount=0) + + +@mpl3d_image_comparison(['wireframe3dzerorstride.png'], style='mpl20') +def test_wireframe3dzerorstride(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + ax.plot_wireframe(X, Y, Z, rstride=0, cstride=10) + + +def test_wireframe3dzerostrideraises(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + with pytest.raises(ValueError): + ax.plot_wireframe(X, Y, Z, rstride=0, cstride=0) + + +def test_mixedsamplesraises(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + X, Y, Z = axes3d.get_test_data(0.05) + with pytest.raises(ValueError): + ax.plot_wireframe(X, Y, Z, rstride=10, ccount=50) + with pytest.raises(ValueError): + ax.plot_surface(X, Y, Z, cstride=50, rcount=10) + + +# remove tolerance when regenerating the test image +@mpl3d_image_comparison(['quiver3d.png'], style='mpl20', tol=0.003) +def test_quiver3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + pivots = ['tip', 'middle', 'tail'] + colors = ['tab:blue', 'tab:orange', 'tab:green'] + for i, (pivot, color) in enumerate(zip(pivots, colors)): + x, y, z = np.meshgrid([-0.5, 0.5], [-0.5, 0.5], [-0.5, 0.5]) + u = -x + v = -y + w = -z + # Offset each set in z direction + z += 2 * i + ax.quiver(x, y, z, u, v, w, length=1, pivot=pivot, color=color) + ax.scatter(x, y, z, color=color) + + ax.set_xlim(-3, 3) + ax.set_ylim(-3, 3) + ax.set_zlim(-1, 5) + + +@check_figures_equal(extensions=["png"]) +def test_quiver3d_empty(fig_test, fig_ref): + fig_ref.add_subplot(projection='3d') + x = y = z = u = v = w = [] + ax = fig_test.add_subplot(projection='3d') + ax.quiver(x, y, z, u, v, w, length=0.1, pivot='tip', normalize=True) + + +@mpl3d_image_comparison(['quiver3d_masked.png'], style='mpl20') +def test_quiver3d_masked(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + # Using mgrid here instead of ogrid because masked_where doesn't + # seem to like broadcasting very much... + x, y, z = np.mgrid[-1:0.8:10j, -1:0.8:10j, -1:0.6:3j] + + u = np.sin(np.pi * x) * np.cos(np.pi * y) * np.cos(np.pi * z) + v = -np.cos(np.pi * x) * np.sin(np.pi * y) * np.cos(np.pi * z) + w = (2/3)**0.5 * np.cos(np.pi * x) * np.cos(np.pi * y) * np.sin(np.pi * z) + u = np.ma.masked_where((-0.4 < x) & (x < 0.1), u, copy=False) + v = np.ma.masked_where((0.1 < y) & (y < 0.7), v, copy=False) + + ax.quiver(x, y, z, u, v, w, length=0.1, pivot='tip', normalize=True) + + +@mpl3d_image_comparison(['quiver3d_colorcoded.png'], style='mpl20') +def test_quiver3d_colorcoded(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + x = y = dx = dz = np.zeros(10) + z = dy = np.arange(10.) + + color = plt.cm.Reds(dy/dy.max()) + ax.quiver(x, y, z, dx, dy, dz, colors=color) + ax.set_ylim(0, 10) + + +def test_patch_modification(): + fig = plt.figure() + ax = fig.add_subplot(projection="3d") + circle = Circle((0, 0)) + ax.add_patch(circle) + art3d.patch_2d_to_3d(circle) + circle.set_facecolor((1.0, 0.0, 0.0, 1)) + + assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1)) + fig.canvas.draw() + assert mcolors.same_color(circle.get_facecolor(), (1, 0, 0, 1)) + + +@check_figures_equal(extensions=['png']) +def test_patch_collection_modification(fig_test, fig_ref): + # Test that modifying Patch3DCollection properties after creation works. + patch1 = Circle((0, 0), 0.05) + patch2 = Circle((0.1, 0.1), 0.03) + facecolors = np.array([[0., 0.5, 0., 1.], [0.5, 0., 0., 0.5]]) + c = art3d.Patch3DCollection([patch1, patch2], linewidths=3) + + ax_test = fig_test.add_subplot(projection='3d') + ax_test.add_collection3d(c) + c.set_edgecolor('C2') + c.set_facecolor(facecolors) + c.set_alpha(0.7) + assert c.get_depthshade() + c.set_depthshade(False) + assert not c.get_depthshade() + + patch1 = Circle((0, 0), 0.05) + patch2 = Circle((0.1, 0.1), 0.03) + facecolors = np.array([[0., 0.5, 0., 1.], [0.5, 0., 0., 0.5]]) + c = art3d.Patch3DCollection([patch1, patch2], linewidths=3, + edgecolor='C2', facecolor=facecolors, + alpha=0.7, depthshade=False) + + ax_ref = fig_ref.add_subplot(projection='3d') + ax_ref.add_collection3d(c) + + +def test_poly3dcollection_verts_validation(): + poly = [[0, 0, 1], [0, 1, 1], [0, 1, 0], [0, 0, 0]] + with pytest.raises(ValueError, match=r'list of \(N, 3\) array-like'): + art3d.Poly3DCollection(poly) # should be Poly3DCollection([poly]) + + poly = np.array(poly, dtype=float) + with pytest.raises(ValueError, match=r'list of \(N, 3\) array-like'): + art3d.Poly3DCollection(poly) # should be Poly3DCollection([poly]) + + +@mpl3d_image_comparison(['poly3dcollection_closed.png'], style='mpl20') +def test_poly3dcollection_closed(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float) + poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float) + c1 = art3d.Poly3DCollection([poly1], linewidths=3, edgecolor='k', + facecolor=(0.5, 0.5, 1, 0.5), closed=True) + c2 = art3d.Poly3DCollection([poly2], linewidths=3, edgecolor='k', + facecolor=(1, 0.5, 0.5, 0.5), closed=False) + ax.add_collection3d(c1, autolim=False) + ax.add_collection3d(c2, autolim=False) + + +def test_poly_collection_2d_to_3d_empty(): + poly = PolyCollection([]) + art3d.poly_collection_2d_to_3d(poly) + assert isinstance(poly, art3d.Poly3DCollection) + assert poly.get_paths() == [] + + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + ax.add_artist(poly) + minz = poly.do_3d_projection() + assert np.isnan(minz) + + # Ensure drawing actually works. + fig.canvas.draw() + + +@mpl3d_image_comparison(['poly3dcollection_alpha.png'], style='mpl20') +def test_poly3dcollection_alpha(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + poly1 = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float) + poly2 = np.array([[0, 1, 1], [1, 1, 1], [1, 1, 0]], float) + c1 = art3d.Poly3DCollection([poly1], linewidths=3, edgecolor='k', + facecolor=(0.5, 0.5, 1), closed=True) + c1.set_alpha(0.5) + c2 = art3d.Poly3DCollection([poly2], linewidths=3, closed=False) + # Post-creation modification should work. + c2.set_facecolor((1, 0.5, 0.5)) + c2.set_edgecolor('k') + c2.set_alpha(0.5) + ax.add_collection3d(c1, autolim=False) + ax.add_collection3d(c2, autolim=False) + + +@mpl3d_image_comparison(['add_collection3d_zs_array.png'], style='mpl20') +def test_add_collection3d_zs_array(): + theta = np.linspace(-4 * np.pi, 4 * np.pi, 100) + z = np.linspace(-2, 2, 100) + r = z**2 + 1 + x = r * np.sin(theta) + y = r * np.cos(theta) + + points = np.column_stack([x, y, z]).reshape(-1, 1, 3) + segments = np.concatenate([points[:-1], points[1:]], axis=1) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + norm = plt.Normalize(0, 2*np.pi) + # 2D LineCollection from x & y values + lc = LineCollection(segments[:, :, :2], cmap='twilight', norm=norm) + lc.set_array(np.mod(theta, 2*np.pi)) + # Add 2D collection at z values to ax + line = ax.add_collection3d(lc, zs=segments[:, :, 2]) + + assert line is not None + + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_xlim(-5, 5) + ax.set_ylim(-4, 6) + ax.set_zlim(-2, 2) + + +@mpl3d_image_comparison(['add_collection3d_zs_scalar.png'], style='mpl20') +def test_add_collection3d_zs_scalar(): + theta = np.linspace(0, 2 * np.pi, 100) + z = 1 + r = z**2 + 1 + x = r * np.sin(theta) + y = r * np.cos(theta) + + points = np.column_stack([x, y]).reshape(-1, 1, 2) + segments = np.concatenate([points[:-1], points[1:]], axis=1) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + norm = plt.Normalize(0, 2*np.pi) + lc = LineCollection(segments, cmap='twilight', norm=norm) + lc.set_array(theta) + line = ax.add_collection3d(lc, zs=z) + + assert line is not None + + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_xlim(-5, 5) + ax.set_ylim(-4, 6) + ax.set_zlim(0, 2) + + +def test_line3dCollection_autoscaling(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + lines = [[(0, 0, 0), (1, 4, 2)], + [(1, 1, 3), (2, 0, 2)], + [(1, 0, 4), (1, 4, 5)]] + + lc = art3d.Line3DCollection(lines) + ax.add_collection3d(lc) + assert np.allclose(ax.get_xlim3d(), (-0.041666666666666664, 2.0416666666666665)) + assert np.allclose(ax.get_ylim3d(), (-0.08333333333333333, 4.083333333333333)) + assert np.allclose(ax.get_zlim3d(), (-0.10416666666666666, 5.104166666666667)) + + +def test_poly3dCollection_autoscaling(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + poly = np.array([[0, 0, 0], [1, 1, 3], [1, 0, 4]]) + col = art3d.Poly3DCollection([poly]) + ax.add_collection3d(col) + assert np.allclose(ax.get_xlim3d(), (-0.020833333333333332, 1.0208333333333333)) + assert np.allclose(ax.get_ylim3d(), (-0.020833333333333332, 1.0208333333333333)) + assert np.allclose(ax.get_zlim3d(), (-0.0833333333333333, 4.083333333333333)) + + +@mpl3d_image_comparison(['axes3d_labelpad.png'], + remove_text=False, style='mpl20') +def test_axes3d_labelpad(): + fig = plt.figure() + ax = fig.add_axes(Axes3D(fig)) + # labelpad respects rcParams + assert ax.xaxis.labelpad == mpl.rcParams['axes.labelpad'] + # labelpad can be set in set_label + ax.set_xlabel('X LABEL', labelpad=10) + assert ax.xaxis.labelpad == 10 + ax.set_ylabel('Y LABEL') + ax.set_zlabel('Z LABEL', labelpad=20) + assert ax.zaxis.labelpad == 20 + assert ax.get_zlabel() == 'Z LABEL' + # or manually + ax.yaxis.labelpad = 20 + ax.zaxis.labelpad = -40 + + # Tick labels also respect tick.pad (also from rcParams) + for i, tick in enumerate(ax.yaxis.get_major_ticks()): + tick.set_pad(tick.get_pad() + 5 - i * 5) + + +@mpl3d_image_comparison(['axes3d_cla.png'], remove_text=False, style='mpl20') +def test_axes3d_cla(): + # fixed in pull request 4553 + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection='3d') + ax.set_axis_off() + ax.cla() # make sure the axis displayed is 3D (not 2D) + + +@mpl3d_image_comparison(['axes3d_rotated.png'], + remove_text=False, style='mpl20') +def test_axes3d_rotated(): + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection='3d') + ax.view_init(90, 45, 0) # look down, rotated. Should be square + + +def test_plotsurface_1d_raises(): + x = np.linspace(0.5, 10, num=100) + y = np.linspace(0.5, 10, num=100) + X, Y = np.meshgrid(x, y) + z = np.random.randn(100) + + fig = plt.figure(figsize=(14, 6)) + ax = fig.add_subplot(1, 2, 1, projection='3d') + with pytest.raises(ValueError): + ax.plot_surface(X, Y, z) + + +def _test_proj_make_M(): + # eye point + E = np.array([1000, -1000, 2000]) + R = np.array([100, 100, 100]) + V = np.array([0, 0, 1]) + roll = 0 + u, v, w = proj3d._view_axes(E, R, V, roll) + viewM = proj3d._view_transformation_uvw(u, v, w, E) + perspM = proj3d._persp_transformation(100, -100, 1) + M = np.dot(perspM, viewM) + return M + + +def test_proj_transform(): + M = _test_proj_make_M() + invM = np.linalg.inv(M) + + xs = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0]) * 300.0 + ys = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0]) * 300.0 + zs = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) * 300.0 + + txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) + ixs, iys, izs = proj3d.inv_transform(txs, tys, tzs, invM) + + np.testing.assert_almost_equal(ixs, xs) + np.testing.assert_almost_equal(iys, ys) + np.testing.assert_almost_equal(izs, zs) + + +def _test_proj_draw_axes(M, s=1, *args, **kwargs): + xs = [0, s, 0, 0] + ys = [0, 0, s, 0] + zs = [0, 0, 0, s] + txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) + o, ax, ay, az = zip(txs, tys) + lines = [(o, ax), (o, ay), (o, az)] + + fig, ax = plt.subplots(*args, **kwargs) + linec = LineCollection(lines) + ax.add_collection(linec) + for x, y, t in zip(txs, tys, ['o', 'x', 'y', 'z']): + ax.text(x, y, t) + + return fig, ax + + +@mpl3d_image_comparison(['proj3d_axes_cube.png'], style='mpl20') +def test_proj_axes_cube(): + M = _test_proj_make_M() + + ts = '0 1 2 3 0 4 5 6 7 4'.split() + xs = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0]) * 300.0 + ys = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0]) * 300.0 + zs = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) * 300.0 + + txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) + + fig, ax = _test_proj_draw_axes(M, s=400) + + ax.scatter(txs, tys, c=tzs) + ax.plot(txs, tys, c='r') + for x, y, t in zip(txs, tys, ts): + ax.text(x, y, t) + + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_xlim(-0.2, 0.2) + ax.set_ylim(-0.2, 0.2) + + +@mpl3d_image_comparison(['proj3d_axes_cube_ortho.png'], style='mpl20') +def test_proj_axes_cube_ortho(): + E = np.array([200, 100, 100]) + R = np.array([0, 0, 0]) + V = np.array([0, 0, 1]) + roll = 0 + u, v, w = proj3d._view_axes(E, R, V, roll) + viewM = proj3d._view_transformation_uvw(u, v, w, E) + orthoM = proj3d._ortho_transformation(-1, 1) + M = np.dot(orthoM, viewM) + + ts = '0 1 2 3 0 4 5 6 7 4'.split() + xs = np.array([0, 1, 1, 0, 0, 0, 1, 1, 0, 0]) * 100 + ys = np.array([0, 0, 1, 1, 0, 0, 0, 1, 1, 0]) * 100 + zs = np.array([0, 0, 0, 0, 0, 1, 1, 1, 1, 1]) * 100 + + txs, tys, tzs = proj3d.proj_transform(xs, ys, zs, M) + + fig, ax = _test_proj_draw_axes(M, s=150) + + ax.scatter(txs, tys, s=300-tzs) + ax.plot(txs, tys, c='r') + for x, y, t in zip(txs, tys, ts): + ax.text(x, y, t) + + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + ax.set_xlim(-200, 200) + ax.set_ylim(-200, 200) + + +def test_world(): + xmin, xmax = 100, 120 + ymin, ymax = -100, 100 + zmin, zmax = 0.1, 0.2 + M = proj3d.world_transformation(xmin, xmax, ymin, ymax, zmin, zmax) + np.testing.assert_allclose(M, + [[5e-2, 0, 0, -5], + [0, 5e-3, 0, 5e-1], + [0, 0, 1e1, -1], + [0, 0, 0, 1]]) + + +def test_autoscale(): + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + assert ax.get_zscale() == 'linear' + ax._view_margin = 0 + ax.margins(x=0, y=.1, z=.2) + ax.plot([0, 1], [0, 1], [0, 1]) + assert ax.get_w_lims() == (0, 1, -.1, 1.1, -.2, 1.2) + ax.autoscale(False) + ax.set_autoscalez_on(True) + ax.plot([0, 2], [0, 2], [0, 2]) + assert ax.get_w_lims() == (0, 1, -.1, 1.1, -.4, 2.4) + ax.autoscale(axis='x') + ax.plot([0, 2], [0, 2], [0, 2]) + assert ax.get_w_lims() == (0, 2, -.1, 1.1, -.4, 2.4) + + +@pytest.mark.parametrize('axis', ('x', 'y', 'z')) +@pytest.mark.parametrize('auto', (True, False, None)) +def test_unautoscale(axis, auto): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + x = np.arange(100) + y = np.linspace(-0.1, 0.1, 100) + ax.scatter(x, y) + + get_autoscale_on = getattr(ax, f'get_autoscale{axis}_on') + set_lim = getattr(ax, f'set_{axis}lim') + get_lim = getattr(ax, f'get_{axis}lim') + + post_auto = get_autoscale_on() if auto is None else auto + + set_lim((-0.5, 0.5), auto=auto) + assert post_auto == get_autoscale_on() + fig.canvas.draw() + np.testing.assert_array_equal(get_lim(), (-0.5, 0.5)) + + +@check_figures_equal(extensions=["png"]) +def test_culling(fig_test, fig_ref): + xmins = (-100, -50) + for fig, xmin in zip((fig_test, fig_ref), xmins): + ax = fig.add_subplot(projection='3d') + n = abs(xmin) + 1 + xs = np.linspace(0, xmin, n) + ys = np.ones(n) + zs = np.zeros(n) + ax.plot(xs, ys, zs, 'k') + + ax.set(xlim=(-5, 5), ylim=(-5, 5), zlim=(-5, 5)) + ax.view_init(5, 180, 0) + + +def test_axes3d_focal_length_checks(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + with pytest.raises(ValueError): + ax.set_proj_type('persp', focal_length=0) + with pytest.raises(ValueError): + ax.set_proj_type('ortho', focal_length=1) + + +@mpl3d_image_comparison(['axes3d_focal_length.png'], + remove_text=False, style='mpl20') +def test_axes3d_focal_length(): + fig, axs = plt.subplots(1, 2, subplot_kw={'projection': '3d'}) + axs[0].set_proj_type('persp', focal_length=np.inf) + axs[1].set_proj_type('persp', focal_length=0.15) + + +@mpl3d_image_comparison(['axes3d_ortho.png'], remove_text=False, style='mpl20') +def test_axes3d_ortho(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.set_proj_type('ortho') + + +@mpl3d_image_comparison(['axes3d_isometric.png'], style='mpl20') +def test_axes3d_isometric(): + from itertools import combinations, product + fig, ax = plt.subplots(subplot_kw=dict( + projection='3d', + proj_type='ortho', + box_aspect=(4, 4, 4) + )) + r = (-1, 1) # stackoverflow.com/a/11156353 + for s, e in combinations(np.array(list(product(r, r, r))), 2): + if abs(s - e).sum() == r[1] - r[0]: + ax.plot3D(*zip(s, e), c='k') + ax.view_init(elev=np.degrees(np.arctan(1. / np.sqrt(2))), azim=-45, roll=0) + ax.grid(True) + + +@check_figures_equal(extensions=["png"]) +def test_axlim_clip(fig_test, fig_ref): + # With axlim clipping + ax = fig_test.add_subplot(projection="3d") + x = np.linspace(0, 1, 11) + y = np.linspace(0, 1, 11) + X, Y = np.meshgrid(x, y) + Z = X + Y + ax.plot_surface(X, Y, Z, facecolor='C1', edgecolors=None, + rcount=50, ccount=50, axlim_clip=True) + # This ax.plot is to cover the extra surface edge which is not clipped out + ax.plot([0.5, 0.5], [0, 1], [0.5, 1.5], + color='k', linewidth=3, zorder=5, axlim_clip=True) + ax.scatter(X.ravel(), Y.ravel(), Z.ravel() + 1, axlim_clip=True) + ax.quiver(X.ravel(), Y.ravel(), Z.ravel() + 2, + 0*X.ravel(), 0*Y.ravel(), 0*Z.ravel() + 1, + arrow_length_ratio=0, axlim_clip=True) + ax.plot(X[0], Y[0], Z[0] + 3, color='C2', axlim_clip=True) + ax.text(1.1, 0.5, 4, 'test', axlim_clip=True) # won't be visible + ax.set(xlim=(0, 0.5), ylim=(0, 1), zlim=(0, 5)) + + # With manual clipping + ax = fig_ref.add_subplot(projection="3d") + idx = (X <= 0.5) + X = X[idx].reshape(11, 6) + Y = Y[idx].reshape(11, 6) + Z = Z[idx].reshape(11, 6) + ax.plot_surface(X, Y, Z, facecolor='C1', edgecolors=None, + rcount=50, ccount=50, axlim_clip=False) + ax.plot([0.5, 0.5], [0, 1], [0.5, 1.5], + color='k', linewidth=3, zorder=5, axlim_clip=False) + ax.scatter(X.ravel(), Y.ravel(), Z.ravel() + 1, axlim_clip=False) + ax.quiver(X.ravel(), Y.ravel(), Z.ravel() + 2, + 0*X.ravel(), 0*Y.ravel(), 0*Z.ravel() + 1, + arrow_length_ratio=0, axlim_clip=False) + ax.plot(X[0], Y[0], Z[0] + 3, color='C2', axlim_clip=False) + ax.set(xlim=(0, 0.5), ylim=(0, 1), zlim=(0, 5)) + + +@pytest.mark.parametrize('value', [np.inf, np.nan]) +@pytest.mark.parametrize(('setter', 'side'), [ + ('set_xlim3d', 'left'), + ('set_xlim3d', 'right'), + ('set_ylim3d', 'bottom'), + ('set_ylim3d', 'top'), + ('set_zlim3d', 'bottom'), + ('set_zlim3d', 'top'), +]) +def test_invalid_axes_limits(setter, side, value): + limit = {side: value} + fig = plt.figure() + obj = fig.add_subplot(projection='3d') + with pytest.raises(ValueError): + getattr(obj, setter)(**limit) + + +class TestVoxels: + @mpl3d_image_comparison(['voxels-simple.png'], style='mpl20') + def test_simple(self): + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + x, y, z = np.indices((5, 4, 3)) + voxels = (x == y) | (y == z) + ax.voxels(voxels) + + @mpl3d_image_comparison(['voxels-edge-style.png'], style='mpl20') + def test_edge_style(self): + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + x, y, z = np.indices((5, 5, 4)) + voxels = ((x - 2)**2 + (y - 2)**2 + (z-1.5)**2) < 2.2**2 + v = ax.voxels(voxels, linewidths=3, edgecolor='C1') + + # change the edge color of one voxel + v[max(v.keys())].set_edgecolor('C2') + + @mpl3d_image_comparison(['voxels-named-colors.png'], style='mpl20') + def test_named_colors(self): + """Test with colors set to a 3D object array of strings.""" + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + x, y, z = np.indices((10, 10, 10)) + voxels = (x == y) | (y == z) + voxels = voxels & ~(x * y * z < 1) + colors = np.full((10, 10, 10), 'C0', dtype=np.object_) + colors[(x < 5) & (y < 5)] = '0.25' + colors[(x + z) < 10] = 'cyan' + ax.voxels(voxels, facecolors=colors) + + @mpl3d_image_comparison(['voxels-rgb-data.png'], style='mpl20') + def test_rgb_data(self): + """Test with colors set to a 4d float array of rgb data.""" + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + x, y, z = np.indices((10, 10, 10)) + voxels = (x == y) | (y == z) + colors = np.zeros((10, 10, 10, 3)) + colors[..., 0] = x / 9 + colors[..., 1] = y / 9 + colors[..., 2] = z / 9 + ax.voxels(voxels, facecolors=colors) + + @mpl3d_image_comparison(['voxels-alpha.png'], style='mpl20') + def test_alpha(self): + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + x, y, z = np.indices((10, 10, 10)) + v1 = x == y + v2 = np.abs(x - y) < 2 + voxels = v1 | v2 + colors = np.zeros((10, 10, 10, 4)) + colors[v2] = [1, 0, 0, 0.5] + colors[v1] = [0, 1, 0, 0.5] + v = ax.voxels(voxels, facecolors=colors) + + assert type(v) is dict + for coord, poly in v.items(): + assert voxels[coord], "faces returned for absent voxel" + assert isinstance(poly, art3d.Poly3DCollection) + + @mpl3d_image_comparison(['voxels-xyz.png'], + tol=0.01, remove_text=False, style='mpl20') + def test_xyz(self): + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + def midpoints(x): + sl = () + for i in range(x.ndim): + x = (x[sl + np.index_exp[:-1]] + + x[sl + np.index_exp[1:]]) / 2.0 + sl += np.index_exp[:] + return x + + # prepare some coordinates, and attach rgb values to each + r, g, b = np.indices((17, 17, 17)) / 16.0 + rc = midpoints(r) + gc = midpoints(g) + bc = midpoints(b) + + # define a sphere about [0.5, 0.5, 0.5] + sphere = (rc - 0.5)**2 + (gc - 0.5)**2 + (bc - 0.5)**2 < 0.5**2 + + # combine the color components + colors = np.zeros(sphere.shape + (3,)) + colors[..., 0] = rc + colors[..., 1] = gc + colors[..., 2] = bc + + # and plot everything + ax.voxels(r, g, b, sphere, + facecolors=colors, + edgecolors=np.clip(2*colors - 0.5, 0, 1), # brighter + linewidth=0.5) + + def test_calling_conventions(self): + x, y, z = np.indices((3, 4, 5)) + filled = np.ones((2, 3, 4)) + + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + + # all the valid calling conventions + for kw in (dict(), dict(edgecolor='k')): + ax.voxels(filled, **kw) + ax.voxels(filled=filled, **kw) + ax.voxels(x, y, z, filled, **kw) + ax.voxels(x, y, z, filled=filled, **kw) + + # duplicate argument + with pytest.raises(TypeError, match='voxels'): + ax.voxels(x, y, z, filled, filled=filled) + # missing arguments + with pytest.raises(TypeError, match='voxels'): + ax.voxels(x, y) + # x, y, z are positional only - this passes them on as attributes of + # Poly3DCollection + with pytest.raises(AttributeError, match="keyword argument 'x'") as exec_info: + ax.voxels(filled=filled, x=x, y=y, z=z) + assert exec_info.value.name == 'x' + + +def test_line3d_set_get_data_3d(): + x, y, z = [0, 1], [2, 3], [4, 5] + x2, y2, z2 = [6, 7], [8, 9], [10, 11] + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + lines = ax.plot(x, y, z) + line = lines[0] + np.testing.assert_array_equal((x, y, z), line.get_data_3d()) + line.set_data_3d(x2, y2, z2) + np.testing.assert_array_equal((x2, y2, z2), line.get_data_3d()) + line.set_xdata(x) + line.set_ydata(y) + line.set_3d_properties(zs=z, zdir='z') + np.testing.assert_array_equal((x, y, z), line.get_data_3d()) + line.set_3d_properties(zs=0, zdir='z') + np.testing.assert_array_equal((x, y, np.zeros_like(z)), line.get_data_3d()) + + +@check_figures_equal(extensions=["png"]) +def test_inverted(fig_test, fig_ref): + # Plot then invert. + ax = fig_test.add_subplot(projection="3d") + ax.plot([1, 1, 10, 10], [1, 10, 10, 10], [1, 1, 1, 10]) + ax.invert_yaxis() + # Invert then plot. + ax = fig_ref.add_subplot(projection="3d") + ax.invert_yaxis() + ax.plot([1, 1, 10, 10], [1, 10, 10, 10], [1, 1, 1, 10]) + + +def test_inverted_cla(): + # GitHub PR #5450. Setting autoscale should reset + # axes to be non-inverted. + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + # 1. test that a new axis is not inverted per default + assert not ax.xaxis_inverted() + assert not ax.yaxis_inverted() + assert not ax.zaxis_inverted() + ax.set_xlim(1, 0) + ax.set_ylim(1, 0) + ax.set_zlim(1, 0) + assert ax.xaxis_inverted() + assert ax.yaxis_inverted() + assert ax.zaxis_inverted() + ax.cla() + assert not ax.xaxis_inverted() + assert not ax.yaxis_inverted() + assert not ax.zaxis_inverted() + + +def test_ax3d_tickcolour(): + fig = plt.figure() + ax = Axes3D(fig) + + ax.tick_params(axis='x', colors='red') + ax.tick_params(axis='y', colors='red') + ax.tick_params(axis='z', colors='red') + fig.canvas.draw() + + for tick in ax.xaxis.get_major_ticks(): + assert tick.tick1line._color == 'red' + for tick in ax.yaxis.get_major_ticks(): + assert tick.tick1line._color == 'red' + for tick in ax.zaxis.get_major_ticks(): + assert tick.tick1line._color == 'red' + + +@check_figures_equal(extensions=["png"]) +def test_ticklabel_format(fig_test, fig_ref): + axs = fig_test.subplots(4, 5, subplot_kw={"projection": "3d"}) + for ax in axs.flat: + ax.set_xlim(1e7, 1e7 + 10) + for row, name in zip(axs, ["x", "y", "z", "both"]): + row[0].ticklabel_format( + axis=name, style="plain") + row[1].ticklabel_format( + axis=name, scilimits=(-2, 2)) + row[2].ticklabel_format( + axis=name, useOffset=not mpl.rcParams["axes.formatter.useoffset"]) + row[3].ticklabel_format( + axis=name, useLocale=not mpl.rcParams["axes.formatter.use_locale"]) + row[4].ticklabel_format( + axis=name, + useMathText=not mpl.rcParams["axes.formatter.use_mathtext"]) + + def get_formatters(ax, names): + return [getattr(ax, name).get_major_formatter() for name in names] + + axs = fig_ref.subplots(4, 5, subplot_kw={"projection": "3d"}) + for ax in axs.flat: + ax.set_xlim(1e7, 1e7 + 10) + for row, names in zip( + axs, [["xaxis"], ["yaxis"], ["zaxis"], ["xaxis", "yaxis", "zaxis"]] + ): + for fmt in get_formatters(row[0], names): + fmt.set_scientific(False) + for fmt in get_formatters(row[1], names): + fmt.set_powerlimits((-2, 2)) + for fmt in get_formatters(row[2], names): + fmt.set_useOffset(not mpl.rcParams["axes.formatter.useoffset"]) + for fmt in get_formatters(row[3], names): + fmt.set_useLocale(not mpl.rcParams["axes.formatter.use_locale"]) + for fmt in get_formatters(row[4], names): + fmt.set_useMathText( + not mpl.rcParams["axes.formatter.use_mathtext"]) + + +@check_figures_equal(extensions=["png"]) +def test_quiver3D_smoke(fig_test, fig_ref): + pivot = "middle" + # Make the grid + x, y, z = np.meshgrid( + np.arange(-0.8, 1, 0.2), + np.arange(-0.8, 1, 0.2), + np.arange(-0.8, 1, 0.8) + ) + u = v = w = np.ones_like(x) + + for fig, length in zip((fig_ref, fig_test), (1, 1.0)): + ax = fig.add_subplot(projection="3d") + ax.quiver(x, y, z, u, v, w, length=length, pivot=pivot) + + +@image_comparison(["minor_ticks.png"], style="mpl20") +def test_minor_ticks(): + ax = plt.figure().add_subplot(projection="3d") + ax.set_xticks([0.25], minor=True) + ax.set_xticklabels(["quarter"], minor=True) + ax.set_yticks([0.33], minor=True) + ax.set_yticklabels(["third"], minor=True) + ax.set_zticks([0.50], minor=True) + ax.set_zticklabels(["half"], minor=True) + + +# remove tolerance when regenerating the test image +@mpl3d_image_comparison(['errorbar3d_errorevery.png'], style='mpl20', tol=0.003) +def test_errorbar3d_errorevery(): + """Tests errorevery functionality for 3D errorbars.""" + t = np.arange(0, 2*np.pi+.1, 0.01) + x, y, z = np.sin(t), np.cos(3*t), np.sin(5*t) + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + estep = 15 + i = np.arange(t.size) + zuplims = (i % estep == 0) & (i // estep % 3 == 0) + zlolims = (i % estep == 0) & (i // estep % 3 == 2) + + ax.errorbar(x, y, z, 0.2, zuplims=zuplims, zlolims=zlolims, + errorevery=estep) + + +@mpl3d_image_comparison(['errorbar3d.png'], style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.02) +def test_errorbar3d(): + """Tests limits, color styling, and legend for 3D errorbars.""" + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + d = [1, 2, 3, 4, 5] + e = [.5, .5, .5, .5, .5] + ax.errorbar(x=d, y=d, z=d, xerr=e, yerr=e, zerr=e, capsize=3, + zuplims=[False, True, False, True, True], + zlolims=[True, False, False, True, False], + yuplims=True, + ecolor='purple', label='Error lines') + ax.legend() + + +@image_comparison(['stem3d.png'], style='mpl20', tol=0.009) +def test_stem3d(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig, axs = plt.subplots(2, 3, figsize=(8, 6), + constrained_layout=True, + subplot_kw={'projection': '3d'}) + + theta = np.linspace(0, 2*np.pi) + x = np.cos(theta - np.pi/2) + y = np.sin(theta - np.pi/2) + z = theta + + for ax, zdir in zip(axs[0], ['x', 'y', 'z']): + ax.stem(x, y, z, orientation=zdir) + ax.set_title(f'orientation={zdir}') + + x = np.linspace(-np.pi/2, np.pi/2, 20) + y = np.ones_like(x) + z = np.cos(x) + + for ax, zdir in zip(axs[1], ['x', 'y', 'z']): + markerline, stemlines, baseline = ax.stem( + x, y, z, + linefmt='C4-.', markerfmt='C1D', basefmt='C2', + orientation=zdir) + ax.set_title(f'orientation={zdir}') + markerline.set(markerfacecolor='none', markeredgewidth=2) + baseline.set_linewidth(3) + + +@image_comparison(["equal_box_aspect.png"], style="mpl20") +def test_equal_box_aspect(): + from itertools import product, combinations + + fig = plt.figure() + ax = fig.add_subplot(projection="3d") + + # Make data + u = np.linspace(0, 2 * np.pi, 100) + v = np.linspace(0, np.pi, 100) + x = np.outer(np.cos(u), np.sin(v)) + y = np.outer(np.sin(u), np.sin(v)) + z = np.outer(np.ones_like(u), np.cos(v)) + + # Plot the surface + ax.plot_surface(x, y, z) + + # draw cube + r = [-1, 1] + for s, e in combinations(np.array(list(product(r, r, r))), 2): + if np.sum(np.abs(s - e)) == r[1] - r[0]: + ax.plot3D(*zip(s, e), color="b") + + # Make axes limits + xyzlim = np.column_stack( + [ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()] + ) + XYZlim = [min(xyzlim[0]), max(xyzlim[1])] + ax.set_xlim3d(XYZlim) + ax.set_ylim3d(XYZlim) + ax.set_zlim3d(XYZlim) + ax.axis('off') + ax.set_box_aspect((1, 1, 1)) + + with pytest.raises(ValueError, match="Argument zoom ="): + ax.set_box_aspect((1, 1, 1), zoom=-1) + + +def test_colorbar_pos(): + num_plots = 2 + fig, axs = plt.subplots(1, num_plots, figsize=(4, 5), + constrained_layout=True, + subplot_kw={'projection': '3d'}) + for ax in axs: + p_tri = ax.plot_trisurf(np.random.randn(5), np.random.randn(5), + np.random.randn(5)) + + cbar = plt.colorbar(p_tri, ax=axs, orientation='horizontal') + + fig.canvas.draw() + # check that actually on the bottom + assert cbar.ax.get_position().extents[1] < 0.2 + + +def test_inverted_zaxis(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.set_zlim(0, 1) + assert not ax.zaxis_inverted() + assert ax.get_zlim() == (0, 1) + assert ax.get_zbound() == (0, 1) + + # Change bound + ax.set_zbound((0, 2)) + assert not ax.zaxis_inverted() + assert ax.get_zlim() == (0, 2) + assert ax.get_zbound() == (0, 2) + + # Change invert + ax.invert_zaxis() + assert ax.zaxis_inverted() + assert ax.get_zlim() == (2, 0) + assert ax.get_zbound() == (0, 2) + + # Set upper bound + ax.set_zbound(upper=1) + assert ax.zaxis_inverted() + assert ax.get_zlim() == (1, 0) + assert ax.get_zbound() == (0, 1) + + # Set lower bound + ax.set_zbound(lower=2) + assert ax.zaxis_inverted() + assert ax.get_zlim() == (2, 1) + assert ax.get_zbound() == (1, 2) + + +def test_set_zlim(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + assert np.allclose(ax.get_zlim(), (-1/48, 49/48)) + ax.set_zlim(zmax=2) + assert np.allclose(ax.get_zlim(), (-1/48, 2)) + ax.set_zlim(zmin=1) + assert ax.get_zlim() == (1, 2) + + with pytest.raises( + TypeError, match="Cannot pass both 'lower' and 'min'"): + ax.set_zlim(bottom=0, zmin=1) + with pytest.raises( + TypeError, match="Cannot pass both 'upper' and 'max'"): + ax.set_zlim(top=0, zmax=1) + + +@check_figures_equal(extensions=["png"]) +def test_shared_view(fig_test, fig_ref): + elev, azim, roll = 5, 20, 30 + ax1 = fig_test.add_subplot(131, projection="3d") + ax2 = fig_test.add_subplot(132, projection="3d", shareview=ax1) + ax3 = fig_test.add_subplot(133, projection="3d") + ax3.shareview(ax1) + ax2.view_init(elev=elev, azim=azim, roll=roll, share=True) + + for subplot_num in (131, 132, 133): + ax = fig_ref.add_subplot(subplot_num, projection="3d") + ax.view_init(elev=elev, azim=azim, roll=roll) + + +def test_shared_axes_retick(): + fig = plt.figure() + ax1 = fig.add_subplot(211, projection="3d") + ax2 = fig.add_subplot(212, projection="3d", sharez=ax1) + ax1.plot([0, 1], [0, 1], [0, 2]) + ax2.plot([0, 1], [0, 1], [0, 2]) + ax1.set_zticks([-0.5, 0, 2, 2.5]) + # check that setting ticks on a shared axis is synchronized + assert ax1.get_zlim() == (-0.5, 2.5) + assert ax2.get_zlim() == (-0.5, 2.5) + + +def test_quaternion(): + # 1: + q1 = Quaternion(1, [0, 0, 0]) + assert q1.scalar == 1 + assert (q1.vector == [0, 0, 0]).all + # __neg__: + assert (-q1).scalar == -1 + assert ((-q1).vector == [0, 0, 0]).all + # i, j, k: + qi = Quaternion(0, [1, 0, 0]) + assert qi.scalar == 0 + assert (qi.vector == [1, 0, 0]).all + qj = Quaternion(0, [0, 1, 0]) + assert qj.scalar == 0 + assert (qj.vector == [0, 1, 0]).all + qk = Quaternion(0, [0, 0, 1]) + assert qk.scalar == 0 + assert (qk.vector == [0, 0, 1]).all + # i^2 = j^2 = k^2 = -1: + assert qi*qi == -q1 + assert qj*qj == -q1 + assert qk*qk == -q1 + # identity: + assert q1*qi == qi + assert q1*qj == qj + assert q1*qk == qk + # i*j=k, j*k=i, k*i=j: + assert qi*qj == qk + assert qj*qk == qi + assert qk*qi == qj + assert qj*qi == -qk + assert qk*qj == -qi + assert qi*qk == -qj + # __mul__: + assert (Quaternion(2, [3, 4, 5]) * Quaternion(6, [7, 8, 9]) + == Quaternion(-86, [28, 48, 44])) + # conjugate(): + for q in [q1, qi, qj, qk]: + assert q.conjugate().scalar == q.scalar + assert (q.conjugate().vector == -q.vector).all + assert q.conjugate().conjugate() == q + assert ((q*q.conjugate()).vector == 0).all + # norm: + q0 = Quaternion(0, [0, 0, 0]) + assert q0.norm == 0 + assert q1.norm == 1 + assert qi.norm == 1 + assert qj.norm == 1 + assert qk.norm == 1 + for q in [q0, q1, qi, qj, qk]: + assert q.norm == (q*q.conjugate()).scalar + # normalize(): + for q in [ + Quaternion(2, [0, 0, 0]), + Quaternion(0, [3, 0, 0]), + Quaternion(0, [0, 4, 0]), + Quaternion(0, [0, 0, 5]), + Quaternion(6, [7, 8, 9]) + ]: + assert q.normalize().norm == 1 + # reciprocal(): + for q in [q1, qi, qj, qk]: + assert q*q.reciprocal() == q1 + assert q.reciprocal()*q == q1 + # rotate(): + assert (qi.rotate([1, 2, 3]) == np.array([1, -2, -3])).all + # rotate_from_to(): + for r1, r2, q in [ + ([1, 0, 0], [0, 1, 0], Quaternion(np.sqrt(1/2), [0, 0, np.sqrt(1/2)])), + ([1, 0, 0], [0, 0, 1], Quaternion(np.sqrt(1/2), [0, -np.sqrt(1/2), 0])), + ([1, 0, 0], [1, 0, 0], Quaternion(1, [0, 0, 0])) + ]: + assert Quaternion.rotate_from_to(r1, r2) == q + # rotate_from_to(), special case: + for r1 in [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 1]]: + r1 = np.array(r1) + with pytest.warns(UserWarning): + q = Quaternion.rotate_from_to(r1, -r1) + assert np.isclose(q.norm, 1) + assert np.dot(q.vector, r1) == 0 + # from_cardan_angles(), as_cardan_angles(): + for elev, azim, roll in [(0, 0, 0), + (90, 0, 0), (0, 90, 0), (0, 0, 90), + (0, 30, 30), (30, 0, 30), (30, 30, 0), + (47, 11, -24)]: + for mag in [1, 2]: + q = Quaternion.from_cardan_angles( + np.deg2rad(elev), np.deg2rad(azim), np.deg2rad(roll)) + assert np.isclose(q.norm, 1) + q = Quaternion(mag * q.scalar, mag * q.vector) + np.testing.assert_allclose(np.rad2deg(Quaternion.as_cardan_angles(q)), + (elev, azim, roll), atol=1e-6) + + +@pytest.mark.parametrize('style', + ('azel', 'trackball', 'sphere', 'arcball')) +def test_rotate(style): + """Test rotating using the left mouse button.""" + if style == 'azel': + s = 0.5 + else: + s = mpl.rcParams['axes3d.trackballsize'] / 2 + s *= 0.5 + mpl.rcParams['axes3d.trackballborder'] = 0 + with mpl.rc_context({'axes3d.mouserotationstyle': style}): + for roll, dx, dy in [ + [0, 1, 0], + [30, 1, 0], + [0, 0, 1], + [30, 0, 1], + [0, 0.5, np.sqrt(3)/2], + [30, 0.5, np.sqrt(3)/2], + [0, 2, 0]]: + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection='3d') + ax.view_init(0, 0, roll) + ax.figure.canvas.draw() + + # drag mouse to change orientation + ax._button_press( + mock_event(ax, button=MouseButton.LEFT, xdata=0, ydata=0)) + ax._on_move( + mock_event(ax, button=MouseButton.LEFT, + xdata=s*dx*ax._pseudo_w, ydata=s*dy*ax._pseudo_h)) + ax.figure.canvas.draw() + + c = np.sqrt(3)/2 + expectations = { + ('azel', 0, 1, 0): (0, -45, 0), + ('azel', 0, 0, 1): (-45, 0, 0), + ('azel', 0, 0.5, c): (-38.971143, -22.5, 0), + ('azel', 0, 2, 0): (0, -90, 0), + ('azel', 30, 1, 0): (22.5, -38.971143, 30), + ('azel', 30, 0, 1): (-38.971143, -22.5, 30), + ('azel', 30, 0.5, c): (-22.5, -38.971143, 30), + + ('trackball', 0, 1, 0): (0, -28.64789, 0), + ('trackball', 0, 0, 1): (-28.64789, 0, 0), + ('trackball', 0, 0.5, c): (-24.531578, -15.277726, 3.340403), + ('trackball', 0, 2, 0): (0, -180/np.pi, 0), + ('trackball', 30, 1, 0): (13.869588, -25.319385, 26.87008), + ('trackball', 30, 0, 1): (-24.531578, -15.277726, 33.340403), + ('trackball', 30, 0.5, c): (-13.869588, -25.319385, 33.129920), + + ('sphere', 0, 1, 0): (0, -30, 0), + ('sphere', 0, 0, 1): (-30, 0, 0), + ('sphere', 0, 0.5, c): (-25.658906, -16.102114, 3.690068), + ('sphere', 0, 2, 0): (0, -90, 0), + ('sphere', 30, 1, 0): (14.477512, -26.565051, 26.565051), + ('sphere', 30, 0, 1): (-25.658906, -16.102114, 33.690068), + ('sphere', 30, 0.5, c): (-14.477512, -26.565051, 33.434949), + + ('arcball', 0, 1, 0): (0, -60, 0), + ('arcball', 0, 0, 1): (-60, 0, 0), + ('arcball', 0, 0.5, c): (-48.590378, -40.893395, 19.106605), + ('arcball', 0, 2, 0): (0, 180, 0), + ('arcball', 30, 1, 0): (25.658906, -56.309932, 16.102114), + ('arcball', 30, 0, 1): (-48.590378, -40.893395, 49.106605), + ('arcball', 30, 0.5, c): (-25.658906, -56.309932, 43.897886)} + new_elev, new_azim, new_roll = expectations[(style, roll, dx, dy)] + np.testing.assert_allclose((ax.elev, ax.azim, ax.roll), + (new_elev, new_azim, new_roll), atol=1e-6) + + +def test_pan(): + """Test mouse panning using the middle mouse button.""" + + def convert_lim(dmin, dmax): + """Convert min/max limits to center and range.""" + center = (dmin + dmax) / 2 + range_ = dmax - dmin + return center, range_ + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.scatter(0, 0, 0) + fig.canvas.draw() + + x_center0, x_range0 = convert_lim(*ax.get_xlim3d()) + y_center0, y_range0 = convert_lim(*ax.get_ylim3d()) + z_center0, z_range0 = convert_lim(*ax.get_zlim3d()) + + # move mouse diagonally to pan along all axis. + ax._button_press( + mock_event(ax, button=MouseButton.MIDDLE, xdata=0, ydata=0)) + ax._on_move( + mock_event(ax, button=MouseButton.MIDDLE, xdata=1, ydata=1)) + + x_center, x_range = convert_lim(*ax.get_xlim3d()) + y_center, y_range = convert_lim(*ax.get_ylim3d()) + z_center, z_range = convert_lim(*ax.get_zlim3d()) + + # Ranges have not changed + assert x_range == pytest.approx(x_range0) + assert y_range == pytest.approx(y_range0) + assert z_range == pytest.approx(z_range0) + + # But center positions have + assert x_center != pytest.approx(x_center0) + assert y_center != pytest.approx(y_center0) + assert z_center != pytest.approx(z_center0) + + +@pytest.mark.parametrize("tool,button,key,expected", + [("zoom", MouseButton.LEFT, None, # zoom in + ((0.00, 0.06), (0.01, 0.07), (0.02, 0.08))), + ("zoom", MouseButton.LEFT, 'x', # zoom in + ((-0.01, 0.10), (-0.03, 0.08), (-0.06, 0.06))), + ("zoom", MouseButton.LEFT, 'y', # zoom in + ((-0.07, 0.05), (-0.04, 0.08), (0.00, 0.12))), + ("zoom", MouseButton.RIGHT, None, # zoom out + ((-0.09, 0.15), (-0.08, 0.17), (-0.07, 0.18))), + ("pan", MouseButton.LEFT, None, + ((-0.70, -0.58), (-1.04, -0.91), (-1.27, -1.15))), + ("pan", MouseButton.LEFT, 'x', + ((-0.97, -0.84), (-0.58, -0.46), (-0.06, 0.06))), + ("pan", MouseButton.LEFT, 'y', + ((0.20, 0.32), (-0.51, -0.39), (-1.27, -1.15)))]) +def test_toolbar_zoom_pan(tool, button, key, expected): + # NOTE: The expected zoom values are rough ballparks of moving in the view + # to make sure we are getting the right direction of motion. + # The specific values can and should change if the zoom movement + # scaling factor gets updated. + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.scatter(0, 0, 0) + fig.canvas.draw() + xlim0, ylim0, zlim0 = ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d() + + # Mouse from (0, 0) to (1, 1) + d0 = (0, 0) + d1 = (1, 1) + # Convert to screen coordinates ("s"). Events are defined only with pixel + # precision, so round the pixel values, and below, check against the + # corresponding xdata/ydata, which are close but not equal to d0/d1. + s0 = ax.transData.transform(d0).astype(int) + s1 = ax.transData.transform(d1).astype(int) + + # Set up the mouse movements + start_event = MouseEvent( + "button_press_event", fig.canvas, *s0, button, key=key) + stop_event = MouseEvent( + "button_release_event", fig.canvas, *s1, button, key=key) + + tb = NavigationToolbar2(fig.canvas) + if tool == "zoom": + tb.zoom() + tb.press_zoom(start_event) + tb.drag_zoom(stop_event) + tb.release_zoom(stop_event) + else: + tb.pan() + tb.press_pan(start_event) + tb.drag_pan(stop_event) + tb.release_pan(stop_event) + + # Should be close, but won't be exact due to screen integer resolution + xlim, ylim, zlim = expected + assert ax.get_xlim3d() == pytest.approx(xlim, abs=0.01) + assert ax.get_ylim3d() == pytest.approx(ylim, abs=0.01) + assert ax.get_zlim3d() == pytest.approx(zlim, abs=0.01) + + # Ensure that back, forward, and home buttons work + tb.back() + assert ax.get_xlim3d() == pytest.approx(xlim0) + assert ax.get_ylim3d() == pytest.approx(ylim0) + assert ax.get_zlim3d() == pytest.approx(zlim0) + + tb.forward() + assert ax.get_xlim3d() == pytest.approx(xlim, abs=0.01) + assert ax.get_ylim3d() == pytest.approx(ylim, abs=0.01) + assert ax.get_zlim3d() == pytest.approx(zlim, abs=0.01) + + tb.home() + assert ax.get_xlim3d() == pytest.approx(xlim0) + assert ax.get_ylim3d() == pytest.approx(ylim0) + assert ax.get_zlim3d() == pytest.approx(zlim0) + + +@mpl.style.context('default') +@check_figures_equal(extensions=["png"]) +def test_scalarmap_update(fig_test, fig_ref): + + x, y, z = np.array(list(itertools.product(*[np.arange(0, 5, 1), + np.arange(0, 5, 1), + np.arange(0, 5, 1)]))).T + c = x + y + + # test + ax_test = fig_test.add_subplot(111, projection='3d') + sc_test = ax_test.scatter(x, y, z, c=c, s=40, cmap='viridis') + # force a draw + fig_test.canvas.draw() + # mark it as "stale" + sc_test.changed() + + # ref + ax_ref = fig_ref.add_subplot(111, projection='3d') + sc_ref = ax_ref.scatter(x, y, z, c=c, s=40, cmap='viridis') + + +def test_subfigure_simple(): + # smoketest that subfigures can work... + fig = plt.figure() + sf = fig.subfigures(1, 2) + ax = sf[0].add_subplot(1, 1, 1, projection='3d') + ax = sf[1].add_subplot(1, 1, 1, projection='3d', label='other') + + +# Update style when regenerating the test image +@image_comparison(baseline_images=['computed_zorder'], remove_text=True, + extensions=['png'], style=('mpl20')) +def test_computed_zorder(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax1 = fig.add_subplot(221, projection='3d') + ax2 = fig.add_subplot(222, projection='3d') + ax2.computed_zorder = False + + # create a horizontal plane + corners = ((0, 0, 0), (0, 5, 0), (5, 5, 0), (5, 0, 0)) + for ax in (ax1, ax2): + tri = art3d.Poly3DCollection([corners], + facecolors='white', + edgecolors='black', + zorder=1) + ax.add_collection3d(tri) + + # plot a vector + ax.plot((2, 2), (2, 2), (0, 4), c='red', zorder=2) + + # plot some points + ax.scatter((3, 3), (1, 3), (1, 3), c='red', zorder=10) + + ax.set_xlim((0, 5.0)) + ax.set_ylim((0, 5.0)) + ax.set_zlim((0, 2.5)) + + ax3 = fig.add_subplot(223, projection='3d') + ax4 = fig.add_subplot(224, projection='3d') + ax4.computed_zorder = False + + dim = 10 + X, Y = np.meshgrid((-dim, dim), (-dim, dim)) + Z = np.zeros((2, 2)) + + angle = 0.5 + X2, Y2 = np.meshgrid((-dim, dim), (0, dim)) + Z2 = Y2 * angle + X3, Y3 = np.meshgrid((-dim, dim), (-dim, 0)) + Z3 = Y3 * angle + + r = 7 + M = 1000 + th = np.linspace(0, 2 * np.pi, M) + x, y, z = r * np.cos(th), r * np.sin(th), angle * r * np.sin(th) + for ax in (ax3, ax4): + ax.plot_surface(X2, Y3, Z3, + color='blue', + alpha=0.5, + linewidth=0, + zorder=-1) + ax.plot(x[y < 0], y[y < 0], z[y < 0], + lw=5, + linestyle='--', + color='green', + zorder=0) + + ax.plot_surface(X, Y, Z, + color='red', + alpha=0.5, + linewidth=0, + zorder=1) + + ax.plot(r * np.sin(th), r * np.cos(th), np.zeros(M), + lw=5, + linestyle='--', + color='black', + zorder=2) + + ax.plot_surface(X2, Y2, Z2, + color='blue', + alpha=0.5, + linewidth=0, + zorder=3) + + ax.plot(x[y > 0], y[y > 0], z[y > 0], lw=5, + linestyle='--', + color='green', + zorder=4) + ax.view_init(elev=20, azim=-20, roll=0) + ax.axis('off') + + +def test_format_coord(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + x = np.arange(10) + ax.plot(x, np.sin(x)) + xv = 0.1 + yv = 0.1 + fig.canvas.draw() + assert ax.format_coord(xv, yv) == 'x=10.5227, y pane=1.0417, z=0.1444' + + # Modify parameters + ax.view_init(roll=30, vertical_axis="y") + fig.canvas.draw() + assert ax.format_coord(xv, yv) == 'x pane=9.1875, y=0.9761, z=0.1291' + + # Reset parameters + ax.view_init() + fig.canvas.draw() + assert ax.format_coord(xv, yv) == 'x=10.5227, y pane=1.0417, z=0.1444' + + # Check orthographic projection + ax.set_proj_type('ortho') + fig.canvas.draw() + assert ax.format_coord(xv, yv) == 'x=10.8869, y pane=1.0417, z=0.1528' + + # Check non-default perspective projection + ax.set_proj_type('persp', focal_length=0.1) + fig.canvas.draw() + assert ax.format_coord(xv, yv) == 'x=9.0620, y pane=1.0417, z=0.1110' + + +def test_get_axis_position(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + x = np.arange(10) + ax.plot(x, np.sin(x)) + fig.canvas.draw() + assert ax.get_axis_position() == (False, True, False) + + +def test_margins(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.margins(0.2) + assert ax.margins() == (0.2, 0.2, 0.2) + ax.margins(0.1, 0.2, 0.3) + assert ax.margins() == (0.1, 0.2, 0.3) + ax.margins(x=0) + assert ax.margins() == (0, 0.2, 0.3) + ax.margins(y=0.1) + assert ax.margins() == (0, 0.1, 0.3) + ax.margins(z=0) + assert ax.margins() == (0, 0.1, 0) + + +def test_margin_getters(): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.margins(0.1, 0.2, 0.3) + assert ax.get_xmargin() == 0.1 + assert ax.get_ymargin() == 0.2 + assert ax.get_zmargin() == 0.3 + + +@pytest.mark.parametrize('err, args, kwargs, match', ( + (ValueError, (-1,), {}, r'margin must be greater than -0\.5'), + (ValueError, (1, -1, 1), {}, r'margin must be greater than -0\.5'), + (ValueError, (1, 1, -1), {}, r'margin must be greater than -0\.5'), + (ValueError, tuple(), {'x': -1}, r'margin must be greater than -0\.5'), + (ValueError, tuple(), {'y': -1}, r'margin must be greater than -0\.5'), + (ValueError, tuple(), {'z': -1}, r'margin must be greater than -0\.5'), + (TypeError, (1, ), {'x': 1}, + 'Cannot pass both positional and keyword'), + (TypeError, (1, ), {'x': 1, 'y': 1, 'z': 1}, + 'Cannot pass both positional and keyword'), + (TypeError, (1, ), {'x': 1, 'y': 1}, + 'Cannot pass both positional and keyword'), + (TypeError, (1, 1), {}, 'Must pass a single positional argument for'), +)) +def test_margins_errors(err, args, kwargs, match): + with pytest.raises(err, match=match): + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.margins(*args, **kwargs) + + +@check_figures_equal(extensions=["png"]) +def test_text_3d(fig_test, fig_ref): + ax = fig_ref.add_subplot(projection="3d") + txt = Text(0.5, 0.5, r'Foo bar $\int$') + art3d.text_2d_to_3d(txt, z=1) + ax.add_artist(txt) + assert txt.get_position_3d() == (0.5, 0.5, 1) + + ax = fig_test.add_subplot(projection="3d") + t3d = art3d.Text3D(0.5, 0.5, 1, r'Foo bar $\int$') + ax.add_artist(t3d) + assert t3d.get_position_3d() == (0.5, 0.5, 1) + + +def test_draw_single_lines_from_Nx1(): + # Smoke test for GH#23459 + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + ax.plot([[0], [1]], [[0], [1]], [[0], [1]]) + + +@check_figures_equal(extensions=["png"]) +def test_pathpatch_3d(fig_test, fig_ref): + ax = fig_ref.add_subplot(projection="3d") + path = Path.unit_rectangle() + patch = PathPatch(path) + art3d.pathpatch_2d_to_3d(patch, z=(0, 0.5, 0.7, 1, 0), zdir='y') + ax.add_artist(patch) + + ax = fig_test.add_subplot(projection="3d") + pp3d = art3d.PathPatch3D(path, zs=(0, 0.5, 0.7, 1, 0), zdir='y') + ax.add_artist(pp3d) + + +@image_comparison(baseline_images=['scatter_spiral.png'], + remove_text=True, + style='mpl20') +def test_scatter_spiral(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + th = np.linspace(0, 2 * np.pi * 6, 256) + sc = ax.scatter(np.sin(th), np.cos(th), th, s=(1 + th * 5), c=th ** 2) + + # force at least 1 draw! + fig.canvas.draw() + + +def test_Poly3DCollection_get_path(): + # Smoke test to see that get_path does not raise + # See GH#27361 + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + p = Circle((0, 0), 1.0) + ax.add_patch(p) + art3d.pathpatch_2d_to_3d(p) + p.get_path() + + +def test_Poly3DCollection_get_facecolor(): + # Smoke test to see that get_facecolor does not raise + # See GH#4067 + y, x = np.ogrid[1:10:100j, 1:10:100j] + z2 = np.cos(x) ** 3 - np.sin(y) ** 2 + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + r = ax.plot_surface(x, y, z2, cmap='hot') + r.get_facecolor() + + +def test_Poly3DCollection_get_edgecolor(): + # Smoke test to see that get_edgecolor does not raise + # See GH#4067 + y, x = np.ogrid[1:10:100j, 1:10:100j] + z2 = np.cos(x) ** 3 - np.sin(y) ** 2 + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + r = ax.plot_surface(x, y, z2, cmap='hot') + r.get_edgecolor() + + +@pytest.mark.parametrize( + "vertical_axis, proj_expected, axis_lines_expected, tickdirs_expected", + [ + ( + "z", + [ + [0.0, 1.142857, 0.0, -0.571429], + [0.0, 0.0, 0.857143, -0.428571], + [0.0, 0.0, 0.0, -10.0], + [-1.142857, 0.0, 0.0, 10.571429], + ], + [ + ([0.05617978, 0.06329114], [-0.04213483, -0.04746835]), + ([-0.06329114, 0.06329114], [-0.04746835, -0.04746835]), + ([-0.06329114, -0.06329114], [-0.04746835, 0.04746835]), + ], + [1, 0, 0], + ), + ( + "y", + [ + [1.142857, 0.0, 0.0, -0.571429], + [0.0, 0.857143, 0.0, -0.428571], + [0.0, 0.0, 0.0, -10.0], + [0.0, 0.0, -1.142857, 10.571429], + ], + [ + ([-0.06329114, 0.06329114], [0.04746835, 0.04746835]), + ([0.06329114, 0.06329114], [-0.04746835, 0.04746835]), + ([-0.05617978, -0.06329114], [0.04213483, 0.04746835]), + ], + [2, 2, 0], + ), + ( + "x", + [ + [0.0, 0.0, 1.142857, -0.571429], + [0.857143, 0.0, 0.0, -0.428571], + [0.0, 0.0, 0.0, -10.0], + [0.0, -1.142857, 0.0, 10.571429], + ], + [ + ([-0.06329114, -0.06329114], [0.04746835, -0.04746835]), + ([0.06329114, 0.05617978], [0.04746835, 0.04213483]), + ([0.06329114, -0.06329114], [0.04746835, 0.04746835]), + ], + [1, 2, 1], + ), + ], +) +def test_view_init_vertical_axis( + vertical_axis, proj_expected, axis_lines_expected, tickdirs_expected +): + """ + Test the actual projection, axis lines and ticks matches expected values. + + Parameters + ---------- + vertical_axis : str + Axis to align vertically. + proj_expected : ndarray + Expected values from ax.get_proj(). + axis_lines_expected : tuple of arrays + Edgepoints of the axis line. Expected values retrieved according + to ``ax.get_[xyz]axis().line.get_data()``. + tickdirs_expected : list of int + indexes indicating which axis to create a tick line along. + """ + rtol = 2e-06 + ax = plt.subplot(1, 1, 1, projection="3d") + ax.view_init(elev=0, azim=0, roll=0, vertical_axis=vertical_axis) + ax.get_figure().canvas.draw() + + # Assert the projection matrix: + proj_actual = ax.get_proj() + np.testing.assert_allclose(proj_expected, proj_actual, rtol=rtol) + + for i, axis in enumerate([ax.get_xaxis(), ax.get_yaxis(), ax.get_zaxis()]): + # Assert black lines are correctly aligned: + axis_line_expected = axis_lines_expected[i] + axis_line_actual = axis.line.get_data() + np.testing.assert_allclose(axis_line_expected, axis_line_actual, + rtol=rtol) + + # Assert ticks are correctly aligned: + tickdir_expected = tickdirs_expected[i] + tickdir_actual = axis._get_tickdir('default') + np.testing.assert_array_equal(tickdir_expected, tickdir_actual) + + +@pytest.mark.parametrize("vertical_axis", ["x", "y", "z"]) +def test_on_move_vertical_axis(vertical_axis: str) -> None: + """ + Test vertical axis is respected when rotating the plot interactively. + """ + ax = plt.subplot(1, 1, 1, projection="3d") + ax.view_init(elev=0, azim=0, roll=0, vertical_axis=vertical_axis) + ax.get_figure().canvas.draw() + + proj_before = ax.get_proj() + event_click = mock_event(ax, button=MouseButton.LEFT, xdata=0, ydata=1) + ax._button_press(event_click) + + event_move = mock_event(ax, button=MouseButton.LEFT, xdata=0.5, ydata=0.8) + ax._on_move(event_move) + + assert ax._axis_names.index(vertical_axis) == ax._vertical_axis + + # Make sure plot has actually moved: + proj_after = ax.get_proj() + np.testing.assert_raises( + AssertionError, np.testing.assert_allclose, proj_before, proj_after + ) + + +@pytest.mark.parametrize( + "vertical_axis, aspect_expected", + [ + ("x", [1.190476, 0.892857, 1.190476]), + ("y", [0.892857, 1.190476, 1.190476]), + ("z", [1.190476, 1.190476, 0.892857]), + ], +) +def test_set_box_aspect_vertical_axis(vertical_axis, aspect_expected): + ax = plt.subplot(1, 1, 1, projection="3d") + ax.view_init(elev=0, azim=0, roll=0, vertical_axis=vertical_axis) + ax.get_figure().canvas.draw() + + ax.set_box_aspect(None) + + np.testing.assert_allclose(aspect_expected, ax._box_aspect, rtol=1e-6) + + +@image_comparison(baseline_images=['arc_pathpatch.png'], + remove_text=True, + style='mpl20') +def test_arc_pathpatch(): + ax = plt.subplot(1, 1, 1, projection="3d") + a = mpatch.Arc((0.5, 0.5), width=0.5, height=0.9, + angle=20, theta1=10, theta2=130) + ax.add_patch(a) + art3d.pathpatch_2d_to_3d(a, z=0, zdir='z') + + +@image_comparison(baseline_images=['panecolor_rcparams.png'], + remove_text=True, + style='mpl20') +def test_panecolor_rcparams(): + with plt.rc_context({'axes3d.xaxis.panecolor': 'r', + 'axes3d.yaxis.panecolor': 'g', + 'axes3d.zaxis.panecolor': 'b'}): + fig = plt.figure(figsize=(1, 1)) + fig.add_subplot(projection='3d') + + +@check_figures_equal(extensions=["png"]) +def test_mutating_input_arrays_y_and_z(fig_test, fig_ref): + """ + Test to see if the `z` axis does not get mutated + after a call to `Axes3D.plot` + + test cases came from GH#8990 + """ + ax1 = fig_test.add_subplot(111, projection='3d') + x = [1, 2, 3] + y = [0.0, 0.0, 0.0] + z = [0.0, 0.0, 0.0] + ax1.plot(x, y, z, 'o-') + + # mutate y,z to get a nontrivial line + y[:] = [1, 2, 3] + z[:] = [1, 2, 3] + + # draw the same plot without mutating x and y + ax2 = fig_ref.add_subplot(111, projection='3d') + x = [1, 2, 3] + y = [0.0, 0.0, 0.0] + z = [0.0, 0.0, 0.0] + ax2.plot(x, y, z, 'o-') + + +def test_scatter_masked_color(): + """ + Test color parameter usage with non-finite coordinate arrays. + + GH#26236 + """ + + x = [np.nan, 1, 2, 1] + y = [0, np.inf, 2, 1] + z = [0, 1, -np.inf, 1] + colors = [ + [0.0, 0.0, 0.0, 1], + [0.0, 0.0, 0.0, 1], + [0.0, 0.0, 0.0, 1], + [0.0, 0.0, 0.0, 1] + ] + + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + path3d = ax.scatter(x, y, z, color=colors) + + # Assert sizes' equality + assert len(path3d.get_offsets()) ==\ + len(super(type(path3d), path3d).get_facecolors()) + + +@mpl3d_image_comparison(['surface3d_zsort_inf.png'], style='mpl20') +def test_surface3d_zsort_inf(): + plt.rcParams['axes3d.automargin'] = True # Remove when image is regenerated + fig = plt.figure() + ax = fig.add_subplot(projection='3d') + + x, y = np.mgrid[-2:2:0.1, -2:2:0.1] + z = np.sin(x)**2 + np.cos(y)**2 + z[x.shape[0] // 2:, x.shape[1] // 2:] = np.inf + + ax.plot_surface(x, y, z, cmap='jet') + ax.view_init(elev=45, azim=145) + + +def test_Poly3DCollection_init_value_error(): + # smoke test to ensure the input check works + # GH#26420 + with pytest.raises(ValueError, + match='You must provide facecolors, edgecolors, ' + 'or both for shade to work.'): + poly = np.array([[0, 0, 1], [0, 1, 1], [0, 0, 0]], float) + c = art3d.Poly3DCollection([poly], shade=True) + + +def test_ndarray_color_kwargs_value_error(): + # smoke test + # ensures ndarray can be passed to color in kwargs for 3d projection plot + fig = plt.figure() + ax = fig.add_subplot(111, projection='3d') + ax.scatter(1, 0, 0, color=np.array([0, 0, 0, 1])) + fig.canvas.draw() diff --git a/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_legend3d.py b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_legend3d.py new file mode 100644 index 0000000000000000000000000000000000000000..7fd676df1e31591f343a4a1bd27c27b98d564949 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/mpl_toolkits/mplot3d/tests/test_legend3d.py @@ -0,0 +1,117 @@ +import platform + +import numpy as np + +import matplotlib as mpl +from matplotlib.colors import same_color +from matplotlib.testing.decorators import image_comparison +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import art3d + + +@image_comparison(['legend_plot.png'], remove_text=True, style='mpl20') +def test_legend_plot(): + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + x = np.arange(10) + ax.plot(x, 5 - x, 'o', zdir='y', label='z=1') + ax.plot(x, x - 5, 'o', zdir='y', label='z=-1') + ax.legend() + + +@image_comparison(['legend_bar.png'], remove_text=True, style='mpl20') +def test_legend_bar(): + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + x = np.arange(10) + b1 = ax.bar(x, x, zdir='y', align='edge', color='m') + b2 = ax.bar(x, x[::-1], zdir='x', align='edge', color='g') + ax.legend([b1[0], b2[0]], ['up', 'down']) + + +@image_comparison(['fancy.png'], remove_text=True, style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.011) +def test_fancy(): + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + ax.plot(np.arange(10), np.full(10, 5), np.full(10, 5), 'o--', label='line') + ax.scatter(np.arange(10), np.arange(10, 0, -1), label='scatter') + ax.errorbar(np.full(10, 5), np.arange(10), np.full(10, 10), + xerr=0.5, zerr=0.5, label='errorbar') + ax.legend(loc='lower left', ncols=2, title='My legend', numpoints=1) + + +def test_linecollection_scaled_dashes(): + lines1 = [[(0, .5), (.5, 1)], [(.3, .6), (.2, .2)]] + lines2 = [[[0.7, .2], [.8, .4]], [[.5, .7], [.6, .1]]] + lines3 = [[[0.6, .2], [.8, .4]], [[.5, .7], [.1, .1]]] + lc1 = art3d.Line3DCollection(lines1, linestyles="--", lw=3) + lc2 = art3d.Line3DCollection(lines2, linestyles="-.") + lc3 = art3d.Line3DCollection(lines3, linestyles=":", lw=.5) + + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + ax.add_collection(lc1) + ax.add_collection(lc2) + ax.add_collection(lc3) + + leg = ax.legend([lc1, lc2, lc3], ['line1', 'line2', 'line 3']) + h1, h2, h3 = leg.legend_handles + + for oh, lh in zip((lc1, lc2, lc3), (h1, h2, h3)): + assert oh.get_linestyles()[0] == lh._dash_pattern + + +def test_handlerline3d(): + # Test marker consistency for monolithic Line3D legend handler. + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + ax.scatter([0, 1], [0, 1], marker="v") + handles = [art3d.Line3D([0], [0], [0], marker="v")] + leg = ax.legend(handles, ["Aardvark"], numpoints=1) + assert handles[0].get_marker() == leg.legend_handles[0].get_marker() + + +def test_contour_legend_elements(): + x, y = np.mgrid[1:10, 1:10] + h = x * y + colors = ['blue', '#00FF00', 'red'] + + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + cs = ax.contour(x, y, h, levels=[10, 30, 50], colors=colors, extend='both') + + artists, labels = cs.legend_elements() + assert labels == ['$x = 10.0$', '$x = 30.0$', '$x = 50.0$'] + assert all(isinstance(a, mpl.lines.Line2D) for a in artists) + assert all(same_color(a.get_color(), c) + for a, c in zip(artists, colors)) + + +def test_contourf_legend_elements(): + x, y = np.mgrid[1:10, 1:10] + h = x * y + + fig, ax = plt.subplots(subplot_kw=dict(projection='3d')) + cs = ax.contourf(x, y, h, levels=[10, 30, 50], + colors=['#FFFF00', '#FF00FF', '#00FFFF'], + extend='both') + cs.cmap.set_over('red') + cs.cmap.set_under('blue') + cs.changed() + artists, labels = cs.legend_elements() + assert labels == ['$x \\leq -1e+250s$', + '$10.0 < x \\leq 30.0$', + '$30.0 < x \\leq 50.0$', + '$x > 1e+250s$'] + expected_colors = ('blue', '#FFFF00', '#FF00FF', 'red') + assert all(isinstance(a, mpl.patches.Rectangle) for a in artists) + assert all(same_color(a.get_facecolor(), c) + for a, c in zip(artists, expected_colors)) + + +def test_legend_Poly3dCollection(): + + verts = np.asarray([[0, 0, 0], [0, 1, 1], [1, 0, 1]]) + mesh = art3d.Poly3DCollection([verts], label="surface") + + fig, ax = plt.subplots(subplot_kw={"projection": "3d"}) + mesh.set_edgecolor('k') + handle = ax.add_collection3d(mesh) + leg = ax.legend() + assert (leg.legend_handles[0].get_facecolor() + == handle.get_facecolor()).all() diff --git a/data/miniconda3/lib/python3.13/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt b/data/miniconda3/lib/python3.13/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt new file mode 100644 index 0000000000000000000000000000000000000000..0bf9a8f3f4922a0b70aac95ac7aab9574975342b --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/networkx-3.6.1.dist-info/licenses/LICENSE.txt @@ -0,0 +1,37 @@ +NetworkX is distributed with the 3-clause BSD license. + +:: + + Copyright (c) 2004-2025, NetworkX Developers + Aric Hagberg + Dan Schult + Pieter Swart + All rights reserved. + + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are + met: + + * Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + * Redistributions in binary form must reproduce the above + copyright notice, this list of conditions and the following + disclaimer in the documentation and/or other materials provided + with the distribution. + + * Neither the name of the NetworkX Developers nor the names of its + contributors may be used to endorse or promote products derived + from this software without specific prior written permission. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/pkce/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pkce/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..23ae95da0601dff561bddb6f26e4f1309cff7e6e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pkce/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0feb1560813164e98dba76122a06a6be1de31531 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_ast_gen.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_ast_gen.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..82f0aded841d7fe83080009fffbdef52c732b95f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_ast_gen.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_build_tables.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_build_tables.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f5e9c1fcf315ec7ed6074f16b7f5e57afc9b33d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/_build_tables.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/ast_transforms.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/ast_transforms.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0014424852fdf8559ae0fc425d5eb6fc060673a3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/ast_transforms.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_ast.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_ast.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2233a3aebf549c04b8d17b3e7782f953ccbacce1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_ast.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_generator.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_generator.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aed4b4415b904936478a0e7b9f41fc90b44f1a20 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_generator.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_lexer.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_lexer.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c50a0605b7c93d20e27d26e07113ae1420b65bb7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_lexer.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_parser.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11615d6be6309f8726c576303b8d664cf60abe6b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/c_parser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/lextab.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/lextab.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0021c74902199229d0b250f7aad324b21d81deec Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/lextab.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/plyparser.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/plyparser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fc14d93228ff6cd56c579ab0f808b1f02b170e4a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/__pycache__/plyparser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6e53cddcf6740cfb5317ce75efd7930c19e66f17 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__init__.py @@ -0,0 +1,5 @@ +# PLY package +# Author: David Beazley (dave@dabeaz.com) + +__version__ = '3.9' +__all__ = ['lex','yacc'] diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2118fbaed2d48ad3677960fc01bc3ab561349ad4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/cpp.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/cpp.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f0e59592f90087534a6644b2ba5be8b0ea7bc5b5 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/cpp.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ctokens.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ctokens.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4926a20fe3a5198d4c92581119f9ddb03306fd8c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ctokens.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/lex.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/lex.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..33502883e674f03e00f7cca08b7930ab6ed57456 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/lex.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ygen.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ygen.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b520440d9be7bbef0d78abc005b71ff583a93e2a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/__pycache__/ygen.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/cpp.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/cpp.py new file mode 100644 index 0000000000000000000000000000000000000000..86273eac77a5b404cb41cf4d2650d8a37415fb67 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/cpp.py @@ -0,0 +1,905 @@ +# ----------------------------------------------------------------------------- +# cpp.py +# +# Author: David Beazley (http://www.dabeaz.com) +# Copyright (C) 2017 +# All rights reserved +# +# This module implements an ANSI-C style lexical preprocessor for PLY. +# ----------------------------------------------------------------------------- +import sys + +# Some Python 3 compatibility shims +if sys.version_info.major < 3: + STRING_TYPES = (str, unicode) +else: + STRING_TYPES = str + xrange = range + +# ----------------------------------------------------------------------------- +# Default preprocessor lexer definitions. These tokens are enough to get +# a basic preprocessor working. Other modules may import these if they want +# ----------------------------------------------------------------------------- + +tokens = ( + 'CPP_ID','CPP_INTEGER', 'CPP_FLOAT', 'CPP_STRING', 'CPP_CHAR', 'CPP_WS', 'CPP_COMMENT1', 'CPP_COMMENT2', 'CPP_POUND','CPP_DPOUND' +) + +literals = "+-*/%|&~^<>=!?()[]{}.,;:\\\'\"" + +# Whitespace +def t_CPP_WS(t): + r'\s+' + t.lexer.lineno += t.value.count("\n") + return t + +t_CPP_POUND = r'\#' +t_CPP_DPOUND = r'\#\#' + +# Identifier +t_CPP_ID = r'[A-Za-z_][\w_]*' + +# Integer literal +def CPP_INTEGER(t): + r'(((((0x)|(0X))[0-9a-fA-F]+)|(\d+))([uU][lL]|[lL][uU]|[uU]|[lL])?)' + return t + +t_CPP_INTEGER = CPP_INTEGER + +# Floating literal +t_CPP_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?' + +# String literal +def t_CPP_STRING(t): + r'\"([^\\\n]|(\\(.|\n)))*?\"' + t.lexer.lineno += t.value.count("\n") + return t + +# Character constant 'c' or L'c' +def t_CPP_CHAR(t): + r'(L)?\'([^\\\n]|(\\(.|\n)))*?\'' + t.lexer.lineno += t.value.count("\n") + return t + +# Comment +def t_CPP_COMMENT1(t): + r'(/\*(.|\n)*?\*/)' + ncr = t.value.count("\n") + t.lexer.lineno += ncr + # replace with one space or a number of '\n' + t.type = 'CPP_WS'; t.value = '\n' * ncr if ncr else ' ' + return t + +# Line comment +def t_CPP_COMMENT2(t): + r'(//.*?(\n|$))' + # replace with '/n' + t.type = 'CPP_WS'; t.value = '\n' + return t + +def t_error(t): + t.type = t.value[0] + t.value = t.value[0] + t.lexer.skip(1) + return t + +import re +import copy +import time +import os.path + +# ----------------------------------------------------------------------------- +# trigraph() +# +# Given an input string, this function replaces all trigraph sequences. +# The following mapping is used: +# +# ??= # +# ??/ \ +# ??' ^ +# ??( [ +# ??) ] +# ??! | +# ??< { +# ??> } +# ??- ~ +# ----------------------------------------------------------------------------- + +_trigraph_pat = re.compile(r'''\?\?[=/\'\(\)\!<>\-]''') +_trigraph_rep = { + '=':'#', + '/':'\\', + "'":'^', + '(':'[', + ')':']', + '!':'|', + '<':'{', + '>':'}', + '-':'~' +} + +def trigraph(input): + return _trigraph_pat.sub(lambda g: _trigraph_rep[g.group()[-1]],input) + +# ------------------------------------------------------------------ +# Macro object +# +# This object holds information about preprocessor macros +# +# .name - Macro name (string) +# .value - Macro value (a list of tokens) +# .arglist - List of argument names +# .variadic - Boolean indicating whether or not variadic macro +# .vararg - Name of the variadic parameter +# +# When a macro is created, the macro replacement token sequence is +# pre-scanned and used to create patch lists that are later used +# during macro expansion +# ------------------------------------------------------------------ + +class Macro(object): + def __init__(self,name,value,arglist=None,variadic=False): + self.name = name + self.value = value + self.arglist = arglist + self.variadic = variadic + if variadic: + self.vararg = arglist[-1] + self.source = None + +# ------------------------------------------------------------------ +# Preprocessor object +# +# Object representing a preprocessor. Contains macro definitions, +# include directories, and other information +# ------------------------------------------------------------------ + +class Preprocessor(object): + def __init__(self,lexer=None): + if lexer is None: + lexer = lex.lexer + self.lexer = lexer + self.macros = { } + self.path = [] + self.temp_path = [] + + # Probe the lexer for selected tokens + self.lexprobe() + + tm = time.localtime() + self.define("__DATE__ \"%s\"" % time.strftime("%b %d %Y",tm)) + self.define("__TIME__ \"%s\"" % time.strftime("%H:%M:%S",tm)) + self.parser = None + + # ----------------------------------------------------------------------------- + # tokenize() + # + # Utility function. Given a string of text, tokenize into a list of tokens + # ----------------------------------------------------------------------------- + + def tokenize(self,text): + tokens = [] + self.lexer.input(text) + while True: + tok = self.lexer.token() + if not tok: break + tokens.append(tok) + return tokens + + # --------------------------------------------------------------------- + # error() + # + # Report a preprocessor error/warning of some kind + # ---------------------------------------------------------------------- + + def error(self,file,line,msg): + print("%s:%d %s" % (file,line,msg)) + + # ---------------------------------------------------------------------- + # lexprobe() + # + # This method probes the preprocessor lexer object to discover + # the token types of symbols that are important to the preprocessor. + # If this works right, the preprocessor will simply "work" + # with any suitable lexer regardless of how tokens have been named. + # ---------------------------------------------------------------------- + + def lexprobe(self): + + # Determine the token type for identifiers + self.lexer.input("identifier") + tok = self.lexer.token() + if not tok or tok.value != "identifier": + print("Couldn't determine identifier type") + else: + self.t_ID = tok.type + + # Determine the token type for integers + self.lexer.input("12345") + tok = self.lexer.token() + if not tok or int(tok.value) != 12345: + print("Couldn't determine integer type") + else: + self.t_INTEGER = tok.type + self.t_INTEGER_TYPE = type(tok.value) + + # Determine the token type for strings enclosed in double quotes + self.lexer.input("\"filename\"") + tok = self.lexer.token() + if not tok or tok.value != "\"filename\"": + print("Couldn't determine string type") + else: + self.t_STRING = tok.type + + # Determine the token type for whitespace--if any + self.lexer.input(" ") + tok = self.lexer.token() + if not tok or tok.value != " ": + self.t_SPACE = None + else: + self.t_SPACE = tok.type + + # Determine the token type for newlines + self.lexer.input("\n") + tok = self.lexer.token() + if not tok or tok.value != "\n": + self.t_NEWLINE = None + print("Couldn't determine token for newlines") + else: + self.t_NEWLINE = tok.type + + self.t_WS = (self.t_SPACE, self.t_NEWLINE) + + # Check for other characters used by the preprocessor + chars = [ '<','>','#','##','\\','(',')',',','.'] + for c in chars: + self.lexer.input(c) + tok = self.lexer.token() + if not tok or tok.value != c: + print("Unable to lex '%s' required for preprocessor" % c) + + # ---------------------------------------------------------------------- + # add_path() + # + # Adds a search path to the preprocessor. + # ---------------------------------------------------------------------- + + def add_path(self,path): + self.path.append(path) + + # ---------------------------------------------------------------------- + # group_lines() + # + # Given an input string, this function splits it into lines. Trailing whitespace + # is removed. Any line ending with \ is grouped with the next line. This + # function forms the lowest level of the preprocessor---grouping into text into + # a line-by-line format. + # ---------------------------------------------------------------------- + + def group_lines(self,input): + lex = self.lexer.clone() + lines = [x.rstrip() for x in input.splitlines()] + for i in xrange(len(lines)): + j = i+1 + while lines[i].endswith('\\') and (j < len(lines)): + lines[i] = lines[i][:-1]+lines[j] + lines[j] = "" + j += 1 + + input = "\n".join(lines) + lex.input(input) + lex.lineno = 1 + + current_line = [] + while True: + tok = lex.token() + if not tok: + break + current_line.append(tok) + if tok.type in self.t_WS and '\n' in tok.value: + yield current_line + current_line = [] + + if current_line: + yield current_line + + # ---------------------------------------------------------------------- + # tokenstrip() + # + # Remove leading/trailing whitespace tokens from a token list + # ---------------------------------------------------------------------- + + def tokenstrip(self,tokens): + i = 0 + while i < len(tokens) and tokens[i].type in self.t_WS: + i += 1 + del tokens[:i] + i = len(tokens)-1 + while i >= 0 and tokens[i].type in self.t_WS: + i -= 1 + del tokens[i+1:] + return tokens + + + # ---------------------------------------------------------------------- + # collect_args() + # + # Collects comma separated arguments from a list of tokens. The arguments + # must be enclosed in parenthesis. Returns a tuple (tokencount,args,positions) + # where tokencount is the number of tokens consumed, args is a list of arguments, + # and positions is a list of integers containing the starting index of each + # argument. Each argument is represented by a list of tokens. + # + # When collecting arguments, leading and trailing whitespace is removed + # from each argument. + # + # This function properly handles nested parenthesis and commas---these do not + # define new arguments. + # ---------------------------------------------------------------------- + + def collect_args(self,tokenlist): + args = [] + positions = [] + current_arg = [] + nesting = 1 + tokenlen = len(tokenlist) + + # Search for the opening '('. + i = 0 + while (i < tokenlen) and (tokenlist[i].type in self.t_WS): + i += 1 + + if (i < tokenlen) and (tokenlist[i].value == '('): + positions.append(i+1) + else: + self.error(self.source,tokenlist[0].lineno,"Missing '(' in macro arguments") + return 0, [], [] + + i += 1 + + while i < tokenlen: + t = tokenlist[i] + if t.value == '(': + current_arg.append(t) + nesting += 1 + elif t.value == ')': + nesting -= 1 + if nesting == 0: + if current_arg: + args.append(self.tokenstrip(current_arg)) + positions.append(i) + return i+1,args,positions + current_arg.append(t) + elif t.value == ',' and nesting == 1: + args.append(self.tokenstrip(current_arg)) + positions.append(i+1) + current_arg = [] + else: + current_arg.append(t) + i += 1 + + # Missing end argument + self.error(self.source,tokenlist[-1].lineno,"Missing ')' in macro arguments") + return 0, [],[] + + # ---------------------------------------------------------------------- + # macro_prescan() + # + # Examine the macro value (token sequence) and identify patch points + # This is used to speed up macro expansion later on---we'll know + # right away where to apply patches to the value to form the expansion + # ---------------------------------------------------------------------- + + def macro_prescan(self,macro): + macro.patch = [] # Standard macro arguments + macro.str_patch = [] # String conversion expansion + macro.var_comma_patch = [] # Variadic macro comma patch + i = 0 + while i < len(macro.value): + if macro.value[i].type == self.t_ID and macro.value[i].value in macro.arglist: + argnum = macro.arglist.index(macro.value[i].value) + # Conversion of argument to a string + if i > 0 and macro.value[i-1].value == '#': + macro.value[i] = copy.copy(macro.value[i]) + macro.value[i].type = self.t_STRING + del macro.value[i-1] + macro.str_patch.append((argnum,i-1)) + continue + # Concatenation + elif (i > 0 and macro.value[i-1].value == '##'): + macro.patch.append(('c',argnum,i-1)) + del macro.value[i-1] + continue + elif ((i+1) < len(macro.value) and macro.value[i+1].value == '##'): + macro.patch.append(('c',argnum,i)) + i += 1 + continue + # Standard expansion + else: + macro.patch.append(('e',argnum,i)) + elif macro.value[i].value == '##': + if macro.variadic and (i > 0) and (macro.value[i-1].value == ',') and \ + ((i+1) < len(macro.value)) and (macro.value[i+1].type == self.t_ID) and \ + (macro.value[i+1].value == macro.vararg): + macro.var_comma_patch.append(i-1) + i += 1 + macro.patch.sort(key=lambda x: x[2],reverse=True) + + # ---------------------------------------------------------------------- + # macro_expand_args() + # + # Given a Macro and list of arguments (each a token list), this method + # returns an expanded version of a macro. The return value is a token sequence + # representing the replacement macro tokens + # ---------------------------------------------------------------------- + + def macro_expand_args(self,macro,args): + # Make a copy of the macro token sequence + rep = [copy.copy(_x) for _x in macro.value] + + # Make string expansion patches. These do not alter the length of the replacement sequence + + str_expansion = {} + for argnum, i in macro.str_patch: + if argnum not in str_expansion: + str_expansion[argnum] = ('"%s"' % "".join([x.value for x in args[argnum]])).replace("\\","\\\\") + rep[i] = copy.copy(rep[i]) + rep[i].value = str_expansion[argnum] + + # Make the variadic macro comma patch. If the variadic macro argument is empty, we get rid + comma_patch = False + if macro.variadic and not args[-1]: + for i in macro.var_comma_patch: + rep[i] = None + comma_patch = True + + # Make all other patches. The order of these matters. It is assumed that the patch list + # has been sorted in reverse order of patch location since replacements will cause the + # size of the replacement sequence to expand from the patch point. + + expanded = { } + for ptype, argnum, i in macro.patch: + # Concatenation. Argument is left unexpanded + if ptype == 'c': + rep[i:i+1] = args[argnum] + # Normal expansion. Argument is macro expanded first + elif ptype == 'e': + if argnum not in expanded: + expanded[argnum] = self.expand_macros(args[argnum]) + rep[i:i+1] = expanded[argnum] + + # Get rid of removed comma if necessary + if comma_patch: + rep = [_i for _i in rep if _i] + + return rep + + + # ---------------------------------------------------------------------- + # expand_macros() + # + # Given a list of tokens, this function performs macro expansion. + # The expanded argument is a dictionary that contains macros already + # expanded. This is used to prevent infinite recursion. + # ---------------------------------------------------------------------- + + def expand_macros(self,tokens,expanded=None): + if expanded is None: + expanded = {} + i = 0 + while i < len(tokens): + t = tokens[i] + if t.type == self.t_ID: + if t.value in self.macros and t.value not in expanded: + # Yes, we found a macro match + expanded[t.value] = True + + m = self.macros[t.value] + if not m.arglist: + # A simple macro + ex = self.expand_macros([copy.copy(_x) for _x in m.value],expanded) + for e in ex: + e.lineno = t.lineno + tokens[i:i+1] = ex + i += len(ex) + else: + # A macro with arguments + j = i + 1 + while j < len(tokens) and tokens[j].type in self.t_WS: + j += 1 + if tokens[j].value == '(': + tokcount,args,positions = self.collect_args(tokens[j:]) + if not m.variadic and len(args) != len(m.arglist): + self.error(self.source,t.lineno,"Macro %s requires %d arguments" % (t.value,len(m.arglist))) + i = j + tokcount + elif m.variadic and len(args) < len(m.arglist)-1: + if len(m.arglist) > 2: + self.error(self.source,t.lineno,"Macro %s must have at least %d arguments" % (t.value, len(m.arglist)-1)) + else: + self.error(self.source,t.lineno,"Macro %s must have at least %d argument" % (t.value, len(m.arglist)-1)) + i = j + tokcount + else: + if m.variadic: + if len(args) == len(m.arglist)-1: + args.append([]) + else: + args[len(m.arglist)-1] = tokens[j+positions[len(m.arglist)-1]:j+tokcount-1] + del args[len(m.arglist):] + + # Get macro replacement text + rep = self.macro_expand_args(m,args) + rep = self.expand_macros(rep,expanded) + for r in rep: + r.lineno = t.lineno + tokens[i:j+tokcount] = rep + i += len(rep) + del expanded[t.value] + continue + elif t.value == '__LINE__': + t.type = self.t_INTEGER + t.value = self.t_INTEGER_TYPE(t.lineno) + + i += 1 + return tokens + + # ---------------------------------------------------------------------- + # evalexpr() + # + # Evaluate an expression token sequence for the purposes of evaluating + # integral expressions. + # ---------------------------------------------------------------------- + + def evalexpr(self,tokens): + # tokens = tokenize(line) + # Search for defined macros + i = 0 + while i < len(tokens): + if tokens[i].type == self.t_ID and tokens[i].value == 'defined': + j = i + 1 + needparen = False + result = "0L" + while j < len(tokens): + if tokens[j].type in self.t_WS: + j += 1 + continue + elif tokens[j].type == self.t_ID: + if tokens[j].value in self.macros: + result = "1L" + else: + result = "0L" + if not needparen: break + elif tokens[j].value == '(': + needparen = True + elif tokens[j].value == ')': + break + else: + self.error(self.source,tokens[i].lineno,"Malformed defined()") + j += 1 + tokens[i].type = self.t_INTEGER + tokens[i].value = self.t_INTEGER_TYPE(result) + del tokens[i+1:j+1] + i += 1 + tokens = self.expand_macros(tokens) + for i,t in enumerate(tokens): + if t.type == self.t_ID: + tokens[i] = copy.copy(t) + tokens[i].type = self.t_INTEGER + tokens[i].value = self.t_INTEGER_TYPE("0L") + elif t.type == self.t_INTEGER: + tokens[i] = copy.copy(t) + # Strip off any trailing suffixes + tokens[i].value = str(tokens[i].value) + while tokens[i].value[-1] not in "0123456789abcdefABCDEF": + tokens[i].value = tokens[i].value[:-1] + + expr = "".join([str(x.value) for x in tokens]) + expr = expr.replace("&&"," and ") + expr = expr.replace("||"," or ") + expr = expr.replace("!"," not ") + try: + result = eval(expr) + except Exception: + self.error(self.source,tokens[0].lineno,"Couldn't evaluate expression") + result = 0 + return result + + # ---------------------------------------------------------------------- + # parsegen() + # + # Parse an input string/ + # ---------------------------------------------------------------------- + def parsegen(self,input,source=None): + + # Replace trigraph sequences + t = trigraph(input) + lines = self.group_lines(t) + + if not source: + source = "" + + self.define("__FILE__ \"%s\"" % source) + + self.source = source + chunk = [] + enable = True + iftrigger = False + ifstack = [] + + for x in lines: + for i,tok in enumerate(x): + if tok.type not in self.t_WS: break + if tok.value == '#': + # Preprocessor directive + + # insert necessary whitespace instead of eaten tokens + for tok in x: + if tok.type in self.t_WS and '\n' in tok.value: + chunk.append(tok) + + dirtokens = self.tokenstrip(x[i+1:]) + if dirtokens: + name = dirtokens[0].value + args = self.tokenstrip(dirtokens[1:]) + else: + name = "" + args = [] + + if name == 'define': + if enable: + for tok in self.expand_macros(chunk): + yield tok + chunk = [] + self.define(args) + elif name == 'include': + if enable: + for tok in self.expand_macros(chunk): + yield tok + chunk = [] + oldfile = self.macros['__FILE__'] + for tok in self.include(args): + yield tok + self.macros['__FILE__'] = oldfile + self.source = source + elif name == 'undef': + if enable: + for tok in self.expand_macros(chunk): + yield tok + chunk = [] + self.undef(args) + elif name == 'ifdef': + ifstack.append((enable,iftrigger)) + if enable: + if not args[0].value in self.macros: + enable = False + iftrigger = False + else: + iftrigger = True + elif name == 'ifndef': + ifstack.append((enable,iftrigger)) + if enable: + if args[0].value in self.macros: + enable = False + iftrigger = False + else: + iftrigger = True + elif name == 'if': + ifstack.append((enable,iftrigger)) + if enable: + result = self.evalexpr(args) + if not result: + enable = False + iftrigger = False + else: + iftrigger = True + elif name == 'elif': + if ifstack: + if ifstack[-1][0]: # We only pay attention if outer "if" allows this + if enable: # If already true, we flip enable False + enable = False + elif not iftrigger: # If False, but not triggered yet, we'll check expression + result = self.evalexpr(args) + if result: + enable = True + iftrigger = True + else: + self.error(self.source,dirtokens[0].lineno,"Misplaced #elif") + + elif name == 'else': + if ifstack: + if ifstack[-1][0]: + if enable: + enable = False + elif not iftrigger: + enable = True + iftrigger = True + else: + self.error(self.source,dirtokens[0].lineno,"Misplaced #else") + + elif name == 'endif': + if ifstack: + enable,iftrigger = ifstack.pop() + else: + self.error(self.source,dirtokens[0].lineno,"Misplaced #endif") + else: + # Unknown preprocessor directive + pass + + else: + # Normal text + if enable: + chunk.extend(x) + + for tok in self.expand_macros(chunk): + yield tok + chunk = [] + + # ---------------------------------------------------------------------- + # include() + # + # Implementation of file-inclusion + # ---------------------------------------------------------------------- + + def include(self,tokens): + # Try to extract the filename and then process an include file + if not tokens: + return + if tokens: + if tokens[0].value != '<' and tokens[0].type != self.t_STRING: + tokens = self.expand_macros(tokens) + + if tokens[0].value == '<': + # Include <...> + i = 1 + while i < len(tokens): + if tokens[i].value == '>': + break + i += 1 + else: + print("Malformed #include <...>") + return + filename = "".join([x.value for x in tokens[1:i]]) + path = self.path + [""] + self.temp_path + elif tokens[0].type == self.t_STRING: + filename = tokens[0].value[1:-1] + path = self.temp_path + [""] + self.path + else: + print("Malformed #include statement") + return + for p in path: + iname = os.path.join(p,filename) + try: + data = open(iname,"r").read() + dname = os.path.dirname(iname) + if dname: + self.temp_path.insert(0,dname) + for tok in self.parsegen(data,filename): + yield tok + if dname: + del self.temp_path[0] + break + except IOError: + pass + else: + print("Couldn't find '%s'" % filename) + + # ---------------------------------------------------------------------- + # define() + # + # Define a new macro + # ---------------------------------------------------------------------- + + def define(self,tokens): + if isinstance(tokens,STRING_TYPES): + tokens = self.tokenize(tokens) + + linetok = tokens + try: + name = linetok[0] + if len(linetok) > 1: + mtype = linetok[1] + else: + mtype = None + if not mtype: + m = Macro(name.value,[]) + self.macros[name.value] = m + elif mtype.type in self.t_WS: + # A normal macro + m = Macro(name.value,self.tokenstrip(linetok[2:])) + self.macros[name.value] = m + elif mtype.value == '(': + # A macro with arguments + tokcount, args, positions = self.collect_args(linetok[1:]) + variadic = False + for a in args: + if variadic: + print("No more arguments may follow a variadic argument") + break + astr = "".join([str(_i.value) for _i in a]) + if astr == "...": + variadic = True + a[0].type = self.t_ID + a[0].value = '__VA_ARGS__' + variadic = True + del a[1:] + continue + elif astr[-3:] == "..." and a[0].type == self.t_ID: + variadic = True + del a[1:] + # If, for some reason, "." is part of the identifier, strip off the name for the purposes + # of macro expansion + if a[0].value[-3:] == '...': + a[0].value = a[0].value[:-3] + continue + if len(a) > 1 or a[0].type != self.t_ID: + print("Invalid macro argument") + break + else: + mvalue = self.tokenstrip(linetok[1+tokcount:]) + i = 0 + while i < len(mvalue): + if i+1 < len(mvalue): + if mvalue[i].type in self.t_WS and mvalue[i+1].value == '##': + del mvalue[i] + continue + elif mvalue[i].value == '##' and mvalue[i+1].type in self.t_WS: + del mvalue[i+1] + i += 1 + m = Macro(name.value,mvalue,[x[0].value for x in args],variadic) + self.macro_prescan(m) + self.macros[name.value] = m + else: + print("Bad macro definition") + except LookupError: + print("Bad macro definition") + + # ---------------------------------------------------------------------- + # undef() + # + # Undefine a macro + # ---------------------------------------------------------------------- + + def undef(self,tokens): + id = tokens[0].value + try: + del self.macros[id] + except LookupError: + pass + + # ---------------------------------------------------------------------- + # parse() + # + # Parse input text. + # ---------------------------------------------------------------------- + def parse(self,input,source=None,ignore={}): + self.ignore = ignore + self.parser = self.parsegen(input,source) + + # ---------------------------------------------------------------------- + # token() + # + # Method to return individual tokens + # ---------------------------------------------------------------------- + def token(self): + try: + while True: + tok = next(self.parser) + if tok.type not in self.ignore: return tok + except StopIteration: + self.parser = None + return None + +if __name__ == '__main__': + import ply.lex as lex + lexer = lex.lex() + + # Run a preprocessor + import sys + f = open(sys.argv[1]) + input = f.read() + + p = Preprocessor(lexer) + p.parse(input,sys.argv[1]) + while True: + tok = p.token() + if not tok: break + print(p.source, tok) diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ctokens.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ctokens.py new file mode 100644 index 0000000000000000000000000000000000000000..f6f6952d605ee5fa0a25eff03f18769b6b445fae --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ctokens.py @@ -0,0 +1,133 @@ +# ---------------------------------------------------------------------- +# ctokens.py +# +# Token specifications for symbols in ANSI C and C++. This file is +# meant to be used as a library in other tokenizers. +# ---------------------------------------------------------------------- + +# Reserved words + +tokens = [ + # Literals (identifier, integer constant, float constant, string constant, char const) + 'ID', 'TYPEID', 'INTEGER', 'FLOAT', 'STRING', 'CHARACTER', + + # Operators (+,-,*,/,%,|,&,~,^,<<,>>, ||, &&, !, <, <=, >, >=, ==, !=) + 'PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'MODULO', + 'OR', 'AND', 'NOT', 'XOR', 'LSHIFT', 'RSHIFT', + 'LOR', 'LAND', 'LNOT', + 'LT', 'LE', 'GT', 'GE', 'EQ', 'NE', + + # Assignment (=, *=, /=, %=, +=, -=, <<=, >>=, &=, ^=, |=) + 'EQUALS', 'TIMESEQUAL', 'DIVEQUAL', 'MODEQUAL', 'PLUSEQUAL', 'MINUSEQUAL', + 'LSHIFTEQUAL','RSHIFTEQUAL', 'ANDEQUAL', 'XOREQUAL', 'OREQUAL', + + # Increment/decrement (++,--) + 'INCREMENT', 'DECREMENT', + + # Structure dereference (->) + 'ARROW', + + # Ternary operator (?) + 'TERNARY', + + # Delimeters ( ) [ ] { } , . ; : + 'LPAREN', 'RPAREN', + 'LBRACKET', 'RBRACKET', + 'LBRACE', 'RBRACE', + 'COMMA', 'PERIOD', 'SEMI', 'COLON', + + # Ellipsis (...) + 'ELLIPSIS', +] + +# Operators +t_PLUS = r'\+' +t_MINUS = r'-' +t_TIMES = r'\*' +t_DIVIDE = r'/' +t_MODULO = r'%' +t_OR = r'\|' +t_AND = r'&' +t_NOT = r'~' +t_XOR = r'\^' +t_LSHIFT = r'<<' +t_RSHIFT = r'>>' +t_LOR = r'\|\|' +t_LAND = r'&&' +t_LNOT = r'!' +t_LT = r'<' +t_GT = r'>' +t_LE = r'<=' +t_GE = r'>=' +t_EQ = r'==' +t_NE = r'!=' + +# Assignment operators + +t_EQUALS = r'=' +t_TIMESEQUAL = r'\*=' +t_DIVEQUAL = r'/=' +t_MODEQUAL = r'%=' +t_PLUSEQUAL = r'\+=' +t_MINUSEQUAL = r'-=' +t_LSHIFTEQUAL = r'<<=' +t_RSHIFTEQUAL = r'>>=' +t_ANDEQUAL = r'&=' +t_OREQUAL = r'\|=' +t_XOREQUAL = r'\^=' + +# Increment/decrement +t_INCREMENT = r'\+\+' +t_DECREMENT = r'--' + +# -> +t_ARROW = r'->' + +# ? +t_TERNARY = r'\?' + +# Delimeters +t_LPAREN = r'\(' +t_RPAREN = r'\)' +t_LBRACKET = r'\[' +t_RBRACKET = r'\]' +t_LBRACE = r'\{' +t_RBRACE = r'\}' +t_COMMA = r',' +t_PERIOD = r'\.' +t_SEMI = r';' +t_COLON = r':' +t_ELLIPSIS = r'\.\.\.' + +# Identifiers +t_ID = r'[A-Za-z_][A-Za-z0-9_]*' + +# Integer literal +t_INTEGER = r'\d+([uU]|[lL]|[uU][lL]|[lL][uU])?' + +# Floating literal +t_FLOAT = r'((\d+)(\.\d+)(e(\+|-)?(\d+))? | (\d+)e(\+|-)?(\d+))([lL]|[fF])?' + +# String literal +t_STRING = r'\"([^\\\n]|(\\.))*?\"' + +# Character constant 'c' or L'c' +t_CHARACTER = r'(L)?\'([^\\\n]|(\\.))*?\'' + +# Comment (C-Style) +def t_COMMENT(t): + r'/\*(.|\n)*?\*/' + t.lexer.lineno += t.value.count('\n') + return t + +# Comment (C++-Style) +def t_CPPCOMMENT(t): + r'//.*\n' + t.lexer.lineno += 1 + return t + + + + + + diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/lex.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/lex.py new file mode 100644 index 0000000000000000000000000000000000000000..dfc5139486c1f675e86b968646e5f756547c2f46 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/lex.py @@ -0,0 +1,1099 @@ +# ----------------------------------------------------------------------------- +# ply: lex.py +# +# Copyright (C) 2001-2017 +# David M. Beazley (Dabeaz LLC) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the David Beazley or Dabeaz LLC may be used to +# endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------------------------- + +__version__ = '3.10' +__tabversion__ = '3.10' + +import re +import sys +import types +import copy +import os +import inspect + +# This tuple contains known string types +try: + # Python 2.6 + StringTypes = (types.StringType, types.UnicodeType) +except AttributeError: + # Python 3.0 + StringTypes = (str, bytes) + +# This regular expression is used to match valid token names +_is_identifier = re.compile(r'^[a-zA-Z0-9_]+$') + +# Exception thrown when invalid token encountered and no default error +# handler is defined. +class LexError(Exception): + def __init__(self, message, s): + self.args = (message,) + self.text = s + + +# Token class. This class is used to represent the tokens produced. +class LexToken(object): + def __str__(self): + return 'LexToken(%s,%r,%d,%d)' % (self.type, self.value, self.lineno, self.lexpos) + + def __repr__(self): + return str(self) + + +# This object is a stand-in for a logging object created by the +# logging module. + +class PlyLogger(object): + def __init__(self, f): + self.f = f + + def critical(self, msg, *args, **kwargs): + self.f.write((msg % args) + '\n') + + def warning(self, msg, *args, **kwargs): + self.f.write('WARNING: ' + (msg % args) + '\n') + + def error(self, msg, *args, **kwargs): + self.f.write('ERROR: ' + (msg % args) + '\n') + + info = critical + debug = critical + + +# Null logger is used when no output is generated. Does nothing. +class NullLogger(object): + def __getattribute__(self, name): + return self + + def __call__(self, *args, **kwargs): + return self + + +# ----------------------------------------------------------------------------- +# === Lexing Engine === +# +# The following Lexer class implements the lexer runtime. There are only +# a few public methods and attributes: +# +# input() - Store a new string in the lexer +# token() - Get the next token +# clone() - Clone the lexer +# +# lineno - Current line number +# lexpos - Current position in the input string +# ----------------------------------------------------------------------------- + +class Lexer: + def __init__(self): + self.lexre = None # Master regular expression. This is a list of + # tuples (re, findex) where re is a compiled + # regular expression and findex is a list + # mapping regex group numbers to rules + self.lexretext = None # Current regular expression strings + self.lexstatere = {} # Dictionary mapping lexer states to master regexs + self.lexstateretext = {} # Dictionary mapping lexer states to regex strings + self.lexstaterenames = {} # Dictionary mapping lexer states to symbol names + self.lexstate = 'INITIAL' # Current lexer state + self.lexstatestack = [] # Stack of lexer states + self.lexstateinfo = None # State information + self.lexstateignore = {} # Dictionary of ignored characters for each state + self.lexstateerrorf = {} # Dictionary of error functions for each state + self.lexstateeoff = {} # Dictionary of eof functions for each state + self.lexreflags = 0 # Optional re compile flags + self.lexdata = None # Actual input data (as a string) + self.lexpos = 0 # Current position in input text + self.lexlen = 0 # Length of the input text + self.lexerrorf = None # Error rule (if any) + self.lexeoff = None # EOF rule (if any) + self.lextokens = None # List of valid tokens + self.lexignore = '' # Ignored characters + self.lexliterals = '' # Literal characters that can be passed through + self.lexmodule = None # Module + self.lineno = 1 # Current line number + self.lexoptimize = False # Optimized mode + + def clone(self, object=None): + c = copy.copy(self) + + # If the object parameter has been supplied, it means we are attaching the + # lexer to a new object. In this case, we have to rebind all methods in + # the lexstatere and lexstateerrorf tables. + + if object: + newtab = {} + for key, ritem in self.lexstatere.items(): + newre = [] + for cre, findex in ritem: + newfindex = [] + for f in findex: + if not f or not f[0]: + newfindex.append(f) + continue + newfindex.append((getattr(object, f[0].__name__), f[1])) + newre.append((cre, newfindex)) + newtab[key] = newre + c.lexstatere = newtab + c.lexstateerrorf = {} + for key, ef in self.lexstateerrorf.items(): + c.lexstateerrorf[key] = getattr(object, ef.__name__) + c.lexmodule = object + return c + + # ------------------------------------------------------------ + # writetab() - Write lexer information to a table file + # ------------------------------------------------------------ + def writetab(self, lextab, outputdir=''): + if isinstance(lextab, types.ModuleType): + raise IOError("Won't overwrite existing lextab module") + basetabmodule = lextab.split('.')[-1] + filename = os.path.join(outputdir, basetabmodule) + '.py' + with open(filename, 'w') as tf: + tf.write('# %s.py. This file automatically created by PLY (version %s). Don\'t edit!\n' % (basetabmodule, __version__)) + tf.write('_tabversion = %s\n' % repr(__tabversion__)) + tf.write('_lextokens = set(%s)\n' % repr(tuple(sorted(self.lextokens)))) + tf.write('_lexreflags = %s\n' % repr(self.lexreflags)) + tf.write('_lexliterals = %s\n' % repr(self.lexliterals)) + tf.write('_lexstateinfo = %s\n' % repr(self.lexstateinfo)) + + # Rewrite the lexstatere table, replacing function objects with function names + tabre = {} + for statename, lre in self.lexstatere.items(): + titem = [] + for (pat, func), retext, renames in zip(lre, self.lexstateretext[statename], self.lexstaterenames[statename]): + titem.append((retext, _funcs_to_names(func, renames))) + tabre[statename] = titem + + tf.write('_lexstatere = %s\n' % repr(tabre)) + tf.write('_lexstateignore = %s\n' % repr(self.lexstateignore)) + + taberr = {} + for statename, ef in self.lexstateerrorf.items(): + taberr[statename] = ef.__name__ if ef else None + tf.write('_lexstateerrorf = %s\n' % repr(taberr)) + + tabeof = {} + for statename, ef in self.lexstateeoff.items(): + tabeof[statename] = ef.__name__ if ef else None + tf.write('_lexstateeoff = %s\n' % repr(tabeof)) + + # ------------------------------------------------------------ + # readtab() - Read lexer information from a tab file + # ------------------------------------------------------------ + def readtab(self, tabfile, fdict): + if isinstance(tabfile, types.ModuleType): + lextab = tabfile + else: + exec('import %s' % tabfile) + lextab = sys.modules[tabfile] + + if getattr(lextab, '_tabversion', '0.0') != __tabversion__: + raise ImportError('Inconsistent PLY version') + + self.lextokens = lextab._lextokens + self.lexreflags = lextab._lexreflags + self.lexliterals = lextab._lexliterals + self.lextokens_all = self.lextokens | set(self.lexliterals) + self.lexstateinfo = lextab._lexstateinfo + self.lexstateignore = lextab._lexstateignore + self.lexstatere = {} + self.lexstateretext = {} + for statename, lre in lextab._lexstatere.items(): + titem = [] + txtitem = [] + for pat, func_name in lre: + titem.append((re.compile(pat, lextab._lexreflags), _names_to_funcs(func_name, fdict))) + + self.lexstatere[statename] = titem + self.lexstateretext[statename] = txtitem + + self.lexstateerrorf = {} + for statename, ef in lextab._lexstateerrorf.items(): + self.lexstateerrorf[statename] = fdict[ef] + + self.lexstateeoff = {} + for statename, ef in lextab._lexstateeoff.items(): + self.lexstateeoff[statename] = fdict[ef] + + self.begin('INITIAL') + + # ------------------------------------------------------------ + # input() - Push a new string into the lexer + # ------------------------------------------------------------ + def input(self, s): + # Pull off the first character to see if s looks like a string + c = s[:1] + if not isinstance(c, StringTypes): + raise ValueError('Expected a string') + self.lexdata = s + self.lexpos = 0 + self.lexlen = len(s) + + # ------------------------------------------------------------ + # begin() - Changes the lexing state + # ------------------------------------------------------------ + def begin(self, state): + if state not in self.lexstatere: + raise ValueError('Undefined state') + self.lexre = self.lexstatere[state] + self.lexretext = self.lexstateretext[state] + self.lexignore = self.lexstateignore.get(state, '') + self.lexerrorf = self.lexstateerrorf.get(state, None) + self.lexeoff = self.lexstateeoff.get(state, None) + self.lexstate = state + + # ------------------------------------------------------------ + # push_state() - Changes the lexing state and saves old on stack + # ------------------------------------------------------------ + def push_state(self, state): + self.lexstatestack.append(self.lexstate) + self.begin(state) + + # ------------------------------------------------------------ + # pop_state() - Restores the previous state + # ------------------------------------------------------------ + def pop_state(self): + self.begin(self.lexstatestack.pop()) + + # ------------------------------------------------------------ + # current_state() - Returns the current lexing state + # ------------------------------------------------------------ + def current_state(self): + return self.lexstate + + # ------------------------------------------------------------ + # skip() - Skip ahead n characters + # ------------------------------------------------------------ + def skip(self, n): + self.lexpos += n + + # ------------------------------------------------------------ + # opttoken() - Return the next token from the Lexer + # + # Note: This function has been carefully implemented to be as fast + # as possible. Don't make changes unless you really know what + # you are doing + # ------------------------------------------------------------ + def token(self): + # Make local copies of frequently referenced attributes + lexpos = self.lexpos + lexlen = self.lexlen + lexignore = self.lexignore + lexdata = self.lexdata + + while lexpos < lexlen: + # This code provides some short-circuit code for whitespace, tabs, and other ignored characters + if lexdata[lexpos] in lexignore: + lexpos += 1 + continue + + # Look for a regular expression match + for lexre, lexindexfunc in self.lexre: + m = lexre.match(lexdata, lexpos) + if not m: + continue + + # Create a token for return + tok = LexToken() + tok.value = m.group() + tok.lineno = self.lineno + tok.lexpos = lexpos + + i = m.lastindex + func, tok.type = lexindexfunc[i] + + if not func: + # If no token type was set, it's an ignored token + if tok.type: + self.lexpos = m.end() + return tok + else: + lexpos = m.end() + break + + lexpos = m.end() + + # If token is processed by a function, call it + + tok.lexer = self # Set additional attributes useful in token rules + self.lexmatch = m + self.lexpos = lexpos + + newtok = func(tok) + + # Every function must return a token, if nothing, we just move to next token + if not newtok: + lexpos = self.lexpos # This is here in case user has updated lexpos. + lexignore = self.lexignore # This is here in case there was a state change + break + + # Verify type of the token. If not in the token map, raise an error + if not self.lexoptimize: + if newtok.type not in self.lextokens_all: + raise LexError("%s:%d: Rule '%s' returned an unknown token type '%s'" % ( + func.__code__.co_filename, func.__code__.co_firstlineno, + func.__name__, newtok.type), lexdata[lexpos:]) + + return newtok + else: + # No match, see if in literals + if lexdata[lexpos] in self.lexliterals: + tok = LexToken() + tok.value = lexdata[lexpos] + tok.lineno = self.lineno + tok.type = tok.value + tok.lexpos = lexpos + self.lexpos = lexpos + 1 + return tok + + # No match. Call t_error() if defined. + if self.lexerrorf: + tok = LexToken() + tok.value = self.lexdata[lexpos:] + tok.lineno = self.lineno + tok.type = 'error' + tok.lexer = self + tok.lexpos = lexpos + self.lexpos = lexpos + newtok = self.lexerrorf(tok) + if lexpos == self.lexpos: + # Error method didn't change text position at all. This is an error. + raise LexError("Scanning error. Illegal character '%s'" % (lexdata[lexpos]), lexdata[lexpos:]) + lexpos = self.lexpos + if not newtok: + continue + return newtok + + self.lexpos = lexpos + raise LexError("Illegal character '%s' at index %d" % (lexdata[lexpos], lexpos), lexdata[lexpos:]) + + if self.lexeoff: + tok = LexToken() + tok.type = 'eof' + tok.value = '' + tok.lineno = self.lineno + tok.lexpos = lexpos + tok.lexer = self + self.lexpos = lexpos + newtok = self.lexeoff(tok) + return newtok + + self.lexpos = lexpos + 1 + if self.lexdata is None: + raise RuntimeError('No input string given with input()') + return None + + # Iterator interface + def __iter__(self): + return self + + def next(self): + t = self.token() + if t is None: + raise StopIteration + return t + + __next__ = next + +# ----------------------------------------------------------------------------- +# ==== Lex Builder === +# +# The functions and classes below are used to collect lexing information +# and build a Lexer object from it. +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# _get_regex(func) +# +# Returns the regular expression assigned to a function either as a doc string +# or as a .regex attribute attached by the @TOKEN decorator. +# ----------------------------------------------------------------------------- +def _get_regex(func): + return getattr(func, 'regex', func.__doc__) + +# ----------------------------------------------------------------------------- +# get_caller_module_dict() +# +# This function returns a dictionary containing all of the symbols defined within +# a caller further down the call stack. This is used to get the environment +# associated with the yacc() call if none was provided. +# ----------------------------------------------------------------------------- +def get_caller_module_dict(levels): + f = sys._getframe(levels) + ldict = f.f_globals.copy() + if f.f_globals != f.f_locals: + ldict.update(f.f_locals) + return ldict + +# ----------------------------------------------------------------------------- +# _funcs_to_names() +# +# Given a list of regular expression functions, this converts it to a list +# suitable for output to a table file +# ----------------------------------------------------------------------------- +def _funcs_to_names(funclist, namelist): + result = [] + for f, name in zip(funclist, namelist): + if f and f[0]: + result.append((name, f[1])) + else: + result.append(f) + return result + +# ----------------------------------------------------------------------------- +# _names_to_funcs() +# +# Given a list of regular expression function names, this converts it back to +# functions. +# ----------------------------------------------------------------------------- +def _names_to_funcs(namelist, fdict): + result = [] + for n in namelist: + if n and n[0]: + result.append((fdict[n[0]], n[1])) + else: + result.append(n) + return result + +# ----------------------------------------------------------------------------- +# _form_master_re() +# +# This function takes a list of all of the regex components and attempts to +# form the master regular expression. Given limitations in the Python re +# module, it may be necessary to break the master regex into separate expressions. +# ----------------------------------------------------------------------------- +def _form_master_re(relist, reflags, ldict, toknames): + if not relist: + return [] + regex = '|'.join(relist) + try: + lexre = re.compile(regex, reflags) + + # Build the index to function map for the matching engine + lexindexfunc = [None] * (max(lexre.groupindex.values()) + 1) + lexindexnames = lexindexfunc[:] + + for f, i in lexre.groupindex.items(): + handle = ldict.get(f, None) + if type(handle) in (types.FunctionType, types.MethodType): + lexindexfunc[i] = (handle, toknames[f]) + lexindexnames[i] = f + elif handle is not None: + lexindexnames[i] = f + if f.find('ignore_') > 0: + lexindexfunc[i] = (None, None) + else: + lexindexfunc[i] = (None, toknames[f]) + + return [(lexre, lexindexfunc)], [regex], [lexindexnames] + except Exception: + m = int(len(relist)/2) + if m == 0: + m = 1 + llist, lre, lnames = _form_master_re(relist[:m], reflags, ldict, toknames) + rlist, rre, rnames = _form_master_re(relist[m:], reflags, ldict, toknames) + return (llist+rlist), (lre+rre), (lnames+rnames) + +# ----------------------------------------------------------------------------- +# def _statetoken(s,names) +# +# Given a declaration name s of the form "t_" and a dictionary whose keys are +# state names, this function returns a tuple (states,tokenname) where states +# is a tuple of state names and tokenname is the name of the token. For example, +# calling this with s = "t_foo_bar_SPAM" might return (('foo','bar'),'SPAM') +# ----------------------------------------------------------------------------- +def _statetoken(s, names): + nonstate = 1 + parts = s.split('_') + for i, part in enumerate(parts[1:], 1): + if part not in names and part != 'ANY': + break + + if i > 1: + states = tuple(parts[1:i]) + else: + states = ('INITIAL',) + + if 'ANY' in states: + states = tuple(names) + + tokenname = '_'.join(parts[i:]) + return (states, tokenname) + + +# ----------------------------------------------------------------------------- +# LexerReflect() +# +# This class represents information needed to build a lexer as extracted from a +# user's input file. +# ----------------------------------------------------------------------------- +class LexerReflect(object): + def __init__(self, ldict, log=None, reflags=0): + self.ldict = ldict + self.error_func = None + self.tokens = [] + self.reflags = reflags + self.stateinfo = {'INITIAL': 'inclusive'} + self.modules = set() + self.error = False + self.log = PlyLogger(sys.stderr) if log is None else log + + # Get all of the basic information + def get_all(self): + self.get_tokens() + self.get_literals() + self.get_states() + self.get_rules() + + # Validate all of the information + def validate_all(self): + self.validate_tokens() + self.validate_literals() + self.validate_rules() + return self.error + + # Get the tokens map + def get_tokens(self): + tokens = self.ldict.get('tokens', None) + if not tokens: + self.log.error('No token list is defined') + self.error = True + return + + if not isinstance(tokens, (list, tuple)): + self.log.error('tokens must be a list or tuple') + self.error = True + return + + if not tokens: + self.log.error('tokens is empty') + self.error = True + return + + self.tokens = tokens + + # Validate the tokens + def validate_tokens(self): + terminals = {} + for n in self.tokens: + if not _is_identifier.match(n): + self.log.error("Bad token name '%s'", n) + self.error = True + if n in terminals: + self.log.warning("Token '%s' multiply defined", n) + terminals[n] = 1 + + # Get the literals specifier + def get_literals(self): + self.literals = self.ldict.get('literals', '') + if not self.literals: + self.literals = '' + + # Validate literals + def validate_literals(self): + try: + for c in self.literals: + if not isinstance(c, StringTypes) or len(c) > 1: + self.log.error('Invalid literal %s. Must be a single character', repr(c)) + self.error = True + + except TypeError: + self.log.error('Invalid literals specification. literals must be a sequence of characters') + self.error = True + + def get_states(self): + self.states = self.ldict.get('states', None) + # Build statemap + if self.states: + if not isinstance(self.states, (tuple, list)): + self.log.error('states must be defined as a tuple or list') + self.error = True + else: + for s in self.states: + if not isinstance(s, tuple) or len(s) != 2: + self.log.error("Invalid state specifier %s. Must be a tuple (statename,'exclusive|inclusive')", repr(s)) + self.error = True + continue + name, statetype = s + if not isinstance(name, StringTypes): + self.log.error('State name %s must be a string', repr(name)) + self.error = True + continue + if not (statetype == 'inclusive' or statetype == 'exclusive'): + self.log.error("State type for state %s must be 'inclusive' or 'exclusive'", name) + self.error = True + continue + if name in self.stateinfo: + self.log.error("State '%s' already defined", name) + self.error = True + continue + self.stateinfo[name] = statetype + + # Get all of the symbols with a t_ prefix and sort them into various + # categories (functions, strings, error functions, and ignore characters) + + def get_rules(self): + tsymbols = [f for f in self.ldict if f[:2] == 't_'] + + # Now build up a list of functions and a list of strings + self.toknames = {} # Mapping of symbols to token names + self.funcsym = {} # Symbols defined as functions + self.strsym = {} # Symbols defined as strings + self.ignore = {} # Ignore strings by state + self.errorf = {} # Error functions by state + self.eoff = {} # EOF functions by state + + for s in self.stateinfo: + self.funcsym[s] = [] + self.strsym[s] = [] + + if len(tsymbols) == 0: + self.log.error('No rules of the form t_rulename are defined') + self.error = True + return + + for f in tsymbols: + t = self.ldict[f] + states, tokname = _statetoken(f, self.stateinfo) + self.toknames[f] = tokname + + if hasattr(t, '__call__'): + if tokname == 'error': + for s in states: + self.errorf[s] = t + elif tokname == 'eof': + for s in states: + self.eoff[s] = t + elif tokname == 'ignore': + line = t.__code__.co_firstlineno + file = t.__code__.co_filename + self.log.error("%s:%d: Rule '%s' must be defined as a string", file, line, t.__name__) + self.error = True + else: + for s in states: + self.funcsym[s].append((f, t)) + elif isinstance(t, StringTypes): + if tokname == 'ignore': + for s in states: + self.ignore[s] = t + if '\\' in t: + self.log.warning("%s contains a literal backslash '\\'", f) + + elif tokname == 'error': + self.log.error("Rule '%s' must be defined as a function", f) + self.error = True + else: + for s in states: + self.strsym[s].append((f, t)) + else: + self.log.error('%s not defined as a function or string', f) + self.error = True + + # Sort the functions by line number + for f in self.funcsym.values(): + f.sort(key=lambda x: x[1].__code__.co_firstlineno) + + # Sort the strings by regular expression length + for s in self.strsym.values(): + s.sort(key=lambda x: len(x[1]), reverse=True) + + # Validate all of the t_rules collected + def validate_rules(self): + for state in self.stateinfo: + # Validate all rules defined by functions + + for fname, f in self.funcsym[state]: + line = f.__code__.co_firstlineno + file = f.__code__.co_filename + module = inspect.getmodule(f) + self.modules.add(module) + + tokname = self.toknames[fname] + if isinstance(f, types.MethodType): + reqargs = 2 + else: + reqargs = 1 + nargs = f.__code__.co_argcount + if nargs > reqargs: + self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__) + self.error = True + continue + + if nargs < reqargs: + self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__) + self.error = True + continue + + if not _get_regex(f): + self.log.error("%s:%d: No regular expression defined for rule '%s'", file, line, f.__name__) + self.error = True + continue + + try: + c = re.compile('(?P<%s>%s)' % (fname, _get_regex(f)), self.reflags) + if c.match(''): + self.log.error("%s:%d: Regular expression for rule '%s' matches empty string", file, line, f.__name__) + self.error = True + except re.error as e: + self.log.error("%s:%d: Invalid regular expression for rule '%s'. %s", file, line, f.__name__, e) + if '#' in _get_regex(f): + self.log.error("%s:%d. Make sure '#' in rule '%s' is escaped with '\\#'", file, line, f.__name__) + self.error = True + + # Validate all rules defined by strings + for name, r in self.strsym[state]: + tokname = self.toknames[name] + if tokname == 'error': + self.log.error("Rule '%s' must be defined as a function", name) + self.error = True + continue + + if tokname not in self.tokens and tokname.find('ignore_') < 0: + self.log.error("Rule '%s' defined for an unspecified token %s", name, tokname) + self.error = True + continue + + try: + c = re.compile('(?P<%s>%s)' % (name, r), self.reflags) + if (c.match('')): + self.log.error("Regular expression for rule '%s' matches empty string", name) + self.error = True + except re.error as e: + self.log.error("Invalid regular expression for rule '%s'. %s", name, e) + if '#' in r: + self.log.error("Make sure '#' in rule '%s' is escaped with '\\#'", name) + self.error = True + + if not self.funcsym[state] and not self.strsym[state]: + self.log.error("No rules defined for state '%s'", state) + self.error = True + + # Validate the error function + efunc = self.errorf.get(state, None) + if efunc: + f = efunc + line = f.__code__.co_firstlineno + file = f.__code__.co_filename + module = inspect.getmodule(f) + self.modules.add(module) + + if isinstance(f, types.MethodType): + reqargs = 2 + else: + reqargs = 1 + nargs = f.__code__.co_argcount + if nargs > reqargs: + self.log.error("%s:%d: Rule '%s' has too many arguments", file, line, f.__name__) + self.error = True + + if nargs < reqargs: + self.log.error("%s:%d: Rule '%s' requires an argument", file, line, f.__name__) + self.error = True + + for module in self.modules: + self.validate_module(module) + + # ----------------------------------------------------------------------------- + # validate_module() + # + # This checks to see if there are duplicated t_rulename() functions or strings + # in the parser input file. This is done using a simple regular expression + # match on each line in the source code of the given module. + # ----------------------------------------------------------------------------- + + def validate_module(self, module): + try: + lines, linen = inspect.getsourcelines(module) + except IOError: + return + + fre = re.compile(r'\s*def\s+(t_[a-zA-Z_0-9]*)\(') + sre = re.compile(r'\s*(t_[a-zA-Z_0-9]*)\s*=') + + counthash = {} + linen += 1 + for line in lines: + m = fre.match(line) + if not m: + m = sre.match(line) + if m: + name = m.group(1) + prev = counthash.get(name) + if not prev: + counthash[name] = linen + else: + filename = inspect.getsourcefile(module) + self.log.error('%s:%d: Rule %s redefined. Previously defined on line %d', filename, linen, name, prev) + self.error = True + linen += 1 + +# ----------------------------------------------------------------------------- +# lex(module) +# +# Build all of the regular expression rules from definitions in the supplied module +# ----------------------------------------------------------------------------- +def lex(module=None, object=None, debug=False, optimize=False, lextab='lextab', + reflags=int(re.VERBOSE), nowarn=False, outputdir=None, debuglog=None, errorlog=None): + + if lextab is None: + lextab = 'lextab' + + global lexer + + ldict = None + stateinfo = {'INITIAL': 'inclusive'} + lexobj = Lexer() + lexobj.lexoptimize = optimize + global token, input + + if errorlog is None: + errorlog = PlyLogger(sys.stderr) + + if debug: + if debuglog is None: + debuglog = PlyLogger(sys.stderr) + + # Get the module dictionary used for the lexer + if object: + module = object + + # Get the module dictionary used for the parser + if module: + _items = [(k, getattr(module, k)) for k in dir(module)] + ldict = dict(_items) + # If no __file__ attribute is available, try to obtain it from the __module__ instead + if '__file__' not in ldict: + ldict['__file__'] = sys.modules[ldict['__module__']].__file__ + else: + ldict = get_caller_module_dict(2) + + # Determine if the module is package of a package or not. + # If so, fix the tabmodule setting so that tables load correctly + pkg = ldict.get('__package__') + if pkg and isinstance(lextab, str): + if '.' not in lextab: + lextab = pkg + '.' + lextab + + # Collect parser information from the dictionary + linfo = LexerReflect(ldict, log=errorlog, reflags=reflags) + linfo.get_all() + if not optimize: + if linfo.validate_all(): + raise SyntaxError("Can't build lexer") + + if optimize and lextab: + try: + lexobj.readtab(lextab, ldict) + token = lexobj.token + input = lexobj.input + lexer = lexobj + return lexobj + + except ImportError: + pass + + # Dump some basic debugging information + if debug: + debuglog.info('lex: tokens = %r', linfo.tokens) + debuglog.info('lex: literals = %r', linfo.literals) + debuglog.info('lex: states = %r', linfo.stateinfo) + + # Build a dictionary of valid token names + lexobj.lextokens = set() + for n in linfo.tokens: + lexobj.lextokens.add(n) + + # Get literals specification + if isinstance(linfo.literals, (list, tuple)): + lexobj.lexliterals = type(linfo.literals[0])().join(linfo.literals) + else: + lexobj.lexliterals = linfo.literals + + lexobj.lextokens_all = lexobj.lextokens | set(lexobj.lexliterals) + + # Get the stateinfo dictionary + stateinfo = linfo.stateinfo + + regexs = {} + # Build the master regular expressions + for state in stateinfo: + regex_list = [] + + # Add rules defined by functions first + for fname, f in linfo.funcsym[state]: + line = f.__code__.co_firstlineno + file = f.__code__.co_filename + regex_list.append('(?P<%s>%s)' % (fname, _get_regex(f))) + if debug: + debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", fname, _get_regex(f), state) + + # Now add all of the simple rules + for name, r in linfo.strsym[state]: + regex_list.append('(?P<%s>%s)' % (name, r)) + if debug: + debuglog.info("lex: Adding rule %s -> '%s' (state '%s')", name, r, state) + + regexs[state] = regex_list + + # Build the master regular expressions + + if debug: + debuglog.info('lex: ==== MASTER REGEXS FOLLOW ====') + + for state in regexs: + lexre, re_text, re_names = _form_master_re(regexs[state], reflags, ldict, linfo.toknames) + lexobj.lexstatere[state] = lexre + lexobj.lexstateretext[state] = re_text + lexobj.lexstaterenames[state] = re_names + if debug: + for i, text in enumerate(re_text): + debuglog.info("lex: state '%s' : regex[%d] = '%s'", state, i, text) + + # For inclusive states, we need to add the regular expressions from the INITIAL state + for state, stype in stateinfo.items(): + if state != 'INITIAL' and stype == 'inclusive': + lexobj.lexstatere[state].extend(lexobj.lexstatere['INITIAL']) + lexobj.lexstateretext[state].extend(lexobj.lexstateretext['INITIAL']) + lexobj.lexstaterenames[state].extend(lexobj.lexstaterenames['INITIAL']) + + lexobj.lexstateinfo = stateinfo + lexobj.lexre = lexobj.lexstatere['INITIAL'] + lexobj.lexretext = lexobj.lexstateretext['INITIAL'] + lexobj.lexreflags = reflags + + # Set up ignore variables + lexobj.lexstateignore = linfo.ignore + lexobj.lexignore = lexobj.lexstateignore.get('INITIAL', '') + + # Set up error functions + lexobj.lexstateerrorf = linfo.errorf + lexobj.lexerrorf = linfo.errorf.get('INITIAL', None) + if not lexobj.lexerrorf: + errorlog.warning('No t_error rule is defined') + + # Set up eof functions + lexobj.lexstateeoff = linfo.eoff + lexobj.lexeoff = linfo.eoff.get('INITIAL', None) + + # Check state information for ignore and error rules + for s, stype in stateinfo.items(): + if stype == 'exclusive': + if s not in linfo.errorf: + errorlog.warning("No error rule is defined for exclusive state '%s'", s) + if s not in linfo.ignore and lexobj.lexignore: + errorlog.warning("No ignore rule is defined for exclusive state '%s'", s) + elif stype == 'inclusive': + if s not in linfo.errorf: + linfo.errorf[s] = linfo.errorf.get('INITIAL', None) + if s not in linfo.ignore: + linfo.ignore[s] = linfo.ignore.get('INITIAL', '') + + # Create global versions of the token() and input() functions + token = lexobj.token + input = lexobj.input + lexer = lexobj + + # If in optimize mode, we write the lextab + if lextab and optimize: + if outputdir is None: + # If no output directory is set, the location of the output files + # is determined according to the following rules: + # - If lextab specifies a package, files go into that package directory + # - Otherwise, files go in the same directory as the specifying module + if isinstance(lextab, types.ModuleType): + srcfile = lextab.__file__ + else: + if '.' not in lextab: + srcfile = ldict['__file__'] + else: + parts = lextab.split('.') + pkgname = '.'.join(parts[:-1]) + exec('import %s' % pkgname) + srcfile = getattr(sys.modules[pkgname], '__file__', '') + outputdir = os.path.dirname(srcfile) + try: + lexobj.writetab(lextab, outputdir) + except IOError as e: + errorlog.warning("Couldn't write lextab module %r. %s" % (lextab, e)) + + return lexobj + +# ----------------------------------------------------------------------------- +# runmain() +# +# This runs the lexer as a main program +# ----------------------------------------------------------------------------- + +def runmain(lexer=None, data=None): + if not data: + try: + filename = sys.argv[1] + f = open(filename) + data = f.read() + f.close() + except IndexError: + sys.stdout.write('Reading from standard input (type EOF to end):\n') + data = sys.stdin.read() + + if lexer: + _input = lexer.input + else: + _input = input + _input(data) + if lexer: + _token = lexer.token + else: + _token = token + + while True: + tok = _token() + if not tok: + break + sys.stdout.write('(%s,%r,%d,%d)\n' % (tok.type, tok.value, tok.lineno, tok.lexpos)) + +# ----------------------------------------------------------------------------- +# @TOKEN(regex) +# +# This decorator function can be used to set the regex expression on a function +# when its docstring might need to be set in an alternative way +# ----------------------------------------------------------------------------- + +def TOKEN(r): + def set_regex(f): + if hasattr(r, '__call__'): + f.regex = _get_regex(r) + else: + f.regex = r + return f + return set_regex + +# Alternative spelling of the TOKEN decorator +Token = TOKEN diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/yacc.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/yacc.py new file mode 100644 index 0000000000000000000000000000000000000000..20b4f2863cc7193ad4b779a30375c865495fa50c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/yacc.py @@ -0,0 +1,3494 @@ +# ----------------------------------------------------------------------------- +# ply: yacc.py +# +# Copyright (C) 2001-2017 +# David M. Beazley (Dabeaz LLC) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# * Neither the name of the David Beazley or Dabeaz LLC may be used to +# endorse or promote products derived from this software without +# specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ----------------------------------------------------------------------------- +# +# This implements an LR parser that is constructed from grammar rules defined +# as Python functions. The grammer is specified by supplying the BNF inside +# Python documentation strings. The inspiration for this technique was borrowed +# from John Aycock's Spark parsing system. PLY might be viewed as cross between +# Spark and the GNU bison utility. +# +# The current implementation is only somewhat object-oriented. The +# LR parser itself is defined in terms of an object (which allows multiple +# parsers to co-exist). However, most of the variables used during table +# construction are defined in terms of global variables. Users shouldn't +# notice unless they are trying to define multiple parsers at the same +# time using threads (in which case they should have their head examined). +# +# This implementation supports both SLR and LALR(1) parsing. LALR(1) +# support was originally implemented by Elias Ioup (ezioup@alumni.uchicago.edu), +# using the algorithm found in Aho, Sethi, and Ullman "Compilers: Principles, +# Techniques, and Tools" (The Dragon Book). LALR(1) has since been replaced +# by the more efficient DeRemer and Pennello algorithm. +# +# :::::::: WARNING ::::::: +# +# Construction of LR parsing tables is fairly complicated and expensive. +# To make this module run fast, a *LOT* of work has been put into +# optimization---often at the expensive of readability and what might +# consider to be good Python "coding style." Modify the code at your +# own risk! +# ---------------------------------------------------------------------------- + +import re +import types +import sys +import os.path +import inspect +import base64 +import warnings + +__version__ = '3.10' +__tabversion__ = '3.10' + +#----------------------------------------------------------------------------- +# === User configurable parameters === +# +# Change these to modify the default behavior of yacc (if you wish) +#----------------------------------------------------------------------------- + +yaccdebug = True # Debugging mode. If set, yacc generates a + # a 'parser.out' file in the current directory + +debug_file = 'parser.out' # Default name of the debugging file +tab_module = 'parsetab' # Default name of the table module +default_lr = 'LALR' # Default LR table generation method + +error_count = 3 # Number of symbols that must be shifted to leave recovery mode + +yaccdevel = False # Set to True if developing yacc. This turns off optimized + # implementations of certain functions. + +resultlimit = 40 # Size limit of results when running in debug mode. + +pickle_protocol = 0 # Protocol to use when writing pickle files + +# String type-checking compatibility +if sys.version_info[0] < 3: + string_types = basestring +else: + string_types = str + +MAXINT = sys.maxsize + +# This object is a stand-in for a logging object created by the +# logging module. PLY will use this by default to create things +# such as the parser.out file. If a user wants more detailed +# information, they can create their own logging object and pass +# it into PLY. + +class PlyLogger(object): + def __init__(self, f): + self.f = f + + def debug(self, msg, *args, **kwargs): + self.f.write((msg % args) + '\n') + + info = debug + + def warning(self, msg, *args, **kwargs): + self.f.write('WARNING: ' + (msg % args) + '\n') + + def error(self, msg, *args, **kwargs): + self.f.write('ERROR: ' + (msg % args) + '\n') + + critical = debug + +# Null logger is used when no output is generated. Does nothing. +class NullLogger(object): + def __getattribute__(self, name): + return self + + def __call__(self, *args, **kwargs): + return self + +# Exception raised for yacc-related errors +class YaccError(Exception): + pass + +# Format the result message that the parser produces when running in debug mode. +def format_result(r): + repr_str = repr(r) + if '\n' in repr_str: + repr_str = repr(repr_str) + if len(repr_str) > resultlimit: + repr_str = repr_str[:resultlimit] + ' ...' + result = '<%s @ 0x%x> (%s)' % (type(r).__name__, id(r), repr_str) + return result + +# Format stack entries when the parser is running in debug mode +def format_stack_entry(r): + repr_str = repr(r) + if '\n' in repr_str: + repr_str = repr(repr_str) + if len(repr_str) < 16: + return repr_str + else: + return '<%s @ 0x%x>' % (type(r).__name__, id(r)) + +# Panic mode error recovery support. This feature is being reworked--much of the +# code here is to offer a deprecation/backwards compatible transition + +_errok = None +_token = None +_restart = None +_warnmsg = '''PLY: Don't use global functions errok(), token(), and restart() in p_error(). +Instead, invoke the methods on the associated parser instance: + + def p_error(p): + ... + # Use parser.errok(), parser.token(), parser.restart() + ... + + parser = yacc.yacc() +''' + +def errok(): + warnings.warn(_warnmsg) + return _errok() + +def restart(): + warnings.warn(_warnmsg) + return _restart() + +def token(): + warnings.warn(_warnmsg) + return _token() + +# Utility function to call the p_error() function with some deprecation hacks +def call_errorfunc(errorfunc, token, parser): + global _errok, _token, _restart + _errok = parser.errok + _token = parser.token + _restart = parser.restart + r = errorfunc(token) + try: + del _errok, _token, _restart + except NameError: + pass + return r + +#----------------------------------------------------------------------------- +# === LR Parsing Engine === +# +# The following classes are used for the LR parser itself. These are not +# used during table construction and are independent of the actual LR +# table generation algorithm +#----------------------------------------------------------------------------- + +# This class is used to hold non-terminal grammar symbols during parsing. +# It normally has the following attributes set: +# .type = Grammar symbol type +# .value = Symbol value +# .lineno = Starting line number +# .endlineno = Ending line number (optional, set automatically) +# .lexpos = Starting lex position +# .endlexpos = Ending lex position (optional, set automatically) + +class YaccSymbol: + def __str__(self): + return self.type + + def __repr__(self): + return str(self) + +# This class is a wrapper around the objects actually passed to each +# grammar rule. Index lookup and assignment actually assign the +# .value attribute of the underlying YaccSymbol object. +# The lineno() method returns the line number of a given +# item (or 0 if not defined). The linespan() method returns +# a tuple of (startline,endline) representing the range of lines +# for a symbol. The lexspan() method returns a tuple (lexpos,endlexpos) +# representing the range of positional information for a symbol. + +class YaccProduction: + def __init__(self, s, stack=None): + self.slice = s + self.stack = stack + self.lexer = None + self.parser = None + + def __getitem__(self, n): + if isinstance(n, slice): + return [s.value for s in self.slice[n]] + elif n >= 0: + return self.slice[n].value + else: + return self.stack[n].value + + def __setitem__(self, n, v): + self.slice[n].value = v + + def __getslice__(self, i, j): + return [s.value for s in self.slice[i:j]] + + def __len__(self): + return len(self.slice) + + def lineno(self, n): + return getattr(self.slice[n], 'lineno', 0) + + def set_lineno(self, n, lineno): + self.slice[n].lineno = lineno + + def linespan(self, n): + startline = getattr(self.slice[n], 'lineno', 0) + endline = getattr(self.slice[n], 'endlineno', startline) + return startline, endline + + def lexpos(self, n): + return getattr(self.slice[n], 'lexpos', 0) + + def lexspan(self, n): + startpos = getattr(self.slice[n], 'lexpos', 0) + endpos = getattr(self.slice[n], 'endlexpos', startpos) + return startpos, endpos + + def error(self): + raise SyntaxError + +# ----------------------------------------------------------------------------- +# == LRParser == +# +# The LR Parsing engine. +# ----------------------------------------------------------------------------- + +class LRParser: + def __init__(self, lrtab, errorf): + self.productions = lrtab.lr_productions + self.action = lrtab.lr_action + self.goto = lrtab.lr_goto + self.errorfunc = errorf + self.set_defaulted_states() + self.errorok = True + + def errok(self): + self.errorok = True + + def restart(self): + del self.statestack[:] + del self.symstack[:] + sym = YaccSymbol() + sym.type = '$end' + self.symstack.append(sym) + self.statestack.append(0) + + # Defaulted state support. + # This method identifies parser states where there is only one possible reduction action. + # For such states, the parser can make a choose to make a rule reduction without consuming + # the next look-ahead token. This delayed invocation of the tokenizer can be useful in + # certain kinds of advanced parsing situations where the lexer and parser interact with + # each other or change states (i.e., manipulation of scope, lexer states, etc.). + # + # See: https://www.gnu.org/software/bison/manual/html_node/Default-Reductions.html#Default-Reductions + def set_defaulted_states(self): + self.defaulted_states = {} + for state, actions in self.action.items(): + rules = list(actions.values()) + if len(rules) == 1 and rules[0] < 0: + self.defaulted_states[state] = rules[0] + + def disable_defaulted_states(self): + self.defaulted_states = {} + + def parse(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + if debug or yaccdevel: + if isinstance(debug, int): + debug = PlyLogger(sys.stderr) + return self.parsedebug(input, lexer, debug, tracking, tokenfunc) + elif tracking: + return self.parseopt(input, lexer, debug, tracking, tokenfunc) + else: + return self.parseopt_notrack(input, lexer, debug, tracking, tokenfunc) + + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parsedebug(). + # + # This is the debugging enabled version of parse(). All changes made to the + # parsing engine should be made here. Optimized versions of this function + # are automatically created by the ply/ygen.py script. This script cuts out + # sections enclosed in markers such as this: + # + # #--! DEBUG + # statements + # #--! DEBUG + # + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parsedebug(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parsedebug-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + #--! DEBUG + debug.info('PLY: PARSE DEBUG START') + #--! DEBUG + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + #--! DEBUG + debug.debug('') + debug.debug('State : %s', state) + #--! DEBUG + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + #--! DEBUG + debug.debug('Defaulted state %s: Reduce using %d', state, -t) + #--! DEBUG + + #--! DEBUG + debug.debug('Stack : %s', + ('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) + #--! DEBUG + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + #--! DEBUG + debug.debug('Action : Shift and goto state %s', t) + #--! DEBUG + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + #--! DEBUG + if plen: + debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str, + '['+','.join([format_stack_entry(_v.value) for _v in symstack[-plen:]])+']', + goto[statestack[-1-plen]][pname]) + else: + debug.info('Action : Reduce rule [%s] with %s and goto state %d', p.str, [], + goto[statestack[-1]][pname]) + + #--! DEBUG + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + #--! TRACKING + if tracking: + t1 = targ[1] + sym.lineno = t1.lineno + sym.lexpos = t1.lexpos + t1 = targ[-1] + sym.endlineno = getattr(t1, 'endlineno', t1.lineno) + sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos) + #--! TRACKING + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + #--! DEBUG + debug.info('Result : %s', format_result(pslice[0])) + #--! DEBUG + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + #--! TRACKING + if tracking: + sym.lineno = lexer.lineno + sym.lexpos = lexer.lexpos + #--! TRACKING + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + #--! DEBUG + debug.info('Result : %s', format_result(pslice[0])) + #--! DEBUG + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + #--! DEBUG + debug.info('Done : Returning %s', format_result(result)) + debug.info('PLY: PARSE DEBUG END') + #--! DEBUG + return result + + if t is None: + + #--! DEBUG + debug.error('Error : %s', + ('%s . %s' % (' '.join([xx.type for xx in symstack][1:]), str(lookahead))).lstrip()) + #--! DEBUG + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + #--! TRACKING + if tracking: + sym.endlineno = getattr(lookahead, 'lineno', sym.lineno) + sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos) + #--! TRACKING + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + #--! TRACKING + if tracking: + lookahead.lineno = sym.lineno + lookahead.lexpos = sym.lexpos + #--! TRACKING + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parsedebug-end + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parseopt(). + # + # Optimized version of parse() method. DO NOT EDIT THIS CODE DIRECTLY! + # This code is automatically generated by the ply/ygen.py script. Make + # changes to the parsedebug() method instead. + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parseopt(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parseopt-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + #--! TRACKING + if tracking: + t1 = targ[1] + sym.lineno = t1.lineno + sym.lexpos = t1.lexpos + t1 = targ[-1] + sym.endlineno = getattr(t1, 'endlineno', t1.lineno) + sym.endlexpos = getattr(t1, 'endlexpos', t1.lexpos) + #--! TRACKING + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + #--! TRACKING + if tracking: + sym.lineno = lexer.lineno + sym.lexpos = lexer.lexpos + #--! TRACKING + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + return result + + if t is None: + + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + #--! TRACKING + if tracking: + sym.endlineno = getattr(lookahead, 'lineno', sym.lineno) + sym.endlexpos = getattr(lookahead, 'lexpos', sym.lexpos) + #--! TRACKING + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + #--! TRACKING + if tracking: + lookahead.lineno = sym.lineno + lookahead.lexpos = sym.lexpos + #--! TRACKING + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parseopt-end + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # parseopt_notrack(). + # + # Optimized version of parseopt() with line number tracking removed. + # DO NOT EDIT THIS CODE DIRECTLY. This code is automatically generated + # by the ply/ygen.py script. Make changes to the parsedebug() method instead. + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + def parseopt_notrack(self, input=None, lexer=None, debug=False, tracking=False, tokenfunc=None): + #--! parseopt-notrack-start + lookahead = None # Current lookahead symbol + lookaheadstack = [] # Stack of lookahead symbols + actions = self.action # Local reference to action table (to avoid lookup on self.) + goto = self.goto # Local reference to goto table (to avoid lookup on self.) + prod = self.productions # Local reference to production list (to avoid lookup on self.) + defaulted_states = self.defaulted_states # Local reference to defaulted states + pslice = YaccProduction(None) # Production object passed to grammar rules + errorcount = 0 # Used during error recovery + + + # If no lexer was given, we will try to use the lex module + if not lexer: + from . import lex + lexer = lex.lexer + + # Set up the lexer and parser objects on pslice + pslice.lexer = lexer + pslice.parser = self + + # If input was supplied, pass to lexer + if input is not None: + lexer.input(input) + + if tokenfunc is None: + # Tokenize function + get_token = lexer.token + else: + get_token = tokenfunc + + # Set the parser() token method (sometimes used in error recovery) + self.token = get_token + + # Set up the state and symbol stacks + + statestack = [] # Stack of parsing states + self.statestack = statestack + symstack = [] # Stack of grammar symbols + self.symstack = symstack + + pslice.stack = symstack # Put in the production + errtoken = None # Err token + + # The start state is assumed to be (0,$end) + + statestack.append(0) + sym = YaccSymbol() + sym.type = '$end' + symstack.append(sym) + state = 0 + while True: + # Get the next symbol on the input. If a lookahead symbol + # is already set, we just use that. Otherwise, we'll pull + # the next token off of the lookaheadstack or from the lexer + + + if state not in defaulted_states: + if not lookahead: + if not lookaheadstack: + lookahead = get_token() # Get the next token + else: + lookahead = lookaheadstack.pop() + if not lookahead: + lookahead = YaccSymbol() + lookahead.type = '$end' + + # Check the action table + ltype = lookahead.type + t = actions[state].get(ltype) + else: + t = defaulted_states[state] + + + if t is not None: + if t > 0: + # shift a symbol on the stack + statestack.append(t) + state = t + + + symstack.append(lookahead) + lookahead = None + + # Decrease error count on successful shift + if errorcount: + errorcount -= 1 + continue + + if t < 0: + # reduce a symbol on the stack, emit a production + p = prod[-t] + pname = p.name + plen = p.len + + # Get production function + sym = YaccSymbol() + sym.type = pname # Production name + sym.value = None + + + if plen: + targ = symstack[-plen-1:] + targ[0] = sym + + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # below as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + del symstack[-plen:] + self.state = state + p.callable(pslice) + del statestack[-plen:] + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + symstack.extend(targ[1:-1]) # Put the production slice back on the stack + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + else: + + + targ = [sym] + + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + # The code enclosed in this section is duplicated + # above as a performance optimization. Make sure + # changes get made in both locations. + + pslice.slice = targ + + try: + # Call the grammar rule with our special slice object + self.state = state + p.callable(pslice) + symstack.append(sym) + state = goto[statestack[-1]][pname] + statestack.append(state) + except SyntaxError: + # If an error was set. Enter error recovery state + lookaheadstack.append(lookahead) # Save the current lookahead token + statestack.pop() # Pop back one state (before the reduce) + state = statestack[-1] + sym.type = 'error' + sym.value = 'error' + lookahead = sym + errorcount = error_count + self.errorok = False + + continue + # !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + + if t == 0: + n = symstack[-1] + result = getattr(n, 'value', None) + return result + + if t is None: + + + # We have some kind of parsing error here. To handle + # this, we are going to push the current token onto + # the tokenstack and replace it with an 'error' token. + # If there are any synchronization rules, they may + # catch it. + # + # In addition to pushing the error token, we call call + # the user defined p_error() function if this is the + # first syntax error. This function is only called if + # errorcount == 0. + if errorcount == 0 or self.errorok: + errorcount = error_count + self.errorok = False + errtoken = lookahead + if errtoken.type == '$end': + errtoken = None # End of file! + if self.errorfunc: + if errtoken and not hasattr(errtoken, 'lexer'): + errtoken.lexer = lexer + self.state = state + tok = call_errorfunc(self.errorfunc, errtoken, self) + if self.errorok: + # User must have done some kind of panic + # mode recovery on their own. The + # returned token is the next lookahead + lookahead = tok + errtoken = None + continue + else: + if errtoken: + if hasattr(errtoken, 'lineno'): + lineno = lookahead.lineno + else: + lineno = 0 + if lineno: + sys.stderr.write('yacc: Syntax error at line %d, token=%s\n' % (lineno, errtoken.type)) + else: + sys.stderr.write('yacc: Syntax error, token=%s' % errtoken.type) + else: + sys.stderr.write('yacc: Parse error in input. EOF\n') + return + + else: + errorcount = error_count + + # case 1: the statestack only has 1 entry on it. If we're in this state, the + # entire parse has been rolled back and we're completely hosed. The token is + # discarded and we just keep going. + + if len(statestack) <= 1 and lookahead.type != '$end': + lookahead = None + errtoken = None + state = 0 + # Nuke the pushback stack + del lookaheadstack[:] + continue + + # case 2: the statestack has a couple of entries on it, but we're + # at the end of the file. nuke the top entry and generate an error token + + # Start nuking entries on the stack + if lookahead.type == '$end': + # Whoa. We're really hosed here. Bail out + return + + if lookahead.type != 'error': + sym = symstack[-1] + if sym.type == 'error': + # Hmmm. Error is on top of stack, we'll just nuke input + # symbol and continue + lookahead = None + continue + + # Create the error symbol for the first time and make it the new lookahead symbol + t = YaccSymbol() + t.type = 'error' + + if hasattr(lookahead, 'lineno'): + t.lineno = t.endlineno = lookahead.lineno + if hasattr(lookahead, 'lexpos'): + t.lexpos = t.endlexpos = lookahead.lexpos + t.value = lookahead + lookaheadstack.append(lookahead) + lookahead = t + else: + sym = symstack.pop() + statestack.pop() + state = statestack[-1] + + continue + + # Call an error function here + raise RuntimeError('yacc: internal parser error!!!\n') + + #--! parseopt-notrack-end + +# ----------------------------------------------------------------------------- +# === Grammar Representation === +# +# The following functions, classes, and variables are used to represent and +# manipulate the rules that make up a grammar. +# ----------------------------------------------------------------------------- + +# regex matching identifiers +_is_identifier = re.compile(r'^[a-zA-Z0-9_-]+$') + +# ----------------------------------------------------------------------------- +# class Production: +# +# This class stores the raw information about a single production or grammar rule. +# A grammar rule refers to a specification such as this: +# +# expr : expr PLUS term +# +# Here are the basic attributes defined on all productions +# +# name - Name of the production. For example 'expr' +# prod - A list of symbols on the right side ['expr','PLUS','term'] +# prec - Production precedence level +# number - Production number. +# func - Function that executes on reduce +# file - File where production function is defined +# lineno - Line number where production function is defined +# +# The following attributes are defined or optional. +# +# len - Length of the production (number of symbols on right hand side) +# usyms - Set of unique symbols found in the production +# ----------------------------------------------------------------------------- + +class Production(object): + reduced = 0 + def __init__(self, number, name, prod, precedence=('right', 0), func=None, file='', line=0): + self.name = name + self.prod = tuple(prod) + self.number = number + self.func = func + self.callable = None + self.file = file + self.line = line + self.prec = precedence + + # Internal settings used during table construction + + self.len = len(self.prod) # Length of the production + + # Create a list of unique production symbols used in the production + self.usyms = [] + for s in self.prod: + if s not in self.usyms: + self.usyms.append(s) + + # List of all LR items for the production + self.lr_items = [] + self.lr_next = None + + # Create a string representation + if self.prod: + self.str = '%s -> %s' % (self.name, ' '.join(self.prod)) + else: + self.str = '%s -> ' % self.name + + def __str__(self): + return self.str + + def __repr__(self): + return 'Production(' + str(self) + ')' + + def __len__(self): + return len(self.prod) + + def __nonzero__(self): + return 1 + + def __getitem__(self, index): + return self.prod[index] + + # Return the nth lr_item from the production (or None if at the end) + def lr_item(self, n): + if n > len(self.prod): + return None + p = LRItem(self, n) + # Precompute the list of productions immediately following. + try: + p.lr_after = Prodnames[p.prod[n+1]] + except (IndexError, KeyError): + p.lr_after = [] + try: + p.lr_before = p.prod[n-1] + except IndexError: + p.lr_before = None + return p + + # Bind the production function name to a callable + def bind(self, pdict): + if self.func: + self.callable = pdict[self.func] + +# This class serves as a minimal standin for Production objects when +# reading table data from files. It only contains information +# actually used by the LR parsing engine, plus some additional +# debugging information. +class MiniProduction(object): + def __init__(self, str, name, len, func, file, line): + self.name = name + self.len = len + self.func = func + self.callable = None + self.file = file + self.line = line + self.str = str + + def __str__(self): + return self.str + + def __repr__(self): + return 'MiniProduction(%s)' % self.str + + # Bind the production function name to a callable + def bind(self, pdict): + if self.func: + self.callable = pdict[self.func] + + +# ----------------------------------------------------------------------------- +# class LRItem +# +# This class represents a specific stage of parsing a production rule. For +# example: +# +# expr : expr . PLUS term +# +# In the above, the "." represents the current location of the parse. Here +# basic attributes: +# +# name - Name of the production. For example 'expr' +# prod - A list of symbols on the right side ['expr','.', 'PLUS','term'] +# number - Production number. +# +# lr_next Next LR item. Example, if we are ' expr -> expr . PLUS term' +# then lr_next refers to 'expr -> expr PLUS . term' +# lr_index - LR item index (location of the ".") in the prod list. +# lookaheads - LALR lookahead symbols for this item +# len - Length of the production (number of symbols on right hand side) +# lr_after - List of all productions that immediately follow +# lr_before - Grammar symbol immediately before +# ----------------------------------------------------------------------------- + +class LRItem(object): + def __init__(self, p, n): + self.name = p.name + self.prod = list(p.prod) + self.number = p.number + self.lr_index = n + self.lookaheads = {} + self.prod.insert(n, '.') + self.prod = tuple(self.prod) + self.len = len(self.prod) + self.usyms = p.usyms + + def __str__(self): + if self.prod: + s = '%s -> %s' % (self.name, ' '.join(self.prod)) + else: + s = '%s -> ' % self.name + return s + + def __repr__(self): + return 'LRItem(' + str(self) + ')' + +# ----------------------------------------------------------------------------- +# rightmost_terminal() +# +# Return the rightmost terminal from a list of symbols. Used in add_production() +# ----------------------------------------------------------------------------- +def rightmost_terminal(symbols, terminals): + i = len(symbols) - 1 + while i >= 0: + if symbols[i] in terminals: + return symbols[i] + i -= 1 + return None + +# ----------------------------------------------------------------------------- +# === GRAMMAR CLASS === +# +# The following class represents the contents of the specified grammar along +# with various computed properties such as first sets, follow sets, LR items, etc. +# This data is used for critical parts of the table generation process later. +# ----------------------------------------------------------------------------- + +class GrammarError(YaccError): + pass + +class Grammar(object): + def __init__(self, terminals): + self.Productions = [None] # A list of all of the productions. The first + # entry is always reserved for the purpose of + # building an augmented grammar + + self.Prodnames = {} # A dictionary mapping the names of nonterminals to a list of all + # productions of that nonterminal. + + self.Prodmap = {} # A dictionary that is only used to detect duplicate + # productions. + + self.Terminals = {} # A dictionary mapping the names of terminal symbols to a + # list of the rules where they are used. + + for term in terminals: + self.Terminals[term] = [] + + self.Terminals['error'] = [] + + self.Nonterminals = {} # A dictionary mapping names of nonterminals to a list + # of rule numbers where they are used. + + self.First = {} # A dictionary of precomputed FIRST(x) symbols + + self.Follow = {} # A dictionary of precomputed FOLLOW(x) symbols + + self.Precedence = {} # Precedence rules for each terminal. Contains tuples of the + # form ('right',level) or ('nonassoc', level) or ('left',level) + + self.UsedPrecedence = set() # Precedence rules that were actually used by the grammer. + # This is only used to provide error checking and to generate + # a warning about unused precedence rules. + + self.Start = None # Starting symbol for the grammar + + + def __len__(self): + return len(self.Productions) + + def __getitem__(self, index): + return self.Productions[index] + + # ----------------------------------------------------------------------------- + # set_precedence() + # + # Sets the precedence for a given terminal. assoc is the associativity such as + # 'left','right', or 'nonassoc'. level is a numeric level. + # + # ----------------------------------------------------------------------------- + + def set_precedence(self, term, assoc, level): + assert self.Productions == [None], 'Must call set_precedence() before add_production()' + if term in self.Precedence: + raise GrammarError('Precedence already specified for terminal %r' % term) + if assoc not in ['left', 'right', 'nonassoc']: + raise GrammarError("Associativity must be one of 'left','right', or 'nonassoc'") + self.Precedence[term] = (assoc, level) + + # ----------------------------------------------------------------------------- + # add_production() + # + # Given an action function, this function assembles a production rule and + # computes its precedence level. + # + # The production rule is supplied as a list of symbols. For example, + # a rule such as 'expr : expr PLUS term' has a production name of 'expr' and + # symbols ['expr','PLUS','term']. + # + # Precedence is determined by the precedence of the right-most non-terminal + # or the precedence of a terminal specified by %prec. + # + # A variety of error checks are performed to make sure production symbols + # are valid and that %prec is used correctly. + # ----------------------------------------------------------------------------- + + def add_production(self, prodname, syms, func=None, file='', line=0): + + if prodname in self.Terminals: + raise GrammarError('%s:%d: Illegal rule name %r. Already defined as a token' % (file, line, prodname)) + if prodname == 'error': + raise GrammarError('%s:%d: Illegal rule name %r. error is a reserved word' % (file, line, prodname)) + if not _is_identifier.match(prodname): + raise GrammarError('%s:%d: Illegal rule name %r' % (file, line, prodname)) + + # Look for literal tokens + for n, s in enumerate(syms): + if s[0] in "'\"": + try: + c = eval(s) + if (len(c) > 1): + raise GrammarError('%s:%d: Literal token %s in rule %r may only be a single character' % + (file, line, s, prodname)) + if c not in self.Terminals: + self.Terminals[c] = [] + syms[n] = c + continue + except SyntaxError: + pass + if not _is_identifier.match(s) and s != '%prec': + raise GrammarError('%s:%d: Illegal name %r in rule %r' % (file, line, s, prodname)) + + # Determine the precedence level + if '%prec' in syms: + if syms[-1] == '%prec': + raise GrammarError('%s:%d: Syntax error. Nothing follows %%prec' % (file, line)) + if syms[-2] != '%prec': + raise GrammarError('%s:%d: Syntax error. %%prec can only appear at the end of a grammar rule' % + (file, line)) + precname = syms[-1] + prodprec = self.Precedence.get(precname) + if not prodprec: + raise GrammarError('%s:%d: Nothing known about the precedence of %r' % (file, line, precname)) + else: + self.UsedPrecedence.add(precname) + del syms[-2:] # Drop %prec from the rule + else: + # If no %prec, precedence is determined by the rightmost terminal symbol + precname = rightmost_terminal(syms, self.Terminals) + prodprec = self.Precedence.get(precname, ('right', 0)) + + # See if the rule is already in the rulemap + map = '%s -> %s' % (prodname, syms) + if map in self.Prodmap: + m = self.Prodmap[map] + raise GrammarError('%s:%d: Duplicate rule %s. ' % (file, line, m) + + 'Previous definition at %s:%d' % (m.file, m.line)) + + # From this point on, everything is valid. Create a new Production instance + pnumber = len(self.Productions) + if prodname not in self.Nonterminals: + self.Nonterminals[prodname] = [] + + # Add the production number to Terminals and Nonterminals + for t in syms: + if t in self.Terminals: + self.Terminals[t].append(pnumber) + else: + if t not in self.Nonterminals: + self.Nonterminals[t] = [] + self.Nonterminals[t].append(pnumber) + + # Create a production and add it to the list of productions + p = Production(pnumber, prodname, syms, prodprec, func, file, line) + self.Productions.append(p) + self.Prodmap[map] = p + + # Add to the global productions list + try: + self.Prodnames[prodname].append(p) + except KeyError: + self.Prodnames[prodname] = [p] + + # ----------------------------------------------------------------------------- + # set_start() + # + # Sets the starting symbol and creates the augmented grammar. Production + # rule 0 is S' -> start where start is the start symbol. + # ----------------------------------------------------------------------------- + + def set_start(self, start=None): + if not start: + start = self.Productions[1].name + if start not in self.Nonterminals: + raise GrammarError('start symbol %s undefined' % start) + self.Productions[0] = Production(0, "S'", [start]) + self.Nonterminals[start].append(0) + self.Start = start + + # ----------------------------------------------------------------------------- + # find_unreachable() + # + # Find all of the nonterminal symbols that can't be reached from the starting + # symbol. Returns a list of nonterminals that can't be reached. + # ----------------------------------------------------------------------------- + + def find_unreachable(self): + + # Mark all symbols that are reachable from a symbol s + def mark_reachable_from(s): + if s in reachable: + return + reachable.add(s) + for p in self.Prodnames.get(s, []): + for r in p.prod: + mark_reachable_from(r) + + reachable = set() + mark_reachable_from(self.Productions[0].prod[0]) + return [s for s in self.Nonterminals if s not in reachable] + + # ----------------------------------------------------------------------------- + # infinite_cycles() + # + # This function looks at the various parsing rules and tries to detect + # infinite recursion cycles (grammar rules where there is no possible way + # to derive a string of only terminals). + # ----------------------------------------------------------------------------- + + def infinite_cycles(self): + terminates = {} + + # Terminals: + for t in self.Terminals: + terminates[t] = True + + terminates['$end'] = True + + # Nonterminals: + + # Initialize to false: + for n in self.Nonterminals: + terminates[n] = False + + # Then propagate termination until no change: + while True: + some_change = False + for (n, pl) in self.Prodnames.items(): + # Nonterminal n terminates iff any of its productions terminates. + for p in pl: + # Production p terminates iff all of its rhs symbols terminate. + for s in p.prod: + if not terminates[s]: + # The symbol s does not terminate, + # so production p does not terminate. + p_terminates = False + break + else: + # didn't break from the loop, + # so every symbol s terminates + # so production p terminates. + p_terminates = True + + if p_terminates: + # symbol n terminates! + if not terminates[n]: + terminates[n] = True + some_change = True + # Don't need to consider any more productions for this n. + break + + if not some_change: + break + + infinite = [] + for (s, term) in terminates.items(): + if not term: + if s not in self.Prodnames and s not in self.Terminals and s != 'error': + # s is used-but-not-defined, and we've already warned of that, + # so it would be overkill to say that it's also non-terminating. + pass + else: + infinite.append(s) + + return infinite + + # ----------------------------------------------------------------------------- + # undefined_symbols() + # + # Find all symbols that were used the grammar, but not defined as tokens or + # grammar rules. Returns a list of tuples (sym, prod) where sym in the symbol + # and prod is the production where the symbol was used. + # ----------------------------------------------------------------------------- + def undefined_symbols(self): + result = [] + for p in self.Productions: + if not p: + continue + + for s in p.prod: + if s not in self.Prodnames and s not in self.Terminals and s != 'error': + result.append((s, p)) + return result + + # ----------------------------------------------------------------------------- + # unused_terminals() + # + # Find all terminals that were defined, but not used by the grammar. Returns + # a list of all symbols. + # ----------------------------------------------------------------------------- + def unused_terminals(self): + unused_tok = [] + for s, v in self.Terminals.items(): + if s != 'error' and not v: + unused_tok.append(s) + + return unused_tok + + # ------------------------------------------------------------------------------ + # unused_rules() + # + # Find all grammar rules that were defined, but not used (maybe not reachable) + # Returns a list of productions. + # ------------------------------------------------------------------------------ + + def unused_rules(self): + unused_prod = [] + for s, v in self.Nonterminals.items(): + if not v: + p = self.Prodnames[s][0] + unused_prod.append(p) + return unused_prod + + # ----------------------------------------------------------------------------- + # unused_precedence() + # + # Returns a list of tuples (term,precedence) corresponding to precedence + # rules that were never used by the grammar. term is the name of the terminal + # on which precedence was applied and precedence is a string such as 'left' or + # 'right' corresponding to the type of precedence. + # ----------------------------------------------------------------------------- + + def unused_precedence(self): + unused = [] + for termname in self.Precedence: + if not (termname in self.Terminals or termname in self.UsedPrecedence): + unused.append((termname, self.Precedence[termname][0])) + + return unused + + # ------------------------------------------------------------------------- + # _first() + # + # Compute the value of FIRST1(beta) where beta is a tuple of symbols. + # + # During execution of compute_first1, the result may be incomplete. + # Afterward (e.g., when called from compute_follow()), it will be complete. + # ------------------------------------------------------------------------- + def _first(self, beta): + + # We are computing First(x1,x2,x3,...,xn) + result = [] + for x in beta: + x_produces_empty = False + + # Add all the non- symbols of First[x] to the result. + for f in self.First[x]: + if f == '': + x_produces_empty = True + else: + if f not in result: + result.append(f) + + if x_produces_empty: + # We have to consider the next x in beta, + # i.e. stay in the loop. + pass + else: + # We don't have to consider any further symbols in beta. + break + else: + # There was no 'break' from the loop, + # so x_produces_empty was true for all x in beta, + # so beta produces empty as well. + result.append('') + + return result + + # ------------------------------------------------------------------------- + # compute_first() + # + # Compute the value of FIRST1(X) for all symbols + # ------------------------------------------------------------------------- + def compute_first(self): + if self.First: + return self.First + + # Terminals: + for t in self.Terminals: + self.First[t] = [t] + + self.First['$end'] = ['$end'] + + # Nonterminals: + + # Initialize to the empty set: + for n in self.Nonterminals: + self.First[n] = [] + + # Then propagate symbols until no change: + while True: + some_change = False + for n in self.Nonterminals: + for p in self.Prodnames[n]: + for f in self._first(p.prod): + if f not in self.First[n]: + self.First[n].append(f) + some_change = True + if not some_change: + break + + return self.First + + # --------------------------------------------------------------------- + # compute_follow() + # + # Computes all of the follow sets for every non-terminal symbol. The + # follow set is the set of all symbols that might follow a given + # non-terminal. See the Dragon book, 2nd Ed. p. 189. + # --------------------------------------------------------------------- + def compute_follow(self, start=None): + # If already computed, return the result + if self.Follow: + return self.Follow + + # If first sets not computed yet, do that first. + if not self.First: + self.compute_first() + + # Add '$end' to the follow list of the start symbol + for k in self.Nonterminals: + self.Follow[k] = [] + + if not start: + start = self.Productions[1].name + + self.Follow[start] = ['$end'] + + while True: + didadd = False + for p in self.Productions[1:]: + # Here is the production set + for i, B in enumerate(p.prod): + if B in self.Nonterminals: + # Okay. We got a non-terminal in a production + fst = self._first(p.prod[i+1:]) + hasempty = False + for f in fst: + if f != '' and f not in self.Follow[B]: + self.Follow[B].append(f) + didadd = True + if f == '': + hasempty = True + if hasempty or i == (len(p.prod)-1): + # Add elements of follow(a) to follow(b) + for f in self.Follow[p.name]: + if f not in self.Follow[B]: + self.Follow[B].append(f) + didadd = True + if not didadd: + break + return self.Follow + + + # ----------------------------------------------------------------------------- + # build_lritems() + # + # This function walks the list of productions and builds a complete set of the + # LR items. The LR items are stored in two ways: First, they are uniquely + # numbered and placed in the list _lritems. Second, a linked list of LR items + # is built for each production. For example: + # + # E -> E PLUS E + # + # Creates the list + # + # [E -> . E PLUS E, E -> E . PLUS E, E -> E PLUS . E, E -> E PLUS E . ] + # ----------------------------------------------------------------------------- + + def build_lritems(self): + for p in self.Productions: + lastlri = p + i = 0 + lr_items = [] + while True: + if i > len(p): + lri = None + else: + lri = LRItem(p, i) + # Precompute the list of productions immediately following + try: + lri.lr_after = self.Prodnames[lri.prod[i+1]] + except (IndexError, KeyError): + lri.lr_after = [] + try: + lri.lr_before = lri.prod[i-1] + except IndexError: + lri.lr_before = None + + lastlri.lr_next = lri + if not lri: + break + lr_items.append(lri) + lastlri = lri + i += 1 + p.lr_items = lr_items + +# ----------------------------------------------------------------------------- +# == Class LRTable == +# +# This basic class represents a basic table of LR parsing information. +# Methods for generating the tables are not defined here. They are defined +# in the derived class LRGeneratedTable. +# ----------------------------------------------------------------------------- + +class VersionError(YaccError): + pass + +class LRTable(object): + def __init__(self): + self.lr_action = None + self.lr_goto = None + self.lr_productions = None + self.lr_method = None + + def read_table(self, module): + if isinstance(module, types.ModuleType): + parsetab = module + else: + exec('import %s' % module) + parsetab = sys.modules[module] + + if parsetab._tabversion != __tabversion__: + raise VersionError('yacc table file version is out of date') + + self.lr_action = parsetab._lr_action + self.lr_goto = parsetab._lr_goto + + self.lr_productions = [] + for p in parsetab._lr_productions: + self.lr_productions.append(MiniProduction(*p)) + + self.lr_method = parsetab._lr_method + return parsetab._lr_signature + + def read_pickle(self, filename): + try: + import cPickle as pickle + except ImportError: + import pickle + + if not os.path.exists(filename): + raise ImportError + + in_f = open(filename, 'rb') + + tabversion = pickle.load(in_f) + if tabversion != __tabversion__: + raise VersionError('yacc table file version is out of date') + self.lr_method = pickle.load(in_f) + signature = pickle.load(in_f) + self.lr_action = pickle.load(in_f) + self.lr_goto = pickle.load(in_f) + productions = pickle.load(in_f) + + self.lr_productions = [] + for p in productions: + self.lr_productions.append(MiniProduction(*p)) + + in_f.close() + return signature + + # Bind all production function names to callable objects in pdict + def bind_callables(self, pdict): + for p in self.lr_productions: + p.bind(pdict) + + +# ----------------------------------------------------------------------------- +# === LR Generator === +# +# The following classes and functions are used to generate LR parsing tables on +# a grammar. +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# digraph() +# traverse() +# +# The following two functions are used to compute set valued functions +# of the form: +# +# F(x) = F'(x) U U{F(y) | x R y} +# +# This is used to compute the values of Read() sets as well as FOLLOW sets +# in LALR(1) generation. +# +# Inputs: X - An input set +# R - A relation +# FP - Set-valued function +# ------------------------------------------------------------------------------ + +def digraph(X, R, FP): + N = {} + for x in X: + N[x] = 0 + stack = [] + F = {} + for x in X: + if N[x] == 0: + traverse(x, N, stack, F, X, R, FP) + return F + +def traverse(x, N, stack, F, X, R, FP): + stack.append(x) + d = len(stack) + N[x] = d + F[x] = FP(x) # F(X) <- F'(x) + + rel = R(x) # Get y's related to x + for y in rel: + if N[y] == 0: + traverse(y, N, stack, F, X, R, FP) + N[x] = min(N[x], N[y]) + for a in F.get(y, []): + if a not in F[x]: + F[x].append(a) + if N[x] == d: + N[stack[-1]] = MAXINT + F[stack[-1]] = F[x] + element = stack.pop() + while element != x: + N[stack[-1]] = MAXINT + F[stack[-1]] = F[x] + element = stack.pop() + +class LALRError(YaccError): + pass + +# ----------------------------------------------------------------------------- +# == LRGeneratedTable == +# +# This class implements the LR table generation algorithm. There are no +# public methods except for write() +# ----------------------------------------------------------------------------- + +class LRGeneratedTable(LRTable): + def __init__(self, grammar, method='LALR', log=None): + if method not in ['SLR', 'LALR']: + raise LALRError('Unsupported method %s' % method) + + self.grammar = grammar + self.lr_method = method + + # Set up the logger + if not log: + log = NullLogger() + self.log = log + + # Internal attributes + self.lr_action = {} # Action table + self.lr_goto = {} # Goto table + self.lr_productions = grammar.Productions # Copy of grammar Production array + self.lr_goto_cache = {} # Cache of computed gotos + self.lr0_cidhash = {} # Cache of closures + + self._add_count = 0 # Internal counter used to detect cycles + + # Diagonistic information filled in by the table generator + self.sr_conflict = 0 + self.rr_conflict = 0 + self.conflicts = [] # List of conflicts + + self.sr_conflicts = [] + self.rr_conflicts = [] + + # Build the tables + self.grammar.build_lritems() + self.grammar.compute_first() + self.grammar.compute_follow() + self.lr_parse_table() + + # Compute the LR(0) closure operation on I, where I is a set of LR(0) items. + + def lr0_closure(self, I): + self._add_count += 1 + + # Add everything in I to J + J = I[:] + didadd = True + while didadd: + didadd = False + for j in J: + for x in j.lr_after: + if getattr(x, 'lr0_added', 0) == self._add_count: + continue + # Add B --> .G to J + J.append(x.lr_next) + x.lr0_added = self._add_count + didadd = True + + return J + + # Compute the LR(0) goto function goto(I,X) where I is a set + # of LR(0) items and X is a grammar symbol. This function is written + # in a way that guarantees uniqueness of the generated goto sets + # (i.e. the same goto set will never be returned as two different Python + # objects). With uniqueness, we can later do fast set comparisons using + # id(obj) instead of element-wise comparison. + + def lr0_goto(self, I, x): + # First we look for a previously cached entry + g = self.lr_goto_cache.get((id(I), x)) + if g: + return g + + # Now we generate the goto set in a way that guarantees uniqueness + # of the result + + s = self.lr_goto_cache.get(x) + if not s: + s = {} + self.lr_goto_cache[x] = s + + gs = [] + for p in I: + n = p.lr_next + if n and n.lr_before == x: + s1 = s.get(id(n)) + if not s1: + s1 = {} + s[id(n)] = s1 + gs.append(n) + s = s1 + g = s.get('$end') + if not g: + if gs: + g = self.lr0_closure(gs) + s['$end'] = g + else: + s['$end'] = gs + self.lr_goto_cache[(id(I), x)] = g + return g + + # Compute the LR(0) sets of item function + def lr0_items(self): + C = [self.lr0_closure([self.grammar.Productions[0].lr_next])] + i = 0 + for I in C: + self.lr0_cidhash[id(I)] = i + i += 1 + + # Loop over the items in C and each grammar symbols + i = 0 + while i < len(C): + I = C[i] + i += 1 + + # Collect all of the symbols that could possibly be in the goto(I,X) sets + asyms = {} + for ii in I: + for s in ii.usyms: + asyms[s] = None + + for x in asyms: + g = self.lr0_goto(I, x) + if not g or id(g) in self.lr0_cidhash: + continue + self.lr0_cidhash[id(g)] = len(C) + C.append(g) + + return C + + # ----------------------------------------------------------------------------- + # ==== LALR(1) Parsing ==== + # + # LALR(1) parsing is almost exactly the same as SLR except that instead of + # relying upon Follow() sets when performing reductions, a more selective + # lookahead set that incorporates the state of the LR(0) machine is utilized. + # Thus, we mainly just have to focus on calculating the lookahead sets. + # + # The method used here is due to DeRemer and Pennelo (1982). + # + # DeRemer, F. L., and T. J. Pennelo: "Efficient Computation of LALR(1) + # Lookahead Sets", ACM Transactions on Programming Languages and Systems, + # Vol. 4, No. 4, Oct. 1982, pp. 615-649 + # + # Further details can also be found in: + # + # J. Tremblay and P. Sorenson, "The Theory and Practice of Compiler Writing", + # McGraw-Hill Book Company, (1985). + # + # ----------------------------------------------------------------------------- + + # ----------------------------------------------------------------------------- + # compute_nullable_nonterminals() + # + # Creates a dictionary containing all of the non-terminals that might produce + # an empty production. + # ----------------------------------------------------------------------------- + + def compute_nullable_nonterminals(self): + nullable = set() + num_nullable = 0 + while True: + for p in self.grammar.Productions[1:]: + if p.len == 0: + nullable.add(p.name) + continue + for t in p.prod: + if t not in nullable: + break + else: + nullable.add(p.name) + if len(nullable) == num_nullable: + break + num_nullable = len(nullable) + return nullable + + # ----------------------------------------------------------------------------- + # find_nonterminal_trans(C) + # + # Given a set of LR(0) items, this functions finds all of the non-terminal + # transitions. These are transitions in which a dot appears immediately before + # a non-terminal. Returns a list of tuples of the form (state,N) where state + # is the state number and N is the nonterminal symbol. + # + # The input C is the set of LR(0) items. + # ----------------------------------------------------------------------------- + + def find_nonterminal_transitions(self, C): + trans = [] + for stateno, state in enumerate(C): + for p in state: + if p.lr_index < p.len - 1: + t = (stateno, p.prod[p.lr_index+1]) + if t[1] in self.grammar.Nonterminals: + if t not in trans: + trans.append(t) + return trans + + # ----------------------------------------------------------------------------- + # dr_relation() + # + # Computes the DR(p,A) relationships for non-terminal transitions. The input + # is a tuple (state,N) where state is a number and N is a nonterminal symbol. + # + # Returns a list of terminals. + # ----------------------------------------------------------------------------- + + def dr_relation(self, C, trans, nullable): + dr_set = {} + state, N = trans + terms = [] + + g = self.lr0_goto(C[state], N) + for p in g: + if p.lr_index < p.len - 1: + a = p.prod[p.lr_index+1] + if a in self.grammar.Terminals: + if a not in terms: + terms.append(a) + + # This extra bit is to handle the start state + if state == 0 and N == self.grammar.Productions[0].prod[0]: + terms.append('$end') + + return terms + + # ----------------------------------------------------------------------------- + # reads_relation() + # + # Computes the READS() relation (p,A) READS (t,C). + # ----------------------------------------------------------------------------- + + def reads_relation(self, C, trans, empty): + # Look for empty transitions + rel = [] + state, N = trans + + g = self.lr0_goto(C[state], N) + j = self.lr0_cidhash.get(id(g), -1) + for p in g: + if p.lr_index < p.len - 1: + a = p.prod[p.lr_index + 1] + if a in empty: + rel.append((j, a)) + + return rel + + # ----------------------------------------------------------------------------- + # compute_lookback_includes() + # + # Determines the lookback and includes relations + # + # LOOKBACK: + # + # This relation is determined by running the LR(0) state machine forward. + # For example, starting with a production "N : . A B C", we run it forward + # to obtain "N : A B C ." We then build a relationship between this final + # state and the starting state. These relationships are stored in a dictionary + # lookdict. + # + # INCLUDES: + # + # Computes the INCLUDE() relation (p,A) INCLUDES (p',B). + # + # This relation is used to determine non-terminal transitions that occur + # inside of other non-terminal transition states. (p,A) INCLUDES (p', B) + # if the following holds: + # + # B -> LAT, where T -> epsilon and p' -L-> p + # + # L is essentially a prefix (which may be empty), T is a suffix that must be + # able to derive an empty string. State p' must lead to state p with the string L. + # + # ----------------------------------------------------------------------------- + + def compute_lookback_includes(self, C, trans, nullable): + lookdict = {} # Dictionary of lookback relations + includedict = {} # Dictionary of include relations + + # Make a dictionary of non-terminal transitions + dtrans = {} + for t in trans: + dtrans[t] = 1 + + # Loop over all transitions and compute lookbacks and includes + for state, N in trans: + lookb = [] + includes = [] + for p in C[state]: + if p.name != N: + continue + + # Okay, we have a name match. We now follow the production all the way + # through the state machine until we get the . on the right hand side + + lr_index = p.lr_index + j = state + while lr_index < p.len - 1: + lr_index = lr_index + 1 + t = p.prod[lr_index] + + # Check to see if this symbol and state are a non-terminal transition + if (j, t) in dtrans: + # Yes. Okay, there is some chance that this is an includes relation + # the only way to know for certain is whether the rest of the + # production derives empty + + li = lr_index + 1 + while li < p.len: + if p.prod[li] in self.grammar.Terminals: + break # No forget it + if p.prod[li] not in nullable: + break + li = li + 1 + else: + # Appears to be a relation between (j,t) and (state,N) + includes.append((j, t)) + + g = self.lr0_goto(C[j], t) # Go to next set + j = self.lr0_cidhash.get(id(g), -1) # Go to next state + + # When we get here, j is the final state, now we have to locate the production + for r in C[j]: + if r.name != p.name: + continue + if r.len != p.len: + continue + i = 0 + # This look is comparing a production ". A B C" with "A B C ." + while i < r.lr_index: + if r.prod[i] != p.prod[i+1]: + break + i = i + 1 + else: + lookb.append((j, r)) + for i in includes: + if i not in includedict: + includedict[i] = [] + includedict[i].append((state, N)) + lookdict[(state, N)] = lookb + + return lookdict, includedict + + # ----------------------------------------------------------------------------- + # compute_read_sets() + # + # Given a set of LR(0) items, this function computes the read sets. + # + # Inputs: C = Set of LR(0) items + # ntrans = Set of nonterminal transitions + # nullable = Set of empty transitions + # + # Returns a set containing the read sets + # ----------------------------------------------------------------------------- + + def compute_read_sets(self, C, ntrans, nullable): + FP = lambda x: self.dr_relation(C, x, nullable) + R = lambda x: self.reads_relation(C, x, nullable) + F = digraph(ntrans, R, FP) + return F + + # ----------------------------------------------------------------------------- + # compute_follow_sets() + # + # Given a set of LR(0) items, a set of non-terminal transitions, a readset, + # and an include set, this function computes the follow sets + # + # Follow(p,A) = Read(p,A) U U {Follow(p',B) | (p,A) INCLUDES (p',B)} + # + # Inputs: + # ntrans = Set of nonterminal transitions + # readsets = Readset (previously computed) + # inclsets = Include sets (previously computed) + # + # Returns a set containing the follow sets + # ----------------------------------------------------------------------------- + + def compute_follow_sets(self, ntrans, readsets, inclsets): + FP = lambda x: readsets[x] + R = lambda x: inclsets.get(x, []) + F = digraph(ntrans, R, FP) + return F + + # ----------------------------------------------------------------------------- + # add_lookaheads() + # + # Attaches the lookahead symbols to grammar rules. + # + # Inputs: lookbacks - Set of lookback relations + # followset - Computed follow set + # + # This function directly attaches the lookaheads to productions contained + # in the lookbacks set + # ----------------------------------------------------------------------------- + + def add_lookaheads(self, lookbacks, followset): + for trans, lb in lookbacks.items(): + # Loop over productions in lookback + for state, p in lb: + if state not in p.lookaheads: + p.lookaheads[state] = [] + f = followset.get(trans, []) + for a in f: + if a not in p.lookaheads[state]: + p.lookaheads[state].append(a) + + # ----------------------------------------------------------------------------- + # add_lalr_lookaheads() + # + # This function does all of the work of adding lookahead information for use + # with LALR parsing + # ----------------------------------------------------------------------------- + + def add_lalr_lookaheads(self, C): + # Determine all of the nullable nonterminals + nullable = self.compute_nullable_nonterminals() + + # Find all non-terminal transitions + trans = self.find_nonterminal_transitions(C) + + # Compute read sets + readsets = self.compute_read_sets(C, trans, nullable) + + # Compute lookback/includes relations + lookd, included = self.compute_lookback_includes(C, trans, nullable) + + # Compute LALR FOLLOW sets + followsets = self.compute_follow_sets(trans, readsets, included) + + # Add all of the lookaheads + self.add_lookaheads(lookd, followsets) + + # ----------------------------------------------------------------------------- + # lr_parse_table() + # + # This function constructs the parse tables for SLR or LALR + # ----------------------------------------------------------------------------- + def lr_parse_table(self): + Productions = self.grammar.Productions + Precedence = self.grammar.Precedence + goto = self.lr_goto # Goto array + action = self.lr_action # Action array + log = self.log # Logger for output + + actionp = {} # Action production array (temporary) + + log.info('Parsing method: %s', self.lr_method) + + # Step 1: Construct C = { I0, I1, ... IN}, collection of LR(0) items + # This determines the number of states + + C = self.lr0_items() + + if self.lr_method == 'LALR': + self.add_lalr_lookaheads(C) + + # Build the parser table, state by state + st = 0 + for I in C: + # Loop over each production in I + actlist = [] # List of actions + st_action = {} + st_actionp = {} + st_goto = {} + log.info('') + log.info('state %d', st) + log.info('') + for p in I: + log.info(' (%d) %s', p.number, p) + log.info('') + + for p in I: + if p.len == p.lr_index + 1: + if p.name == "S'": + # Start symbol. Accept! + st_action['$end'] = 0 + st_actionp['$end'] = p + else: + # We are at the end of a production. Reduce! + if self.lr_method == 'LALR': + laheads = p.lookaheads[st] + else: + laheads = self.grammar.Follow[p.name] + for a in laheads: + actlist.append((a, p, 'reduce using rule %d (%s)' % (p.number, p))) + r = st_action.get(a) + if r is not None: + # Whoa. Have a shift/reduce or reduce/reduce conflict + if r > 0: + # Need to decide on shift or reduce here + # By default we favor shifting. Need to add + # some precedence rules here. + + # Shift precedence comes from the token + sprec, slevel = Precedence.get(a, ('right', 0)) + + # Reduce precedence comes from rule being reduced (p) + rprec, rlevel = Productions[p.number].prec + + if (slevel < rlevel) or ((slevel == rlevel) and (rprec == 'left')): + # We really need to reduce here. + st_action[a] = -p.number + st_actionp[a] = p + if not slevel and not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as reduce', a) + self.sr_conflicts.append((st, a, 'reduce')) + Productions[p.number].reduced += 1 + elif (slevel == rlevel) and (rprec == 'nonassoc'): + st_action[a] = None + else: + # Hmmm. Guess we'll keep the shift + if not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as shift', a) + self.sr_conflicts.append((st, a, 'shift')) + elif r < 0: + # Reduce/reduce conflict. In this case, we favor the rule + # that was defined first in the grammar file + oldp = Productions[-r] + pp = Productions[p.number] + if oldp.line > pp.line: + st_action[a] = -p.number + st_actionp[a] = p + chosenp, rejectp = pp, oldp + Productions[p.number].reduced += 1 + Productions[oldp.number].reduced -= 1 + else: + chosenp, rejectp = oldp, pp + self.rr_conflicts.append((st, chosenp, rejectp)) + log.info(' ! reduce/reduce conflict for %s resolved using rule %d (%s)', + a, st_actionp[a].number, st_actionp[a]) + else: + raise LALRError('Unknown conflict in state %d' % st) + else: + st_action[a] = -p.number + st_actionp[a] = p + Productions[p.number].reduced += 1 + else: + i = p.lr_index + a = p.prod[i+1] # Get symbol right after the "." + if a in self.grammar.Terminals: + g = self.lr0_goto(I, a) + j = self.lr0_cidhash.get(id(g), -1) + if j >= 0: + # We are in a shift state + actlist.append((a, p, 'shift and go to state %d' % j)) + r = st_action.get(a) + if r is not None: + # Whoa have a shift/reduce or shift/shift conflict + if r > 0: + if r != j: + raise LALRError('Shift/shift conflict in state %d' % st) + elif r < 0: + # Do a precedence check. + # - if precedence of reduce rule is higher, we reduce. + # - if precedence of reduce is same and left assoc, we reduce. + # - otherwise we shift + + # Shift precedence comes from the token + sprec, slevel = Precedence.get(a, ('right', 0)) + + # Reduce precedence comes from the rule that could have been reduced + rprec, rlevel = Productions[st_actionp[a].number].prec + + if (slevel > rlevel) or ((slevel == rlevel) and (rprec == 'right')): + # We decide to shift here... highest precedence to shift + Productions[st_actionp[a].number].reduced -= 1 + st_action[a] = j + st_actionp[a] = p + if not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as shift', a) + self.sr_conflicts.append((st, a, 'shift')) + elif (slevel == rlevel) and (rprec == 'nonassoc'): + st_action[a] = None + else: + # Hmmm. Guess we'll keep the reduce + if not slevel and not rlevel: + log.info(' ! shift/reduce conflict for %s resolved as reduce', a) + self.sr_conflicts.append((st, a, 'reduce')) + + else: + raise LALRError('Unknown conflict in state %d' % st) + else: + st_action[a] = j + st_actionp[a] = p + + # Print the actions associated with each terminal + _actprint = {} + for a, p, m in actlist: + if a in st_action: + if p is st_actionp[a]: + log.info(' %-15s %s', a, m) + _actprint[(a, m)] = 1 + log.info('') + # Print the actions that were not used. (debugging) + not_used = 0 + for a, p, m in actlist: + if a in st_action: + if p is not st_actionp[a]: + if not (a, m) in _actprint: + log.debug(' ! %-15s [ %s ]', a, m) + not_used = 1 + _actprint[(a, m)] = 1 + if not_used: + log.debug('') + + # Construct the goto table for this state + + nkeys = {} + for ii in I: + for s in ii.usyms: + if s in self.grammar.Nonterminals: + nkeys[s] = None + for n in nkeys: + g = self.lr0_goto(I, n) + j = self.lr0_cidhash.get(id(g), -1) + if j >= 0: + st_goto[n] = j + log.info(' %-30s shift and go to state %d', n, j) + + action[st] = st_action + actionp[st] = st_actionp + goto[st] = st_goto + st += 1 + + # ----------------------------------------------------------------------------- + # write() + # + # This function writes the LR parsing tables to a file + # ----------------------------------------------------------------------------- + + def write_table(self, tabmodule, outputdir='', signature=''): + if isinstance(tabmodule, types.ModuleType): + raise IOError("Won't overwrite existing tabmodule") + + basemodulename = tabmodule.split('.')[-1] + filename = os.path.join(outputdir, basemodulename) + '.py' + try: + f = open(filename, 'w') + + f.write(''' +# %s +# This file is automatically generated. Do not edit. +_tabversion = %r + +_lr_method = %r + +_lr_signature = %r + ''' % (os.path.basename(filename), __tabversion__, self.lr_method, signature)) + + # Change smaller to 0 to go back to original tables + smaller = 1 + + # Factor out names to try and make smaller + if smaller: + items = {} + + for s, nd in self.lr_action.items(): + for name, v in nd.items(): + i = items.get(name) + if not i: + i = ([], []) + items[name] = i + i[0].append(s) + i[1].append(v) + + f.write('\n_lr_action_items = {') + for k, v in items.items(): + f.write('%r:([' % k) + for i in v[0]: + f.write('%r,' % i) + f.write('],[') + for i in v[1]: + f.write('%r,' % i) + + f.write(']),') + f.write('}\n') + + f.write(''' +_lr_action = {} +for _k, _v in _lr_action_items.items(): + for _x,_y in zip(_v[0],_v[1]): + if not _x in _lr_action: _lr_action[_x] = {} + _lr_action[_x][_k] = _y +del _lr_action_items +''') + + else: + f.write('\n_lr_action = { ') + for k, v in self.lr_action.items(): + f.write('(%r,%r):%r,' % (k[0], k[1], v)) + f.write('}\n') + + if smaller: + # Factor out names to try and make smaller + items = {} + + for s, nd in self.lr_goto.items(): + for name, v in nd.items(): + i = items.get(name) + if not i: + i = ([], []) + items[name] = i + i[0].append(s) + i[1].append(v) + + f.write('\n_lr_goto_items = {') + for k, v in items.items(): + f.write('%r:([' % k) + for i in v[0]: + f.write('%r,' % i) + f.write('],[') + for i in v[1]: + f.write('%r,' % i) + + f.write(']),') + f.write('}\n') + + f.write(''' +_lr_goto = {} +for _k, _v in _lr_goto_items.items(): + for _x, _y in zip(_v[0], _v[1]): + if not _x in _lr_goto: _lr_goto[_x] = {} + _lr_goto[_x][_k] = _y +del _lr_goto_items +''') + else: + f.write('\n_lr_goto = { ') + for k, v in self.lr_goto.items(): + f.write('(%r,%r):%r,' % (k[0], k[1], v)) + f.write('}\n') + + # Write production table + f.write('_lr_productions = [\n') + for p in self.lr_productions: + if p.func: + f.write(' (%r,%r,%d,%r,%r,%d),\n' % (p.str, p.name, p.len, + p.func, os.path.basename(p.file), p.line)) + else: + f.write(' (%r,%r,%d,None,None,None),\n' % (str(p), p.name, p.len)) + f.write(']\n') + f.close() + + except IOError as e: + raise + + + # ----------------------------------------------------------------------------- + # pickle_table() + # + # This function pickles the LR parsing tables to a supplied file object + # ----------------------------------------------------------------------------- + + def pickle_table(self, filename, signature=''): + try: + import cPickle as pickle + except ImportError: + import pickle + with open(filename, 'wb') as outf: + pickle.dump(__tabversion__, outf, pickle_protocol) + pickle.dump(self.lr_method, outf, pickle_protocol) + pickle.dump(signature, outf, pickle_protocol) + pickle.dump(self.lr_action, outf, pickle_protocol) + pickle.dump(self.lr_goto, outf, pickle_protocol) + + outp = [] + for p in self.lr_productions: + if p.func: + outp.append((p.str, p.name, p.len, p.func, os.path.basename(p.file), p.line)) + else: + outp.append((str(p), p.name, p.len, None, None, None)) + pickle.dump(outp, outf, pickle_protocol) + +# ----------------------------------------------------------------------------- +# === INTROSPECTION === +# +# The following functions and classes are used to implement the PLY +# introspection features followed by the yacc() function itself. +# ----------------------------------------------------------------------------- + +# ----------------------------------------------------------------------------- +# get_caller_module_dict() +# +# This function returns a dictionary containing all of the symbols defined within +# a caller further down the call stack. This is used to get the environment +# associated with the yacc() call if none was provided. +# ----------------------------------------------------------------------------- + +def get_caller_module_dict(levels): + f = sys._getframe(levels) + ldict = f.f_globals.copy() + if f.f_globals != f.f_locals: + ldict.update(f.f_locals) + return ldict + +# ----------------------------------------------------------------------------- +# parse_grammar() +# +# This takes a raw grammar rule string and parses it into production data +# ----------------------------------------------------------------------------- +def parse_grammar(doc, file, line): + grammar = [] + # Split the doc string into lines + pstrings = doc.splitlines() + lastp = None + dline = line + for ps in pstrings: + dline += 1 + p = ps.split() + if not p: + continue + try: + if p[0] == '|': + # This is a continuation of a previous rule + if not lastp: + raise SyntaxError("%s:%d: Misplaced '|'" % (file, dline)) + prodname = lastp + syms = p[1:] + else: + prodname = p[0] + lastp = prodname + syms = p[2:] + assign = p[1] + if assign != ':' and assign != '::=': + raise SyntaxError("%s:%d: Syntax error. Expected ':'" % (file, dline)) + + grammar.append((file, dline, prodname, syms)) + except SyntaxError: + raise + except Exception: + raise SyntaxError('%s:%d: Syntax error in rule %r' % (file, dline, ps.strip())) + + return grammar + +# ----------------------------------------------------------------------------- +# ParserReflect() +# +# This class represents information extracted for building a parser including +# start symbol, error function, tokens, precedence list, action functions, +# etc. +# ----------------------------------------------------------------------------- +class ParserReflect(object): + def __init__(self, pdict, log=None): + self.pdict = pdict + self.start = None + self.error_func = None + self.tokens = None + self.modules = set() + self.grammar = [] + self.error = False + + if log is None: + self.log = PlyLogger(sys.stderr) + else: + self.log = log + + # Get all of the basic information + def get_all(self): + self.get_start() + self.get_error_func() + self.get_tokens() + self.get_precedence() + self.get_pfunctions() + + # Validate all of the information + def validate_all(self): + self.validate_start() + self.validate_error_func() + self.validate_tokens() + self.validate_precedence() + self.validate_pfunctions() + self.validate_modules() + return self.error + + # Compute a signature over the grammar + def signature(self): + parts = [] + try: + if self.start: + parts.append(self.start) + if self.prec: + parts.append(''.join([''.join(p) for p in self.prec])) + if self.tokens: + parts.append(' '.join(self.tokens)) + for f in self.pfuncs: + if f[3]: + parts.append(f[3]) + except (TypeError, ValueError): + pass + return ''.join(parts) + + # ----------------------------------------------------------------------------- + # validate_modules() + # + # This method checks to see if there are duplicated p_rulename() functions + # in the parser module file. Without this function, it is really easy for + # users to make mistakes by cutting and pasting code fragments (and it's a real + # bugger to try and figure out why the resulting parser doesn't work). Therefore, + # we just do a little regular expression pattern matching of def statements + # to try and detect duplicates. + # ----------------------------------------------------------------------------- + + def validate_modules(self): + # Match def p_funcname( + fre = re.compile(r'\s*def\s+(p_[a-zA-Z_0-9]*)\(') + + for module in self.modules: + try: + lines, linen = inspect.getsourcelines(module) + except IOError: + continue + + counthash = {} + for linen, line in enumerate(lines): + linen += 1 + m = fre.match(line) + if m: + name = m.group(1) + prev = counthash.get(name) + if not prev: + counthash[name] = linen + else: + filename = inspect.getsourcefile(module) + self.log.warning('%s:%d: Function %s redefined. Previously defined on line %d', + filename, linen, name, prev) + + # Get the start symbol + def get_start(self): + self.start = self.pdict.get('start') + + # Validate the start symbol + def validate_start(self): + if self.start is not None: + if not isinstance(self.start, string_types): + self.log.error("'start' must be a string") + + # Look for error handler + def get_error_func(self): + self.error_func = self.pdict.get('p_error') + + # Validate the error function + def validate_error_func(self): + if self.error_func: + if isinstance(self.error_func, types.FunctionType): + ismethod = 0 + elif isinstance(self.error_func, types.MethodType): + ismethod = 1 + else: + self.log.error("'p_error' defined, but is not a function or method") + self.error = True + return + + eline = self.error_func.__code__.co_firstlineno + efile = self.error_func.__code__.co_filename + module = inspect.getmodule(self.error_func) + self.modules.add(module) + + argcount = self.error_func.__code__.co_argcount - ismethod + if argcount != 1: + self.log.error('%s:%d: p_error() requires 1 argument', efile, eline) + self.error = True + + # Get the tokens map + def get_tokens(self): + tokens = self.pdict.get('tokens') + if not tokens: + self.log.error('No token list is defined') + self.error = True + return + + if not isinstance(tokens, (list, tuple)): + self.log.error('tokens must be a list or tuple') + self.error = True + return + + if not tokens: + self.log.error('tokens is empty') + self.error = True + return + + self.tokens = tokens + + # Validate the tokens + def validate_tokens(self): + # Validate the tokens. + if 'error' in self.tokens: + self.log.error("Illegal token name 'error'. Is a reserved word") + self.error = True + return + + terminals = set() + for n in self.tokens: + if n in terminals: + self.log.warning('Token %r multiply defined', n) + terminals.add(n) + + # Get the precedence map (if any) + def get_precedence(self): + self.prec = self.pdict.get('precedence') + + # Validate and parse the precedence map + def validate_precedence(self): + preclist = [] + if self.prec: + if not isinstance(self.prec, (list, tuple)): + self.log.error('precedence must be a list or tuple') + self.error = True + return + for level, p in enumerate(self.prec): + if not isinstance(p, (list, tuple)): + self.log.error('Bad precedence table') + self.error = True + return + + if len(p) < 2: + self.log.error('Malformed precedence entry %s. Must be (assoc, term, ..., term)', p) + self.error = True + return + assoc = p[0] + if not isinstance(assoc, string_types): + self.log.error('precedence associativity must be a string') + self.error = True + return + for term in p[1:]: + if not isinstance(term, string_types): + self.log.error('precedence items must be strings') + self.error = True + return + preclist.append((term, assoc, level+1)) + self.preclist = preclist + + # Get all p_functions from the grammar + def get_pfunctions(self): + p_functions = [] + for name, item in self.pdict.items(): + if not name.startswith('p_') or name == 'p_error': + continue + if isinstance(item, (types.FunctionType, types.MethodType)): + line = getattr(item, 'co_firstlineno', item.__code__.co_firstlineno) + module = inspect.getmodule(item) + p_functions.append((line, module, name, item.__doc__)) + + # Sort all of the actions by line number; make sure to stringify + # modules to make them sortable, since `line` may not uniquely sort all + # p functions + p_functions.sort(key=lambda p_function: ( + p_function[0], + str(p_function[1]), + p_function[2], + p_function[3])) + self.pfuncs = p_functions + + # Validate all of the p_functions + def validate_pfunctions(self): + grammar = [] + # Check for non-empty symbols + if len(self.pfuncs) == 0: + self.log.error('no rules of the form p_rulename are defined') + self.error = True + return + + for line, module, name, doc in self.pfuncs: + file = inspect.getsourcefile(module) + func = self.pdict[name] + if isinstance(func, types.MethodType): + reqargs = 2 + else: + reqargs = 1 + if func.__code__.co_argcount > reqargs: + self.log.error('%s:%d: Rule %r has too many arguments', file, line, func.__name__) + self.error = True + elif func.__code__.co_argcount < reqargs: + self.log.error('%s:%d: Rule %r requires an argument', file, line, func.__name__) + self.error = True + elif not func.__doc__: + self.log.warning('%s:%d: No documentation string specified in function %r (ignored)', + file, line, func.__name__) + else: + try: + parsed_g = parse_grammar(doc, file, line) + for g in parsed_g: + grammar.append((name, g)) + except SyntaxError as e: + self.log.error(str(e)) + self.error = True + + # Looks like a valid grammar rule + # Mark the file in which defined. + self.modules.add(module) + + # Secondary validation step that looks for p_ definitions that are not functions + # or functions that look like they might be grammar rules. + + for n, v in self.pdict.items(): + if n.startswith('p_') and isinstance(v, (types.FunctionType, types.MethodType)): + continue + if n.startswith('t_'): + continue + if n.startswith('p_') and n != 'p_error': + self.log.warning('%r not defined as a function', n) + if ((isinstance(v, types.FunctionType) and v.__code__.co_argcount == 1) or + (isinstance(v, types.MethodType) and v.__func__.__code__.co_argcount == 2)): + if v.__doc__: + try: + doc = v.__doc__.split(' ') + if doc[1] == ':': + self.log.warning('%s:%d: Possible grammar rule %r defined without p_ prefix', + v.__code__.co_filename, v.__code__.co_firstlineno, n) + except IndexError: + pass + + self.grammar = grammar + +# ----------------------------------------------------------------------------- +# yacc(module) +# +# Build a parser +# ----------------------------------------------------------------------------- + +def yacc(method='LALR', debug=yaccdebug, module=None, tabmodule=tab_module, start=None, + check_recursion=True, optimize=False, write_tables=True, debugfile=debug_file, + outputdir=None, debuglog=None, errorlog=None, picklefile=None): + + if tabmodule is None: + tabmodule = tab_module + + # Reference to the parsing method of the last built parser + global parse + + # If pickling is enabled, table files are not created + if picklefile: + write_tables = 0 + + if errorlog is None: + errorlog = PlyLogger(sys.stderr) + + # Get the module dictionary used for the parser + if module: + _items = [(k, getattr(module, k)) for k in dir(module)] + pdict = dict(_items) + # If no __file__ attribute is available, try to obtain it from the __module__ instead + if '__file__' not in pdict: + pdict['__file__'] = sys.modules[pdict['__module__']].__file__ + else: + pdict = get_caller_module_dict(2) + + if outputdir is None: + # If no output directory is set, the location of the output files + # is determined according to the following rules: + # - If tabmodule specifies a package, files go into that package directory + # - Otherwise, files go in the same directory as the specifying module + if isinstance(tabmodule, types.ModuleType): + srcfile = tabmodule.__file__ + else: + if '.' not in tabmodule: + srcfile = pdict['__file__'] + else: + parts = tabmodule.split('.') + pkgname = '.'.join(parts[:-1]) + exec('import %s' % pkgname) + srcfile = getattr(sys.modules[pkgname], '__file__', '') + outputdir = os.path.dirname(srcfile) + + # Determine if the module is package of a package or not. + # If so, fix the tabmodule setting so that tables load correctly + pkg = pdict.get('__package__') + if pkg and isinstance(tabmodule, str): + if '.' not in tabmodule: + tabmodule = pkg + '.' + tabmodule + + + + # Set start symbol if it's specified directly using an argument + if start is not None: + pdict['start'] = start + + # Collect parser information from the dictionary + pinfo = ParserReflect(pdict, log=errorlog) + pinfo.get_all() + + if pinfo.error: + raise YaccError('Unable to build parser') + + # Check signature against table files (if any) + signature = pinfo.signature() + + # Read the tables + try: + lr = LRTable() + if picklefile: + read_signature = lr.read_pickle(picklefile) + else: + read_signature = lr.read_table(tabmodule) + if optimize or (read_signature == signature): + try: + lr.bind_callables(pinfo.pdict) + parser = LRParser(lr, pinfo.error_func) + parse = parser.parse + return parser + except Exception as e: + errorlog.warning('There was a problem loading the table file: %r', e) + except VersionError as e: + errorlog.warning(str(e)) + except ImportError: + pass + + if debuglog is None: + if debug: + try: + debuglog = PlyLogger(open(os.path.join(outputdir, debugfile), 'w')) + except IOError as e: + errorlog.warning("Couldn't open %r. %s" % (debugfile, e)) + debuglog = NullLogger() + else: + debuglog = NullLogger() + + debuglog.info('Created by PLY version %s (http://www.dabeaz.com/ply)', __version__) + + errors = False + + # Validate the parser information + if pinfo.validate_all(): + raise YaccError('Unable to build parser') + + if not pinfo.error_func: + errorlog.warning('no p_error() function is defined') + + # Create a grammar object + grammar = Grammar(pinfo.tokens) + + # Set precedence level for terminals + for term, assoc, level in pinfo.preclist: + try: + grammar.set_precedence(term, assoc, level) + except GrammarError as e: + errorlog.warning('%s', e) + + # Add productions to the grammar + for funcname, gram in pinfo.grammar: + file, line, prodname, syms = gram + try: + grammar.add_production(prodname, syms, funcname, file, line) + except GrammarError as e: + errorlog.error('%s', e) + errors = True + + # Set the grammar start symbols + try: + if start is None: + grammar.set_start(pinfo.start) + else: + grammar.set_start(start) + except GrammarError as e: + errorlog.error(str(e)) + errors = True + + if errors: + raise YaccError('Unable to build parser') + + # Verify the grammar structure + undefined_symbols = grammar.undefined_symbols() + for sym, prod in undefined_symbols: + errorlog.error('%s:%d: Symbol %r used, but not defined as a token or a rule', prod.file, prod.line, sym) + errors = True + + unused_terminals = grammar.unused_terminals() + if unused_terminals: + debuglog.info('') + debuglog.info('Unused terminals:') + debuglog.info('') + for term in unused_terminals: + errorlog.warning('Token %r defined, but not used', term) + debuglog.info(' %s', term) + + # Print out all productions to the debug log + if debug: + debuglog.info('') + debuglog.info('Grammar') + debuglog.info('') + for n, p in enumerate(grammar.Productions): + debuglog.info('Rule %-5d %s', n, p) + + # Find unused non-terminals + unused_rules = grammar.unused_rules() + for prod in unused_rules: + errorlog.warning('%s:%d: Rule %r defined, but not used', prod.file, prod.line, prod.name) + + if len(unused_terminals) == 1: + errorlog.warning('There is 1 unused token') + if len(unused_terminals) > 1: + errorlog.warning('There are %d unused tokens', len(unused_terminals)) + + if len(unused_rules) == 1: + errorlog.warning('There is 1 unused rule') + if len(unused_rules) > 1: + errorlog.warning('There are %d unused rules', len(unused_rules)) + + if debug: + debuglog.info('') + debuglog.info('Terminals, with rules where they appear') + debuglog.info('') + terms = list(grammar.Terminals) + terms.sort() + for term in terms: + debuglog.info('%-20s : %s', term, ' '.join([str(s) for s in grammar.Terminals[term]])) + + debuglog.info('') + debuglog.info('Nonterminals, with rules where they appear') + debuglog.info('') + nonterms = list(grammar.Nonterminals) + nonterms.sort() + for nonterm in nonterms: + debuglog.info('%-20s : %s', nonterm, ' '.join([str(s) for s in grammar.Nonterminals[nonterm]])) + debuglog.info('') + + if check_recursion: + unreachable = grammar.find_unreachable() + for u in unreachable: + errorlog.warning('Symbol %r is unreachable', u) + + infinite = grammar.infinite_cycles() + for inf in infinite: + errorlog.error('Infinite recursion detected for symbol %r', inf) + errors = True + + unused_prec = grammar.unused_precedence() + for term, assoc in unused_prec: + errorlog.error('Precedence rule %r defined for unknown symbol %r', assoc, term) + errors = True + + if errors: + raise YaccError('Unable to build parser') + + # Run the LRGeneratedTable on the grammar + if debug: + errorlog.debug('Generating %s tables', method) + + lr = LRGeneratedTable(grammar, method, debuglog) + + if debug: + num_sr = len(lr.sr_conflicts) + + # Report shift/reduce and reduce/reduce conflicts + if num_sr == 1: + errorlog.warning('1 shift/reduce conflict') + elif num_sr > 1: + errorlog.warning('%d shift/reduce conflicts', num_sr) + + num_rr = len(lr.rr_conflicts) + if num_rr == 1: + errorlog.warning('1 reduce/reduce conflict') + elif num_rr > 1: + errorlog.warning('%d reduce/reduce conflicts', num_rr) + + # Write out conflicts to the output file + if debug and (lr.sr_conflicts or lr.rr_conflicts): + debuglog.warning('') + debuglog.warning('Conflicts:') + debuglog.warning('') + + for state, tok, resolution in lr.sr_conflicts: + debuglog.warning('shift/reduce conflict for %s in state %d resolved as %s', tok, state, resolution) + + already_reported = set() + for state, rule, rejected in lr.rr_conflicts: + if (state, id(rule), id(rejected)) in already_reported: + continue + debuglog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) + debuglog.warning('rejected rule (%s) in state %d', rejected, state) + errorlog.warning('reduce/reduce conflict in state %d resolved using rule (%s)', state, rule) + errorlog.warning('rejected rule (%s) in state %d', rejected, state) + already_reported.add((state, id(rule), id(rejected))) + + warned_never = [] + for state, rule, rejected in lr.rr_conflicts: + if not rejected.reduced and (rejected not in warned_never): + debuglog.warning('Rule (%s) is never reduced', rejected) + errorlog.warning('Rule (%s) is never reduced', rejected) + warned_never.append(rejected) + + # Write the table file if requested + if write_tables: + try: + lr.write_table(tabmodule, outputdir, signature) + except IOError as e: + errorlog.warning("Couldn't create %r. %s" % (tabmodule, e)) + + # Write a pickled version of the tables + if picklefile: + try: + lr.pickle_table(picklefile, signature) + except IOError as e: + errorlog.warning("Couldn't create %r. %s" % (picklefile, e)) + + # Build the parser + lr.bind_callables(pinfo.pdict) + parser = LRParser(lr, pinfo.error_func) + + parse = parser.parse + return parser diff --git a/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ygen.py b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ygen.py new file mode 100644 index 0000000000000000000000000000000000000000..acf5ca1a37b69389256227c570c65eed96e3228e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pycparser/ply/ygen.py @@ -0,0 +1,74 @@ +# ply: ygen.py +# +# This is a support program that auto-generates different versions of the YACC parsing +# function with different features removed for the purposes of performance. +# +# Users should edit the method LParser.parsedebug() in yacc.py. The source code +# for that method is then used to create the other methods. See the comments in +# yacc.py for further details. + +import os.path +import shutil + +def get_source_range(lines, tag): + srclines = enumerate(lines) + start_tag = '#--! %s-start' % tag + end_tag = '#--! %s-end' % tag + + for start_index, line in srclines: + if line.strip().startswith(start_tag): + break + + for end_index, line in srclines: + if line.strip().endswith(end_tag): + break + + return (start_index + 1, end_index) + +def filter_section(lines, tag): + filtered_lines = [] + include = True + tag_text = '#--! %s' % tag + for line in lines: + if line.strip().startswith(tag_text): + include = not include + elif include: + filtered_lines.append(line) + return filtered_lines + +def main(): + dirname = os.path.dirname(__file__) + shutil.copy2(os.path.join(dirname, 'yacc.py'), os.path.join(dirname, 'yacc.py.bak')) + with open(os.path.join(dirname, 'yacc.py'), 'r') as f: + lines = f.readlines() + + parse_start, parse_end = get_source_range(lines, 'parsedebug') + parseopt_start, parseopt_end = get_source_range(lines, 'parseopt') + parseopt_notrack_start, parseopt_notrack_end = get_source_range(lines, 'parseopt-notrack') + + # Get the original source + orig_lines = lines[parse_start:parse_end] + + # Filter the DEBUG sections out + parseopt_lines = filter_section(orig_lines, 'DEBUG') + + # Filter the TRACKING sections out + parseopt_notrack_lines = filter_section(parseopt_lines, 'TRACKING') + + # Replace the parser source sections with updated versions + lines[parseopt_notrack_start:parseopt_notrack_end] = parseopt_notrack_lines + lines[parseopt_start:parseopt_end] = parseopt_lines + + lines = [line.rstrip()+'\n' for line in lines] + with open(os.path.join(dirname, 'yacc.py'), 'w') as f: + f.writelines(lines) + + print('Updated yacc.py') + +if __name__ == '__main__': + main() + + + + + diff --git a/data/miniconda3/lib/python3.13/site-packages/pydantic_core-2.41.5.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/pydantic_core-2.41.5.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0716871caabdbbb3e77a0371d49936cef1923ea1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pydantic_core-2.41.5.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2022 Samuel Colvin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/AUTHORS b/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/AUTHORS new file mode 100644 index 0000000000000000000000000000000000000000..811c66ae178b354c0a0eb9bd5e7a9ac63b4b056c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/AUTHORS @@ -0,0 +1,291 @@ +Pygments is written and maintained by Georg Brandl . + +Major developers are Tim Hatch and Armin Ronacher +. + +Other contributors, listed alphabetically, are: + +* Sam Aaron -- Ioke lexer +* Jean Abou Samra -- LilyPond lexer +* João Abecasis -- JSLT lexer +* Ali Afshar -- image formatter +* Thomas Aglassinger -- Easytrieve, JCL, Rexx, Transact-SQL and VBScript + lexers +* Maxence Ahlouche -- PostgreSQL Explain lexer +* Muthiah Annamalai -- Ezhil lexer +* Nikolay Antipov -- OpenSCAD lexer +* Kumar Appaiah -- Debian control lexer +* Andreas Amann -- AppleScript lexer +* Timothy Armstrong -- Dart lexer fixes +* Jeffrey Arnold -- R/S, Rd, BUGS, Jags, and Stan lexers +* Eiríkr Åsheim -- Uxntal lexer +* Jeremy Ashkenas -- CoffeeScript lexer +* José Joaquín Atria -- Praat lexer +* Stefan Matthias Aust -- Smalltalk lexer +* Lucas Bajolet -- Nit lexer +* Ben Bangert -- Mako lexers +* Max Battcher -- Darcs patch lexer +* Thomas Baruchel -- APL lexer +* Tim Baumann -- (Literate) Agda lexer +* Paul Baumgart, 280 North, Inc. -- Objective-J lexer +* Michael Bayer -- Myghty lexers +* Thomas Beale -- Archetype lexers +* John Benediktsson -- Factor lexer +* David Benjamin, Google LLC -- TLS lexer +* Trevor Bergeron -- mIRC formatter +* Vincent Bernat -- LessCSS lexer +* Christopher Bertels -- Fancy lexer +* Sébastien Bigaret -- QVT Operational lexer +* Jarrett Billingsley -- MiniD lexer +* Adam Blinkinsop -- Haskell, Redcode lexers +* Stéphane Blondon -- Procfile, SGF and Sieve lexers +* Frits van Bommel -- assembler lexers +* Pierre Bourdon -- bugfixes +* Martijn Braam -- Kernel log lexer, BARE lexer +* JD Browne, Google LLC -- GoogleSQL lexer +* Matthias Bussonnier -- ANSI style handling for terminal-256 formatter +* chebee7i -- Python traceback lexer improvements +* Hiram Chirino -- Scaml and Jade lexers +* Mauricio Caceres -- SAS and Stata lexers. +* Michael Camilleri, John Gabriele, sogaiu -- Janet lexer +* Daren Chandisingh -- Gleam lexer +* Ian Cooper -- VGL lexer +* David Corbett -- Inform, Jasmin, JSGF, Snowball, and TADS 3 lexers +* Leaf Corcoran -- MoonScript lexer +* Fraser Cormack -- TableGen lexer +* Gabriel Corona -- ASN.1 lexer +* Christopher Creutzig -- MuPAD lexer +* Daniël W. Crompton -- Pike lexer +* Pete Curry -- bugfixes +* Bryan Davis -- EBNF lexer +* Bruno Deferrari -- Shen lexer +* Walter Dörwald -- UL4 lexer +* Luke Drummond -- Meson lexer +* Giedrius Dubinskas -- HTML formatter improvements +* Owen Durni -- Haxe lexer +* Alexander Dutton, Oxford University Computing Services -- SPARQL lexer +* James Edwards -- Terraform lexer +* Nick Efford -- Python 3 lexer +* Sven Efftinge -- Xtend lexer +* Artem Egorkine -- terminal256 formatter +* Matthew Fernandez -- CAmkES lexer +* Paweł Fertyk -- GDScript lexer, HTML formatter improvements +* Michael Ficarra -- CPSA lexer +* James H. Fisher -- PostScript lexer +* Amanda Fitch, Google LLC -- GoogleSQL lexer +* William S. Fulton -- SWIG lexer +* Carlos Galdino -- Elixir and Elixir Console lexers +* Michael Galloy -- IDL lexer +* Naveen Garg -- Autohotkey lexer +* Simon Garnotel -- FreeFem++ lexer +* Laurent Gautier -- R/S lexer +* Alex Gaynor -- PyPy log lexer +* Richard Gerkin -- Igor Pro lexer +* Alain Gilbert -- TypeScript lexer +* Alex Gilding -- BlitzBasic lexer +* GitHub, Inc -- DASM16, Augeas, TOML, and Slash lexers +* Bertrand Goetzmann -- Groovy lexer +* Krzysiek Goj -- Scala lexer +* Rostyslav Golda -- FloScript lexer +* Andrey Golovizin -- BibTeX lexers +* Matt Good -- Genshi, Cheetah lexers +* Michał Górny -- vim modeline support +* Alex Gosse -- TrafficScript lexer +* Patrick Gotthardt -- PHP namespaces support +* Hubert Gruniaux -- C and C++ lexer improvements +* Olivier Guibe -- Asymptote lexer +* Phil Hagelberg -- Fennel lexer +* Florian Hahn -- Boogie lexer +* Martin Harriman -- SNOBOL lexer +* Matthew Harrison -- SVG formatter +* Steven Hazel -- Tcl lexer +* Dan Michael Heggø -- Turtle lexer +* Aslak Hellesøy -- Gherkin lexer +* Greg Hendershott -- Racket lexer +* Justin Hendrick -- ParaSail lexer +* Jordi Gutiérrez Hermoso -- Octave lexer +* David Hess, Fish Software, Inc. -- Objective-J lexer +* Ken Hilton -- Typographic Number Theory and Arrow lexers +* Varun Hiremath -- Debian control lexer +* Rob Hoelz -- Perl 6 lexer +* Doug Hogan -- Mscgen lexer +* Ben Hollis -- Mason lexer +* Max Horn -- GAP lexer +* Fred Hornsey -- OMG IDL Lexer +* Alastair Houghton -- Lexer inheritance facility +* Tim Howard -- BlitzMax lexer +* Dustin Howett -- Logos lexer +* Ivan Inozemtsev -- Fantom lexer +* Hiroaki Itoh -- Shell console rewrite, Lexers for PowerShell session, + MSDOS session, BC, WDiff +* Brian R. Jackson -- Tea lexer +* Christian Jann -- ShellSession lexer +* Jonas Camillus Jeppesen -- Line numbers and line highlighting for + RTF-formatter +* Dennis Kaarsemaker -- sources.list lexer +* Dmitri Kabak -- Inferno Limbo lexer +* Igor Kalnitsky -- vhdl lexer +* Colin Kennedy - USD lexer +* Alexander Kit -- MaskJS lexer +* Pekka Klärck -- Robot Framework lexer +* Gerwin Klein -- Isabelle lexer +* Eric Knibbe -- Lasso lexer +* Stepan Koltsov -- Clay lexer +* Oliver Kopp - Friendly grayscale style +* Adam Koprowski -- Opa lexer +* Benjamin Kowarsch -- Modula-2 lexer +* Domen Kožar -- Nix lexer +* Oleh Krekel -- Emacs Lisp lexer +* Alexander Kriegisch -- Kconfig and AspectJ lexers +* Marek Kubica -- Scheme lexer +* Jochen Kupperschmidt -- Markdown processor +* Gerd Kurzbach -- Modelica lexer +* Jon Larimer, Google Inc. -- Smali lexer +* Olov Lassus -- Dart lexer +* Matt Layman -- TAP lexer +* Dan Lazin, Google LLC -- GoogleSQL lexer +* Kristian Lyngstøl -- Varnish lexers +* Sylvestre Ledru -- Scilab lexer +* Chee Sing Lee -- Flatline lexer +* Mark Lee -- Vala lexer +* Thomas Linder Puls -- Visual Prolog lexer +* Pete Lomax -- Phix lexer +* Valentin Lorentz -- C++ lexer improvements +* Ben Mabey -- Gherkin lexer +* Angus MacArthur -- QML lexer +* Louis Mandel -- X10 lexer +* Louis Marchand -- Eiffel lexer +* Simone Margaritelli -- Hybris lexer +* Tim Martin - World of Warcraft TOC lexer +* Kirk McDonald -- D lexer +* Gordon McGregor -- SystemVerilog lexer +* Stephen McKamey -- Duel/JBST lexer +* Brian McKenna -- F# lexer +* Charles McLaughlin -- Puppet lexer +* Kurt McKee -- Tera Term macro lexer, PostgreSQL updates, MySQL overhaul, JSON lexer +* Joe Eli McIlvain -- Savi lexer +* Lukas Meuser -- BBCode formatter, Lua lexer +* Cat Miller -- Pig lexer +* Paul Miller -- LiveScript lexer +* Hong Minhee -- HTTP lexer +* Michael Mior -- Awk lexer +* Bruce Mitchener -- Dylan lexer rewrite +* Reuben Morais -- SourcePawn lexer +* Jon Morton -- Rust lexer +* Paulo Moura -- Logtalk lexer +* Mher Movsisyan -- DTD lexer +* Dejan Muhamedagic -- Crmsh lexer +* Adrien Nayrat -- PostgreSQL Explain lexer +* Ana Nelson -- Ragel, ANTLR, R console lexers +* David Neto, Google LLC -- WebGPU Shading Language lexer +* Kurt Neufeld -- Markdown lexer +* Nam T. Nguyen -- Monokai style +* Jesper Noehr -- HTML formatter "anchorlinenos" +* Mike Nolta -- Julia lexer +* Avery Nortonsmith -- Pointless lexer +* Jonas Obrist -- BBCode lexer +* Edward O'Callaghan -- Cryptol lexer +* David Oliva -- Rebol lexer +* Pat Pannuto -- nesC lexer +* Jon Parise -- Protocol buffers and Thrift lexers +* Benjamin Peterson -- Test suite refactoring +* Ronny Pfannschmidt -- BBCode lexer +* Dominik Picheta -- Nimrod lexer +* Andrew Pinkham -- RTF Formatter Refactoring +* Clément Prévost -- UrbiScript lexer +* Tanner Prynn -- cmdline -x option and loading lexers from files +* Oleh Prypin -- Crystal lexer (based on Ruby lexer) +* Nick Psaris -- K and Q lexers +* Xidorn Quan -- Web IDL lexer +* Elias Rabel -- Fortran fixed form lexer +* raichoo -- Idris lexer +* Daniel Ramirez -- GDScript lexer +* Kashif Rasul -- CUDA lexer +* Nathan Reed -- HLSL lexer +* Justin Reidy -- MXML lexer +* Jonathon Reinhart, Google LLC -- Soong lexer +* Norman Richards -- JSON lexer +* Corey Richardson -- Rust lexer updates +* Fabrizio Riguzzi -- cplint leder +* Lubomir Rintel -- GoodData MAQL and CL lexers +* Andre Roberge -- Tango style +* Georg Rollinger -- HSAIL lexer +* Michiel Roos -- TypoScript lexer +* Konrad Rudolph -- LaTeX formatter enhancements +* Mario Ruggier -- Evoque lexers +* Miikka Salminen -- Lovelace style, Hexdump lexer, lexer enhancements +* Stou Sandalski -- NumPy, FORTRAN, tcsh and XSLT lexers +* Matteo Sasso -- Common Lisp lexer +* Joe Schafer -- Ada lexer +* Max Schillinger -- TiddlyWiki5 lexer +* Andrew Schmidt -- X++ lexer +* Ken Schutte -- Matlab lexers +* René Schwaiger -- Rainbow Dash style +* Sebastian Schweizer -- Whiley lexer +* Tassilo Schweyer -- Io, MOOCode lexers +* Pablo Seminario -- PromQL lexer +* Ted Shaw -- AutoIt lexer +* Joerg Sieker -- ABAP lexer +* Robert Simmons -- Standard ML lexer +* Kirill Simonov -- YAML lexer +* Corbin Simpson -- Monte lexer +* Ville Skyttä -- ASCII armored lexer +* Alexander Smishlajev -- Visual FoxPro lexer +* Steve Spigarelli -- XQuery lexer +* Jerome St-Louis -- eC lexer +* Camil Staps -- Clean and NuSMV lexers; Solarized style +* James Strachan -- Kotlin lexer +* Tom Stuart -- Treetop lexer +* Colin Sullivan -- SuperCollider lexer +* Ben Swift -- Extempore lexer +* tatt61880 -- Kuin lexer +* Edoardo Tenani -- Arduino lexer +* Tiberius Teng -- default style overhaul +* Jeremy Thurgood -- Erlang, Squid config lexers +* Brian Tiffin -- OpenCOBOL lexer +* Bob Tolbert -- Hy lexer +* Doug Torrance -- Macaulay2 lexer +* Matthias Trute -- Forth lexer +* Tuoa Spi T4 -- Bdd lexer +* Erick Tryzelaar -- Felix lexer +* Alexander Udalov -- Kotlin lexer improvements +* Thomas Van Doren -- Chapel lexer +* Dave Van Ee -- Uxntal lexer updates +* Daniele Varrazzo -- PostgreSQL lexers +* Abe Voelker -- OpenEdge ABL lexer +* Pepijn de Vos -- HTML formatter CTags support +* Matthias Vallentin -- Bro lexer +* Benoît Vinot -- AMPL lexer +* Linh Vu Hong -- RSL lexer +* Taavi Väänänen -- Debian control lexer +* Immanuel Washington -- Smithy lexer +* Nathan Weizenbaum -- Haml and Sass lexers +* Nathan Whetsell -- Csound lexers +* Dietmar Winkler -- Modelica lexer +* Nils Winter -- Smalltalk lexer +* Davy Wybiral -- Clojure lexer +* Whitney Young -- ObjectiveC lexer +* Diego Zamboni -- CFengine3 lexer +* Enrique Zamudio -- Ceylon lexer +* Alex Zimin -- Nemerle lexer +* Rob Zimmerman -- Kal lexer +* Evgenii Zheltonozhskii -- Maple lexer +* Vincent Zurczak -- Roboconf lexer +* Hubert Gruniaux -- C and C++ lexer improvements +* Thomas Symalla -- AMDGPU Lexer +* 15b3 -- Image Formatter improvements +* Fabian Neumann -- CDDL lexer +* Thomas Duboucher -- CDDL lexer +* Philipp Imhof -- Pango Markup formatter +* Thomas Voss -- Sed lexer +* Martin Fischer -- WCAG contrast testing +* Marc Auberer -- Spice lexer +* Amr Hesham -- Carbon lexer +* diskdance -- Wikitext lexer +* vanillajonathan -- PRQL lexer +* Nikolay Antipov -- OpenSCAD lexer +* Markus Meyer, Nextron Systems -- YARA lexer +* Hannes Römer -- Mojo lexer +* Jan Frederik Schaefer -- PDDL lexer + +Many thanks for all contributions! diff --git a/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..446a1a805c8a949579fb8a9799f2bec7777349dc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pygments-2.19.2.dist-info/licenses/LICENSE @@ -0,0 +1,25 @@ +Copyright (c) 2006-2022 by the respective authors (see AUTHORS file). +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd3f8508896017b74f2c8d01ef4a6e75acc2689c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/actions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/actions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf4ac3856b2b4e8afce400c824b63ee284babb13 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/actions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/common.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/common.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8b8c72ba10d5d5696bb46783e4dcdd05928e01c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/common.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6c7be90e3c694f7557e171a471f1644f40d4cec3 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/helpers.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/helpers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9ba6fac68144a57aa5e77e63bca4c84812c4e008 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/helpers.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/results.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/results.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..412e8b728d7d9e01805c34da454b6694fafbc0a6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/results.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/testing.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/testing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1e2067aa08867ef48498b925746db9ca6cb25ff Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/testing.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/unicode.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/unicode.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..616edfdfbdc6d1bf86da43070a43723797f21b26 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/unicode.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/util.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/util.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..41b6c5ab01b7091c6f66f2a5838a5f15ff45ede7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/util.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/warnings.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/warnings.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d2c95baee41bd7dbdd6560e526d7ae0e1c2e1595 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/__pycache__/warnings.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..48e597d7e8a5c9d9e1d0d51ab443f596df6de770 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/best_practices.md b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/best_practices.md new file mode 100644 index 0000000000000000000000000000000000000000..94aa52d8f42579e90ddff66d53efc1626f27ff41 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/best_practices.md @@ -0,0 +1,75 @@ + + +## Planning +- If not provided or if target language definition is ambiguous, ask for examples of valid strings to be parsed +- Before developing the pyparsing expressions, define a Backus-Naur Form definition and save this in docs/grammar.md. Update this document as changes are made in the parser. + +## Implementing +- Import pyparsing using `import pyparsing as pp`, and use that for all pyparsing references. + - If referencing names from `pyparsing.common`, follow the pyparsing import with "ppc = pp.common" and use `ppc` as the namespace to access `pyparsing.common`. + - If referencing names from `pyparsing.unicode`, follow the pyparsing import with "ppu = pp.unicode" and use `ppu` as the namespace to access `pyparsing.unicode`. +- When writing parsers that contain recursive elements (using `Forward()` or `infix_notation()`), immediately enable packrat parsing for performance: `pp.ParserElement.enable_packrat()` (call this right after importing pyparsing). See https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html. + - For recursive grammars, define placeholders with `pp.Forward()` and assign later using the `<<=` operator; give Forwards meaningful names with `set_name()` to improve errors. +- Use PEP8 method and argument names in the pyparsing API (`parse_string`, not `parseString`). +- Do not include expressions for matching whitespace in the grammar. Pyparsing skips whitespace by default. +- For line-oriented grammars where newlines are significant, set skippable whitespace to just spaces/tabs early: `pp.ParserElement.set_default_whitespace_chars(" \t")`, and define `NL = pp.LineEnd().suppress()` to handle line ends explicitly. +- Prefer operator forms for readability: use +, |, ^, ~, etc., instead of explicit And/MatchFirst/Or/Not classes (see Usage notes in https://pyparsing-docs.readthedocs.io/en/latest/HowToUsePyparsing.html). +- Use `set_name()` on all major grammar elements to support railroad diagramming and better error/debug output. +- The grammar should be independently testable, without pulling in separate modules for data structures, evaluation, or command execution. +- Use results names for robust access to parsed data fields; results names should be valid Python identifiers to support attribute-style access on returned ParseResults. + - Results names should take the place of numeric indexing into parsed results in most places. + - Define results names using call format not `set_results_name()`, example: `full_name = Word(alphas)("first_name") + Word(alphas)("last_name")` + - If adding results name to an expression that is contains one more sub-expressions with results names, the expression must be inclused in a Group. +- Prefer `Keyword` over `Literal` for reserved words to avoid partial matches (e.g., `Keyword("for")` will not match the leading "for" in "format"). + - Use `pp.CaselessKeyword`/`pp.CaselessLiteral` when keywords should match regardless of case. +- When the full input must be consumed, call `parse_string` with `parse_all=True`. +- If the grammar must handle comments, define an expression for them and use the `ignore()` method to skip them. + - Prefer built-ins like `pp.cpp_style_comment` and `pp.python_style_comment` for common comment syntaxes. +- Use pyparsing `Group` to organize sub-expressions. Groups are also important for preserving results names when a sub-expression is used in a `OneOrMore` or `ZeroOrMore` expression. +- Suppress punctuation tokens to keep results clean; a convenient pattern is `LBRACK, RBRACK, LBRACE, RBRACE, COLON = pp.Suppress.using_each("[]{}:")`. +- For comma-separated sequences, prefer `pp.DelimitedList(...)`; wrap with `pp.Optional(...)` to allow empty lists or objects where appropriate. +- For helper sub-expressions used only to build larger expressions, consider `set_name(None)` to keep result dumps uncluttered. +- Use pyparsing `Each()` to define a list of elements that may occur in any order. + - The '&' operator is the operator form of Each and is often more readable when combining order-independent parts. +- Use parse actions to do parse-time conversion of data from strings to useful data types. + - Use objects defined in pyparsing.common for common types like integer, real — these already have their conversion parse actions defined. + - For quoted strings, use `pp.dbl_quoted_string().set_parse_action(pp.remove_quotes)` to unquote automatically. + - Map reserved words to Python constants per this example for parsing "true" to auto-convert to a Python True: `pp.Keyword("true").set_parse_action(pp.replace_with(True))` (and similarly for false/null/etc.). + - When you want native Python containers from the parse, use `pp.Group(..., aslist=True)` for lists and `pp.Dict(..., asdict=True)` for dict-like data. +- Use "using_each" with a list of keywords to define keyword constants, instead of separate assignments. +- Choose the appropriate matching method: + - `parse_string()` parses from the start + - `search_string()` searches anywhere in the text + - `scan_string()` yields all matches with positions + - `transform_string()` is a convenience wrapper around `scan_string` to apply filters or transforms defined in parse actions, to perform batch transforms or conversions of expressions within a larger body of text +- For line suffixes or directives, combine lookahead and slicing helpers: `pp.FollowedBy(...)` with `pp.rest_of_line`; when reusing a base expression with a different parse action, call `.copy()` before applying the new action to avoid side effects. +- When defining a parser to be used in a REPL: + - add pyparsing `Tag()` elements of the form `Tag("command", )` to each command definition to support model construction from parsed commands. + - define model classes using dataclasses, and use the "command" attribute in the parsed results to identify which model class to create. The model classes can then be used to construct the model from the ParseResults returned by parse_string(). Define the models in a separate parser_models.py file. +- If defining the grammar as part of a Parser class, only the finished grammar needs to be implemented as an instance variable. +- `ParseResults` support "in" testing for results names. Use "in" tests for the existence of results names, not `hasattr()`. +- Avoid left recursion where possible. If you must support left-recursive grammars, enable it with `pp.ParserElement.enable_left_recursion()` and do not enable packrat at the same time (these modes are incompatible). +- Use `pp.SkipTo` as a skipping expression to skip over arbitrary content. + - For example, `pp.SkipTo(pp.LineEnd())` will skip over all content until the end of the line; add a stop_on argument to SkipTo to stop skipping when a particular string is matched. + - Use `...` in place of simple SkipTo(expression) + +## Testing +- Use the pyparsing `ParserElement.run_tests` method to run mini validation tests. + - Pass a single multiline string to `run_tests` to test the parser on multiple test input strings, each line is a separate test. + - You can add comments starting with "#" within the string passed to `run_tests` to document the individual test cases. + - To pass test input strings that span multiple lines, pass the test input strings as a list of strings. + - Pass `parse_all=True` to `run_tests` to test that the entire input is consumed. +- When generating unit tests for the parser: + - generate tests that include presence and absence of optional elements + - use the methods in the mixin class pyparsing.testing.TestParseResultsAsserts to easily define expression, test input string, and expected results + - do not generate tests for invalid data + +## Debugging +- If troubleshooting parse actions, use pyparsing's `trace_parse_action` decorator to echo arguments and return value +- During development, call `pp.autoname_elements()` to auto-assign names to unnamed expressions to improve `dump()` and error messages. +- Sub-expressions can be tested in isolation using `ParserElement.matches()` +- When defined out of order, Literals can mistakenly match fragments: `Literal("for")` will match the leading "for" in "format". Can be corrected by using `Keyword` instead of `Literal`. +- Dump the parsed results using `ParseResults.dump()`, `ParseResults.pprint()`, or `repr(ParseResults)`. diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__main__.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..b3172570ce5be7e8ec468ad4c1e493ac2df06886 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__main__.py @@ -0,0 +1,2 @@ +import pyparsing +pyparsing.show_best_practices() diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..70cb017a4f335ba52915bddfe30791b1fa96771c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..845177d0cf9c2fd01a80d2498440c6227800c38d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/ai/show_best_practices/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b8baa47d14751ee7954e380ef16b97707bce9e0d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__init__.py @@ -0,0 +1,761 @@ +# mypy: ignore-errors +from __future__ import annotations + +import itertools +import railroad +import pyparsing +import dataclasses +import typing +from typing import ( + Generic, + TypeVar, + Callable, + Iterable, +) +from jinja2 import Template +from io import StringIO +import inspect +import re + + +jinja2_template_source = """\ +{% if not embed %} + + + +{% endif %} + {% if not head %} + + {% else %} + {{ head | safe }} + {% endif %} +{% if not embed %} + + +{% endif %} + +{{ body | safe }} +{% for diagram in diagrams %} +
    +

    {{ diagram.title }}

    +
    {{ diagram.text }}
    +
    + {{ diagram.svg }} +
    +
    +{% endfor %} +{% if not embed %} + + +{% endif %} +""" + +template = Template(jinja2_template_source) + + +_bookmark_lookup = {} +_bookmark_ids = itertools.count(start=1) + +def _make_bookmark(s: str) -> str: + """ + Converts a string into a valid HTML bookmark (ID or anchor name). + """ + if s in _bookmark_lookup: + return _bookmark_lookup[s] + + # Replace invalid characters with hyphens and ensure only valid characters + bookmark = re.sub(r'[^a-zA-Z0-9-]+', '-', s) + + # Ensure it starts with a letter by adding 'z' if necessary + if not bookmark[:1].isalpha(): + bookmark = f"z{bookmark}" + + # Convert to lowercase and strip hyphens + bookmark = bookmark.lower().strip('-') + + _bookmark_lookup[s] = bookmark = f"{bookmark}-{next(_bookmark_ids):04d}" + + return bookmark + + +def _collapse_verbose_regex(regex_str: str) -> str: + if "\n" not in regex_str: + return regex_str + collapsed = pyparsing.Regex(r"#.*$").suppress().transform_string(regex_str) + collapsed = re.sub(r"\s*\n\s*", "", collapsed) + return collapsed + + +@dataclasses.dataclass +class NamedDiagram: + """ + A simple structure for associating a name with a railroad diagram + """ + + name: str + index: int + diagram: railroad.DiagramItem = None + + @property + def bookmark(self): + bookmark = _make_bookmark(self.name) + return bookmark + + +T = TypeVar("T") + + +class EachItem(railroad.Group): + """ + Custom railroad item to compose a: + + - :class:`railroad.Group` containing a + + - :class:`railroad.OneOrMore` containing a + + - :class:`railroad.Choice` of the elements in the + :class:`railroad.Each` + + with the group label indicating that all must be matched + """ + + all_label = "[ALL]" + + def __init__(self, *items) -> None: + choice_item = railroad.Choice(len(items) - 1, *items) + one_or_more_item = railroad.OneOrMore(item=choice_item) + super().__init__(one_or_more_item, label=self.all_label) + + +class AnnotatedItem(railroad.Group): + """ + Simple subclass of Group that creates an annotation label + """ + + def __init__(self, label: str, item) -> None: + super().__init__(item=item, label=f"[{label}]" if label else "") + + +class EditablePartial(Generic[T]): + """ + Acts like a functools.partial, but can be edited. In other words, it represents a type that hasn't yet been + constructed. + """ + + # We need this here because the railroad constructors actually transform the data, so can't be called until the + # entire tree is assembled + + def __init__(self, func: Callable[..., T], args: list, kwargs: dict) -> None: + self.func = func + self.args = args + self.kwargs = kwargs + + @classmethod + def from_call(cls, func: Callable[..., T], *args, **kwargs) -> EditablePartial[T]: + """ + If you call this function in the same way that you would call the constructor, + it will store the arguments as you expect. For example + ``EditablePartial.from_call(Fraction, 1, 3)() == Fraction(1, 3)`` + """ + return EditablePartial(func=func, args=list(args), kwargs=kwargs) + + @property + def name(self): + return self.kwargs["name"] + + def __call__(self) -> T: + """ + Evaluate the partial and return the result + """ + args = self.args.copy() + kwargs = self.kwargs.copy() + + # This is a helpful hack to allow you to specify varargs parameters (e.g. *args) as keyword args (e.g. + # args=['list', 'of', 'things']) + arg_spec = inspect.getfullargspec(self.func) + if arg_spec.varargs in self.kwargs: + args += kwargs.pop(arg_spec.varargs) + + return self.func(*args, **kwargs) + + +def railroad_to_html(diagrams: list[NamedDiagram], embed=False, **kwargs) -> str: + """ + Given a list of :class:`NamedDiagram`, produce a single HTML string + that visualises those diagrams. + + :params kwargs: kwargs to be passed in to the template + """ + data = [] + for diagram in diagrams: + if diagram.diagram is None: + continue + io = StringIO() + try: + css = kwargs.get("css") + diagram.diagram.writeStandalone(io.write, css=css) + except AttributeError: + diagram.diagram.writeSvg(io.write) + title = diagram.name + if diagram.index == 0: + title += " (root)" + data.append( + { + "title": title, "text": "", "svg": io.getvalue(), "bookmark": diagram.bookmark + } + ) + + return template.render(diagrams=data, embed=embed, **kwargs) + + +def resolve_partial(partial: EditablePartial[T]) -> T: + """ + Recursively resolves a collection of Partials into whatever type they are + """ + if isinstance(partial, EditablePartial): + partial.args = resolve_partial(partial.args) + partial.kwargs = resolve_partial(partial.kwargs) + return partial() + elif isinstance(partial, list): + return [resolve_partial(x) for x in partial] + elif isinstance(partial, dict): + return {key: resolve_partial(x) for key, x in partial.items()} + else: + return partial + + +def to_railroad( + element: pyparsing.ParserElement, + diagram_kwargs: typing.Optional[dict] = None, + vertical: int = 3, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> list[NamedDiagram]: + """ + Convert a pyparsing element tree into a list of diagrams. This is the recommended entrypoint to diagram + creation if you want to access the Railroad tree before it is converted to HTML + + :param element: base element of the parser being diagrammed + + :param diagram_kwargs: kwargs to pass to the :meth:`Diagram` constructor + + :param vertical: (optional) int - limit at which number of alternatives + should be shown vertically instead of horizontally + + :param show_results_names: bool to indicate whether results name + annotations should be included in the diagram + + :param show_groups: bool to indicate whether groups should be highlighted + with an unlabeled surrounding box + + :param show_hidden: bool to indicate whether internal elements that are + typically hidden should be shown + """ + # Convert the whole tree underneath the root + lookup = ConverterState(diagram_kwargs=diagram_kwargs or {}) + _to_diagram_element( + element, + lookup=lookup, + parent=None, + vertical=vertical, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + root_id = id(element) + # Convert the root if it hasn't been already + if root_id in lookup: + if not element.customName: + lookup[root_id].name = "" + lookup[root_id].mark_for_extraction(root_id, lookup, force=True) + + # Now that we're finished, we can convert from intermediate structures into Railroad elements + diags = list(lookup.diagrams.values()) + if len(diags) > 1: + # collapse out duplicate diags with the same name + seen = set() + deduped_diags = [] + for d in diags: + # don't extract SkipTo elements, they are uninformative as subdiagrams + if d.name == "...": + continue + if d.name is not None and d.name not in seen: + seen.add(d.name) + deduped_diags.append(d) + resolved = [resolve_partial(partial) for partial in deduped_diags] + else: + # special case - if just one diagram, always display it, even if + # it has no name + resolved = [resolve_partial(partial) for partial in diags] + return sorted(resolved, key=lambda diag: diag.index) + + +def _should_vertical( + specification: int, exprs: Iterable[pyparsing.ParserElement] +) -> bool: + """ + Returns true if we should return a vertical list of elements + """ + if specification is None: + return False + else: + return len(_visible_exprs(exprs)) >= specification + + +@dataclasses.dataclass +class ElementState: + """ + State recorded for an individual pyparsing Element + """ + + #: The pyparsing element that this represents + element: pyparsing.ParserElement + #: The output Railroad element in an unconverted state + converted: EditablePartial + #: The parent Railroad element, which we store so that we can extract this if it's duplicated + parent: EditablePartial + #: The order in which we found this element, used for sorting diagrams if this is extracted into a diagram + number: int + #: The name of the element + name: str = None + #: The index of this inside its parent + parent_index: typing.Optional[int] = None + #: If true, we should extract this out into a subdiagram + extract: bool = False + #: If true, all of this element's children have been filled out + complete: bool = False + + def mark_for_extraction( + self, el_id: int, state: ConverterState, name: str = None, force: bool = False + ): + """ + Called when this instance has been seen twice, and thus should eventually be extracted into a sub-diagram + :param el_id: id of the element + :param state: element/diagram state tracker + :param name: name to use for this element's text + :param force: If true, force extraction now, regardless of the state of this. Only useful for extracting the + root element when we know we're finished + """ + self.extract = True + + # Set the name + if not self.name: + if name: + # Allow forcing a custom name + self.name = name + elif self.element.customName: + self.name = self.element.customName + else: + self.name = "" + + # Just because this is marked for extraction doesn't mean we can do it yet. We may have to wait for children + # to be added + # Also, if this is just a string literal etc, don't bother extracting it + if force or (self.complete and _worth_extracting(self.element)): + state.extract_into_diagram(el_id) + + +class ConverterState: + """ + Stores some state that persists between recursions into the element tree + """ + index_generator = itertools.count(start=1) + + def __init__(self, diagram_kwargs: typing.Optional[dict] = None) -> None: + #: A dictionary mapping ParserElements to state relating to them + self._element_diagram_states: dict[int, ElementState] = {} + #: A dictionary mapping ParserElement IDs to subdiagrams generated from them + self.diagrams: dict[int, EditablePartial[NamedDiagram]] = {} + #: The index of the next element. This is used for sorting + self.index: int = 0 + #: Shared kwargs that are used to customize the construction of diagrams + self.diagram_kwargs: dict = diagram_kwargs or {} + self.extracted_diagram_names: set[str] = set() + + def __setitem__(self, key: int, value: ElementState): + self._element_diagram_states[key] = value + + def __getitem__(self, key: int) -> ElementState: + return self._element_diagram_states[key] + + def __delitem__(self, key: int): + del self._element_diagram_states[key] + + def __contains__(self, key: int): + return key in self._element_diagram_states + + def get(self, key, default=None): + try: + return self[key] + except KeyError: + return default + + def generate_index(self) -> int: + """ + Generate a number used to index a diagram + """ + return next(self.index_generator) + + def extract_into_diagram(self, el_id: int): + """ + Used when we encounter the same token twice in the same tree. When this + happens, we replace all instances of that token with a terminal, and + create a new subdiagram for the token + """ + position = self[el_id] + + # Replace the original definition of this element with a regular block + if position.parent: + href = f"#{_make_bookmark(position.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=position.name, href=href) + if "item" in position.parent.kwargs: + position.parent.kwargs["item"] = ret + elif "items" in position.parent.kwargs: + position.parent.kwargs["items"][position.parent_index] = ret + + # If the element we're extracting is a group, skip to its content but keep the title + if position.converted.func == railroad.Group: + content = position.converted.kwargs["item"] + else: + content = position.converted + + self.diagrams[el_id] = EditablePartial.from_call( + NamedDiagram, + name=position.name, + diagram=EditablePartial.from_call( + railroad.Diagram, content, **self.diagram_kwargs + ), + index=position.number, + ) + + del self[el_id] + + +def _worth_extracting(element: pyparsing.ParserElement) -> bool: + """ + Returns true if this element is worth having its own sub-diagram. Simply, if any of its children + themselves have children, then its complex enough to extract + """ + children = element.recurse() + return any(child.recurse() for child in children) + + +def _apply_diagram_item_enhancements(fn): + """ + decorator to ensure enhancements to a diagram item (such as results name annotations) + get applied on return from _to_diagram_element (we do this since there are several + returns in _to_diagram_element) + """ + + def _inner( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, + ) -> typing.Optional[EditablePartial]: + ret = fn( + element, + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ) + + # apply annotation for results name, if present + if show_results_names and ret is not None: + element_results_name = element.resultsName + if element_results_name: + # add "*" to indicate if this is a "list all results" name + modal_tag = "" if element.modalResults else "*" + ret = EditablePartial.from_call( + railroad.Group, + item=ret, + label=f"{repr(element_results_name)}{modal_tag}", + ) + + return ret + + return _inner + + +def _visible_exprs(exprs: Iterable[pyparsing.ParserElement]): + non_diagramming_exprs = ( + pyparsing.ParseElementEnhance, + pyparsing.PositionToken, + pyparsing.And._ErrorStop, + ) + return [ + e + for e in exprs + if not isinstance(e, non_diagramming_exprs) + ] + + +@_apply_diagram_item_enhancements +def _to_diagram_element( + element: pyparsing.ParserElement, + parent: typing.Optional[EditablePartial], + lookup: ConverterState = None, + vertical: int = None, + index: int = 0, + name_hint: str = None, + show_results_names: bool = False, + show_groups: bool = False, + show_hidden: bool = False, +) -> typing.Optional[EditablePartial]: + """ + Recursively converts a PyParsing Element to a railroad Element + :param lookup: The shared converter state that keeps track of useful things + :param index: The index of this element within the parent + :param parent: The parent of this element in the output tree + :param vertical: Controls at what point we make a list of elements vertical. If this is an integer (the default), + it sets the threshold of the number of items before we go vertical. If True, always go vertical, if False, never + do so + :param name_hint: If provided, this will override the generated name + :param show_results_names: bool flag indicating whether to add annotations for results names + :param show_groups: bool flag indicating whether to show groups using bounding box + :param show_hidden: bool flag indicating whether to show elements that are typically hidden + :returns: The converted version of the input element, but as a Partial that hasn't yet been constructed + """ + exprs = element.recurse() + name = name_hint or element.customName or type(element).__name__ + + # Python's id() is used to provide a unique identifier for elements + el_id = id(element) + + element_results_name = element.resultsName + + # Here we basically bypass processing certain wrapper elements if they contribute nothing to the diagram + if not element.customName: + if isinstance( + element, + ( + # pyparsing.TokenConverter, + pyparsing.Forward, + pyparsing.Located, + pyparsing.AtStringStart, + pyparsing.AtLineStart, + ), + ): + # However, if this element has a useful custom name, and its child does not, we can pass it on to the child + if exprs: + if not exprs[0].customName: + propagated_name = name + else: + propagated_name = None + + return _to_diagram_element( + element.expr, + parent=parent, + lookup=lookup, + vertical=vertical, + index=index, + name_hint=propagated_name, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # If the element isn't worth extracting, we always treat it as the first time we say it + if _worth_extracting(element): + looked_up = lookup.get(el_id) + if looked_up and looked_up.name is not None: + # If we've seen this element exactly once before, we are only just now finding out that it's a duplicate, + # so we have to extract it into a new diagram. + looked_up.mark_for_extraction(el_id, lookup, name=name_hint) + href = f"#{_make_bookmark(looked_up.name)}" + ret = EditablePartial.from_call(railroad.NonTerminal, text=looked_up.name, href=href) + return ret + + elif el_id in lookup.diagrams: + # If we have seen the element at least twice before, and have already extracted it into a subdiagram, we + # just put in a marker element that refers to the sub-diagram + text = lookup.diagrams[el_id].kwargs["name"] + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=f"#{_make_bookmark(text)}" + ) + return ret + + # Recursively convert child elements + # Here we find the most relevant Railroad element for matching pyparsing Element + # We use ``items=[]`` here to hold the place for where the child elements will go once created + + # see if this element is normally hidden, and whether hidden elements are desired + # if not, just return None + if not element.show_in_diagram and not show_hidden: + return None + + if isinstance(element, pyparsing.And): + # detect And's created with ``expr*N`` notation - for these use a OneOrMore with a repeat + # (all will have the same name, and resultsName) + if not exprs: + return None + if len(set((e.name, e.resultsName) for e in exprs)) == 1 and len(exprs) > 2: + ret = EditablePartial.from_call( + railroad.OneOrMore, item="", repeat=str(len(exprs)) + ) + elif _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Stack, items=[]) + else: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif isinstance(element, (pyparsing.Or, pyparsing.MatchFirst)): + if not exprs: + return None + if _should_vertical(vertical, exprs): + ret = EditablePartial.from_call(railroad.Choice, 0, items=[]) + else: + ret = EditablePartial.from_call(railroad.HorizontalChoice, items=[]) + elif isinstance(element, pyparsing.Each): + if not exprs: + return None + ret = EditablePartial.from_call(EachItem, items=[]) + elif isinstance(element, pyparsing.NotAny): + ret = EditablePartial.from_call(AnnotatedItem, label="NOT", item="") + elif isinstance(element, pyparsing.FollowedBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKAHEAD", item="") + elif isinstance(element, pyparsing.PrecededBy): + ret = EditablePartial.from_call(AnnotatedItem, label="LOOKBEHIND", item="") + elif isinstance(element, pyparsing.Group): + if show_groups: + ret = EditablePartial.from_call(AnnotatedItem, label="", item="") + else: + ret = EditablePartial.from_call( + railroad.Group, item=None, label=element_results_name + ) + elif isinstance(element, pyparsing.TokenConverter): + label = type(element).__name__.lower() + if label == "tokenconverter": + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + ret = EditablePartial.from_call(AnnotatedItem, label=label, item="") + elif isinstance(element, pyparsing.Opt): + ret = EditablePartial.from_call(railroad.Optional, item="") + elif isinstance(element, pyparsing.OneOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[1, ...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.OneOrMore, item=None) + elif isinstance(element, pyparsing.ZeroOrMore): + if element.not_ender is not None: + args = [ + parent, + lookup, + vertical, + index, + name_hint, + show_results_names, + show_groups, + show_hidden, + ] + return _to_diagram_element( + (~element.not_ender.expr + element.expr)[...].set_name(element.name), + *args, + ) + ret = EditablePartial.from_call(railroad.ZeroOrMore, item="") + elif isinstance(element, pyparsing.Empty) and not element.customName: + # Skip unnamed "Empty" elements + ret = None + elif isinstance(element, pyparsing.ParseElementEnhance): + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + elif len(exprs) > 0 and not element_results_name: + ret = EditablePartial.from_call(railroad.Group, item="", label=name) + elif isinstance(element, pyparsing.Regex): + collapsed_patt = _collapse_verbose_regex(element.pattern) + ret = EditablePartial.from_call(railroad.Terminal, collapsed_patt) + elif len(exprs) > 0: + ret = EditablePartial.from_call(railroad.Sequence, items=[]) + else: + terminal = EditablePartial.from_call(railroad.Terminal, element.defaultName) + ret = terminal + + if ret is None: + return + + # Indicate this element's position in the tree so we can extract it if necessary + lookup[el_id] = ElementState( + element=element, + converted=ret, + parent=parent, + parent_index=index, + number=lookup.generate_index(), + ) + if element.customName: + lookup[el_id].mark_for_extraction(el_id, lookup, element.customName) + + i = 0 + for expr in exprs: + # Add a placeholder index in case we have to extract the child before we even add it to the parent + if "items" in ret.kwargs: + ret.kwargs["items"].insert(i, None) + + item = _to_diagram_element( + expr, + parent=ret, + lookup=lookup, + vertical=vertical, + index=i, + show_results_names=show_results_names, + show_groups=show_groups, + show_hidden=show_hidden, + ) + + # Some elements don't need to be shown in the diagram + if item is not None: + if "item" in ret.kwargs: + ret.kwargs["item"] = item + elif "items" in ret.kwargs: + # If we've already extracted the child, don't touch this index, since it's occupied by a nonterminal + ret.kwargs["items"][i] = item + i += 1 + elif "items" in ret.kwargs: + # If we're supposed to skip this element, remove it from the parent + del ret.kwargs["items"][i] + + # If all this items children are none, skip this item + if ret and ( + ("items" in ret.kwargs and len(ret.kwargs["items"]) == 0) + or ("item" in ret.kwargs and ret.kwargs["item"] is None) + ): + ret = EditablePartial.from_call(railroad.Terminal, name) + + # Mark this element as "complete", ie it has all of its children + if el_id in lookup: + lookup[el_id].complete = True + + if el_id in lookup and lookup[el_id].extract and lookup[el_id].complete: + lookup.extract_into_diagram(el_id) + if ret is not None: + text = lookup.diagrams[el_id].kwargs["name"] + href = f"#{_make_bookmark(text)}" + ret = EditablePartial.from_call( + railroad.NonTerminal, text=text, href=href + ) + + return ret diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b2208f14f709a8205d96ffa658aad5b4b40d35b6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/diagram/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__init__.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..303bb8df08155eea6ed04a8abab3ee9531b01b26 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..26dde528bfc9bb335b7fbe1cf885b3a091acfb0b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/__pycache__/cvt_pyparsing_pep8_names.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py new file mode 100644 index 0000000000000000000000000000000000000000..ecd2be7b4bc2eac78b4af9dd6829495bcf000338 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/pyparsing/tools/cvt_pyparsing_pep8_names.py @@ -0,0 +1,142 @@ +import warnings +from functools import lru_cache +import pyparsing as pp + + +@lru_cache(maxsize=None) +def camel_to_snake(s: str) -> str: + """ + Convert CamelCase to snake_case. + """ + return "".join(f"_{c.lower()}" if c.isupper() else c for c in s).lstrip("_") + + +pre_pep8_method_names = """ +addCondition addParseAction anyCloseTag anyOpenTag asDict asList cStyleComment canParseNext conditionAsParseAction +convertToDate convertToDatetime convertToFloat convertToInteger countedArray cppStyleComment dblQuotedString +dblSlashComment defaultName dictOf disableMemoization downcaseTokens enableLeftRecursion enablePackrat getName +htmlComment ignoreWhitespace infixNotation inlineLiteralsUsing javaStyleComment leaveWhitespace +lineEnd lineStart matchOnlyAtCol matchPreviousExpr matchPreviousLiteral nestedExpr nullDebugAction oneOf +originalTextFor parseFile parseString parseWithTabs pythonStyleComment quotedString removeQuotes replaceWith +resetCache restOfLine runTests scanString searchString setBreak setDebug setDebugActions setDefaultWhitespaceChars +setFailAction setName setParseAction setResultsName setWhitespaceChars sglQuotedString stringEnd stringStart tokenMap +traceParseAction transformString tryParse unicodeString upcaseTokens withAttribute withClass +""".split() + +special_changes = { + "opAssoc": "OpAssoc", + "delimitedList": "DelimitedList", + "delimited_list": "DelimitedList", + "replaceHTMLEntity": "replace_html_entity", + "makeHTMLTags": "make_html_tags", + "makeXMLTags": "make_xml_tags", + "commonHTMLEntity": "common_html_entity", + "stripHTMLTags": "strip_html_tags", + "indentedBlock": "IndentedBlock", + "locatedExpr": "Located", +} + +pre_pep8_arg_names = """parseAll maxMatches listAllMatches callDuringTry includeSeparators fullDump printResults +failureTests postParse matchString identChars maxMismatches initChars bodyChars asKeyword excludeChars asGroupList +asMatch quoteChar escChar escQuote unquoteResults endQuoteChar convertWhitespaceEscapes notChars wordChars stopOn +failOn joinString markerString intExpr useRegex asString ignoreExpr""".split() + +special_changes_arg_names = { + "asList": "aslist", +} + +pre_pep8_method_name = pp.one_of(pre_pep8_method_names, as_keyword=True) +pre_pep8_method_name.set_parse_action(lambda t: camel_to_snake(t[0])) +special_pre_pep8_name = pp.one_of(special_changes, as_keyword=True) +def update_special_changes(s, l, t): + if t[0] == "indentedBlock": + warnings.warn( + "Conversion of 'indentedBlock' to new 'IndentedBlock'" + " requires added code changes to remove 'indentStack' argument\n" + f" {pp.lineno(l, s)}: {pp.line(l, s)}", + stacklevel=2, + ) + elif t[0] == "locatedExpr": + warnings.warn( + "Conversion of 'locatedExpr' to new 'Located'" + " may require added code changes - Located does not automatically" + " group parsed elements\n" + f" {pp.lineno(l, s)}: {pp.line(l, s)}", + stacklevel=2, + ) + return special_changes[t[0]] +special_pre_pep8_name.set_parse_action(update_special_changes) +# only replace arg names if part of an arg list +pre_pep8_arg_name = pp.Regex( + rf"{pp.util.make_compressed_re(pre_pep8_arg_names)}" +) + pp.FollowedBy("=") +pre_pep8_arg_name.set_parse_action(lambda t: camel_to_snake(t[0])) +special_pre_pep8_arg_name = pp.one_of(special_changes_arg_names, as_keyword=True) + pp.FollowedBy("=") +special_pre_pep8_arg_name.set_parse_action(lambda t: special_changes_arg_names[t[0]]) + +pep8_converter = special_pre_pep8_arg_name | pre_pep8_method_name | special_pre_pep8_name | pre_pep8_arg_name + +if __name__ == "__main__": + import argparse + from pathlib import Path + import sys + + argparser = argparse.ArgumentParser( + description = ( + "Utility to convert Python pyparsing scripts using legacy" + " camelCase names to use PEP8 snake_case names." + "\nBy default, this script will only show whether this script would make any changes." + ) + ) + argparser.add_argument("--verbose", "-v", action="store_true", help="Show unified diff for each source file") + argparser.add_argument("-vv", action="store_true", dest="verbose2", help="Show unified diff for each source file, plus names of scanned files with no changes") + argparser.add_argument("--update", "-u", action="store_true", help="Update source files in-place") + argparser.add_argument("--encoding", type=str, default="utf-8", help="Encoding of source files (default: utf-8)") + argparser.add_argument("--exit-zero-even-if-changed", "-exit0", action="store_true", help="Exit with status code 0 even if changes were made") + argparser.add_argument("source_filename", nargs="+", help="Source filenames or filename patterns of Python files to be converted") + args = argparser.parse_args() + + + def show_diffs(original, modified): + import difflib + + diff = difflib.unified_diff( + original.splitlines(), modified.splitlines(), lineterm="" + ) + sys.stdout.writelines(f"{diff_line}\n" for diff_line in diff) + + exit_status = 0 + + for filename_pattern in args.source_filename: + + for filename in Path().glob(filename_pattern): + if not Path(filename).is_file(): + continue + + try: + original_contents = Path(filename).read_text(encoding=args.encoding) + modified_contents = pep8_converter.transform_string( + original_contents + ) + + if modified_contents != original_contents: + if args.update: + Path(filename).write_text(modified_contents, encoding=args.encoding) + print(f"Converted {filename}") + else: + print(f"Found required changes in {filename}") + + if args.verbose: + show_diffs(original_contents, modified_contents) + print() + + exit_status = 1 + + else: + if args.verbose2: + print(f"No required changes in {filename}") + + except Exception as e: + print(f"Failed to convert {filename}: {type(e).__name__}: {e}") + + sys.exit(exit_status if not args.exit_zero_even_if_changed else 0) diff --git a/data/miniconda3/lib/python3.13/site-packages/readchar-4.2.1.dist-info/licenses/LICENCE b/data/miniconda3/lib/python3.13/site-packages/readchar-4.2.1.dist-info/licenses/LICENCE new file mode 100644 index 0000000000000000000000000000000000000000..66937d171e48ca37b57383850b2c26f2c36e7701 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/readchar-4.2.1.dist-info/licenses/LICENCE @@ -0,0 +1,21 @@ +MIT Licence + +Copyright (c) 2022 Miguel Angel Garcia + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicence, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a337f1cc7acc2c5aa4f592ce7d9cfeb13711df1 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/core.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/core.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..13e64c91b3c2faf36e85b6c2bee471e2f6514315 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/core.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..befaac4d204ce8e7de9832ec32e2a4d7d25b5130 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/finder.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/finder.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e43916414432e77759649a9cc4d98a8966f8b984 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/rtree/__pycache__/finder.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Ball.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Ball.h new file mode 100644 index 0000000000000000000000000000000000000000..50299a9a6a19cc3798b9d3938e27e5552cd0b124 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Ball.h @@ -0,0 +1,98 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Peter Labadorf - plaba3.1415@gmail.com + ****************************************************************************** + * Copyright (c) 2023, Peter Labadorf + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#ifndef M_PI +#define M_PI 3.14159265358979323846 +#endif + +namespace SpatialIndex +{ + + class SIDX_DLL Ball: public Tools::IObject, public virtual IShape + { + public: + Ball(); + Ball(double radius, const Point& center); + Ball(double radius, const double *pCoords, uint32_t dimension); + Ball(const Ball& b); + ~Ball() override; + + virtual Ball& operator=(const Ball& b); + virtual bool operator==(const Ball& b) const; + + // + // IObject interface + // + + Ball* clone() override; + + // + // ISerializable interface + // + + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t *data) override; + void storeToByteArray(uint8_t **data, uint32_t &length) override; + + // + // IShape interface + // + + bool intersectsShape(const IShape &in) const override; + bool containsShape(const IShape &in) const override; + bool touchesShape(const IShape &in) const override; + void getCenter(SpatialIndex::Point &out) const override; + uint32_t getDimension() const override; + void getMBR(SpatialIndex::Region &out) const override; + double getArea() const override; + double getMinimumDistance(const IShape &in) const override; + + virtual bool containsLineSegment(const SpatialIndex::LineSegment *line) const; + virtual bool containsRegion(const SpatialIndex::Region *region) const; + + inline bool containsPoint(const Point *point) const + { + return getMinimumDistance(*point) <= m_centerPoint.m_dimension; + } + + inline bool containsBall(const Ball *ball) const + { + return getMinimumDistance(ball->m_centerPoint) + ball->m_radius <= m_radius; + } + + public: + double m_radius{0.0}; + Point m_centerPoint; + + }; // Ball + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const Ball& ball); + +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/LineSegment.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/LineSegment.h new file mode 100644 index 0000000000000000000000000000000000000000..5cd399ceed5fa4554fc1874fbf18348059feb4c1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/LineSegment.h @@ -0,0 +1,103 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL LineSegment : public Tools::IObject, public virtual IShape + { + public: + LineSegment(); + LineSegment(const double* startPoint, const double* endPoint, uint32_t dimension); + LineSegment(const Point& startPoint, const Point& endPoint); + LineSegment(const LineSegment& l); + ~LineSegment() override; + + virtual LineSegment& operator=(const LineSegment& p); + virtual bool operator==(const LineSegment& p) const; + + // + // IObject interface + // + LineSegment* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& length) override; + + // + // IShape interface + // + bool intersectsShape(const IShape& in) const override; + bool containsShape(const IShape& in) const override; + bool touchesShape(const IShape& in) const override; + void getCenter(Point& out) const override; + uint32_t getDimension() const override; + void getMBR(Region& out) const override; + double getArea() const override; + double getMinimumDistance(const IShape& in) const override; + + virtual bool intersectsLineSegment(const LineSegment& l) const; + virtual bool intersectsRegion(const Region& p) const; + virtual double getMinimumDistance(const Point& p) const; + //virtual double getMinimumDistance(const Region& r) const; + virtual double getRelativeMinimumDistance(const Point& p) const; + virtual double getRelativeMaximumDistance(const Region& r) const; + virtual double getAngleOfPerpendicularRay(); + + virtual void makeInfinite(uint32_t dimension); + virtual void makeDimension(uint32_t dimension); + + public: + uint32_t m_dimension{0}; + double* m_pStartPoint{nullptr}; + double* m_pEndPoint{nullptr}; + + friend class Region; + friend class Point; + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const LineSegment& pt); + + protected: + + //some helpers for intersects methods + static double doubleAreaTriangle(const Point& a, const Point& b, const Point& c); + static bool leftOf(const Point& a, const Point& b, const Point& c); + static bool collinear(const Point& a, const Point& b, const Point& c); + static bool between(const Point& a, const Point& b, const Point& c); + static bool between(double a, double b, double c); + static bool intersectsProper(const Point& a, const Point& b, const Point& c, const Point& d); + static bool intersects(const Point& a, const Point& b, const Point& c, const Point& d); + + }; // LineSegment + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const LineSegment& pt); +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MVRTree.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MVRTree.h new file mode 100644 index 0000000000000000000000000000000000000000..492e7428cc79faa8d0c5382d96c7f5cd4909f249 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MVRTree.h @@ -0,0 +1,88 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + namespace MVRTree + { + enum MVRTreeVariant + { + RV_LINEAR = 0x0, + RV_QUADRATIC, + RV_RSTAR + }; + + enum PersistenObjectIdentifier + { + PersistentIndex = 0x1, + PersistentLeaf = 0x2 + }; + + enum RangeQueryType + { + ContainmentQuery = 0x1, + IntersectionQuery = 0x2 + }; + + class SIDX_DLL Data : public IData, public Tools::ISerializable + { + public: + Data(uint32_t len, uint8_t* pData, TimeRegion& r, id_type id); + ~Data() override; + + Data* clone() override; + id_type getIdentifier() const override; + void getShape(IShape** out) const override; + void getData(uint32_t& len, uint8_t** data) const override; + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + id_type m_id; + TimeRegion m_region; + uint8_t* m_pData; + uint32_t m_dataLength; + }; // Data + + SIDX_DLL ISpatialIndex* returnMVRTree(IStorageManager& ind, Tools::PropertySet& in); + SIDX_DLL ISpatialIndex* createNewMVRTree( + IStorageManager& in, + double fillFactor, + uint32_t indexCapacity, + uint32_t leafCapacity, + uint32_t dimension, + MVRTreeVariant rv, + id_type& out_indexIdentifier + ); + SIDX_DLL ISpatialIndex* loadMVRTree( + IStorageManager& in, + id_type indexIdentifier + ); + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingPoint.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingPoint.h new file mode 100644 index 0000000000000000000000000000000000000000..ea9c35fbc6f3a670083c5557701ae255155311e8 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingPoint.h @@ -0,0 +1,85 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL MovingPoint : public TimePoint, public IEvolvingShape + { + public: + MovingPoint(); + MovingPoint(const double* pCoords, const double* pVCoords, const Tools::IInterval& ti, uint32_t dimension); + MovingPoint(const double* pCoords, const double* pVCoords, double tStart, double tEnd, uint32_t dimension); + MovingPoint(const Point& p, const Point& vp, const Tools::IInterval& ti); + MovingPoint(const Point& p, const Point& vp, double tStart, double tEnd); + MovingPoint(const MovingPoint& p); + ~MovingPoint() override; + + virtual MovingPoint& operator=(const MovingPoint& p); + virtual bool operator==(const MovingPoint& p) const; + + virtual double getCoord(uint32_t index, double t) const; + virtual double getProjectedCoord(uint32_t index, double t) const; + virtual double getVCoord(uint32_t index) const; + virtual void getPointAtTime(double t, Point& out) const; + + // + // IObject interface + // + MovingPoint* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + // + // IEvolvingShape interface + // + void getVMBR(Region& out) const override; + void getMBRAtTime(double t, Region& out) const override; + + void makeInfinite(uint32_t dimension) override; + void makeDimension(uint32_t dimension) override; + + private: + void initialize( + const double* pCoords, const double* pVCoords, + double tStart, double tEnd, uint32_t dimension); + + public: + double* m_pVCoords; + + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const MovingPoint& pt); + }; // MovingPoint + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const MovingPoint& pt); +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingRegion.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingRegion.h new file mode 100644 index 0000000000000000000000000000000000000000..8f3f0a9d933260bd45ab7af52a8e9686e4e6788a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/MovingRegion.h @@ -0,0 +1,166 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL MovingRegion : public TimeRegion, public IEvolvingShape + { + using Region::getLow; + using Region::getHigh; + using TimeRegion::intersectsRegionInTime; + using TimeRegion::containsRegionInTime; + using TimeRegion::combineRegionInTime; + using TimeRegion::getCombinedRegionInTime; + using TimeRegion::containsPointInTime; + + public: + MovingRegion(); + MovingRegion( + const double* pLow, const double* pHigh, + const double* pVLow, const double* pVHigh, + const Tools::IInterval& ti, uint32_t dimension); + MovingRegion( + const double* pLow, const double* pHigh, + const double* pVLow, const double* pVHigh, + double tStart, double tEnd, uint32_t dimension); + MovingRegion( + const Point& low, const Point& high, + const Point& vlow, const Point& vhigh, + const Tools::IInterval& ti); + MovingRegion( + const Point& low, const Point& high, + const Point& vlow, const Point& vhigh, + double tStart, double tEnd); + MovingRegion(const Region& mbr, const Region& vbr, const Tools::IInterval& ivI); + MovingRegion(const Region& mbr, const Region& vbr, double tStart, double tEnd); + MovingRegion(const MovingPoint& low, const MovingPoint& high); + MovingRegion(const MovingRegion& in); + ~MovingRegion() override; + + virtual MovingRegion& operator=(const MovingRegion& r); + virtual bool operator==(const MovingRegion&) const; + + bool isShrinking() const; + + virtual double getLow(uint32_t index, double t) const; + virtual double getHigh(uint32_t index, double t) const; + virtual double getExtrapolatedLow(uint32_t index, double t) const; + virtual double getExtrapolatedHigh(uint32_t index, double t) const; + virtual double getVLow(uint32_t index) const; + virtual double getVHigh(uint32_t index) const; + + virtual bool intersectsRegionInTime(const MovingRegion& r) const; + virtual bool intersectsRegionInTime(const MovingRegion& r, Tools::IInterval& out) const; + virtual bool intersectsRegionInTime(const Tools::IInterval& ivI, const MovingRegion& r, Tools::IInterval& ret) const; + virtual bool containsRegionInTime(const MovingRegion& r) const; + virtual bool containsRegionInTime(const Tools::IInterval& ivI, const MovingRegion& r) const; + virtual bool containsRegionAfterTime(double t, const MovingRegion& r) const; + + virtual double getProjectedSurfaceAreaInTime() const; + virtual double getProjectedSurfaceAreaInTime(const Tools::IInterval& ivI) const; + + virtual double getCenterDistanceInTime(const MovingRegion& r) const; + virtual double getCenterDistanceInTime(const Tools::IInterval& ivI, const MovingRegion& r) const; + + virtual bool intersectsRegionAtTime(double t, const MovingRegion& r) const; + virtual bool containsRegionAtTime(double t, const MovingRegion& r) const; + + virtual bool intersectsPointInTime(const MovingPoint& p) const; + virtual bool intersectsPointInTime(const MovingPoint& p, Tools::IInterval& out) const; + virtual bool intersectsPointInTime(const Tools::IInterval& ivI, const MovingPoint& p, Tools::IInterval& out) const; + virtual bool containsPointInTime(const MovingPoint& p) const; + virtual bool containsPointInTime(const Tools::IInterval& ivI, const MovingPoint& p) const; + + //virtual bool intersectsPointAtTime(double t, const MovingRegion& in) const; + //virtual bool containsPointAtTime(double t, const MovingRegion& in) const; + + virtual void combineRegionInTime(const MovingRegion& r); + virtual void combineRegionAfterTime(double t, const MovingRegion& r); + virtual void getCombinedRegionInTime(MovingRegion& out, const MovingRegion& in) const; + virtual void getCombinedRegionAfterTime(double t, MovingRegion& out, const MovingRegion& in) const; + + virtual double getIntersectingAreaInTime(const MovingRegion& r) const; + virtual double getIntersectingAreaInTime(const Tools::IInterval& ivI, const MovingRegion& r) const; + + // + // IObject interface + // + MovingRegion* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + // + // IEvolvingShape interface + // + void getVMBR(Region& out) const override; + void getMBRAtTime(double t, Region& out) const override; + + // + // ITimeShape interface + // + double getAreaInTime() const override; + double getAreaInTime(const Tools::IInterval& ivI) const override; + double getIntersectingAreaInTime(const ITimeShape& r) const override; + double getIntersectingAreaInTime(const Tools::IInterval& ivI, const ITimeShape& r) const override; + + void makeInfinite(uint32_t dimension) override; + void makeDimension(uint32_t dimension) override; + + private: + void initialize( + const double* pLow, const double* pHigh, + const double* pVLow, const double* pVHigh, + double tStart, double tEnd, uint32_t dimension); + + public: + class CrossPoint + { + public: + double m_t; + uint32_t m_dimension; + uint32_t m_boundary; + const MovingRegion* m_to; + + }; // CrossPoint + + public: + double* m_pVLow{nullptr}; + double* m_pVHigh{nullptr}; + + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const MovingRegion& r); + }; // MovingRegion + + typedef Tools::PoolPointer MovingRegionPtr; + SIDX_DLL std::ostream& operator<<(std::ostream& os, const MovingRegion& r); +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Point.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Point.h new file mode 100644 index 0000000000000000000000000000000000000000..1f9c8d4e8e2f64b57eaae3175f52e0b85da89c7e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Point.h @@ -0,0 +1,92 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "tools/Tools.h" + +namespace SpatialIndex +{ + class SIDX_DLL Point : public IShape, public Tools::IObject + { + public: + Point(); + Point(const double* pCoords, uint32_t dimension); + Point(const Point& p); + ~Point() override; + + virtual Point& operator=(const Point& p); + virtual bool operator==(const Point& p) const; + + // + // IObject interface + // + Point* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& length) override; + + // + // IShape interface + // + bool intersectsShape(const IShape& in) const override; + bool containsShape(const IShape& in) const override; + bool touchesShape(const IShape& in) const override; + void getCenter(Point& out) const override; + uint32_t getDimension() const override; + void getMBR(Region& out) const override; + double getArea() const override; + double getMinimumDistance(const IShape& in) const override; + + virtual double getMinimumDistance(const Point& p) const; + + virtual double getCoordinate(uint32_t index) const; + + virtual void makeInfinite(uint32_t dimension); + virtual void makeDimension(uint32_t dimension); + + static constexpr int local_dim = 3; + + public: + uint32_t m_dimension{0}; + double* m_pCoords{nullptr}; + + friend class Region; + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const Point& pt); + + private: + double m_local[local_dim]; + }; // Point + + typedef Tools::PoolPointer PointPtr; + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const Point& pt); +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/RTree.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/RTree.h new file mode 100644 index 0000000000000000000000000000000000000000..03a08ab919f28ae0c0fe94ad7142ed8116546958 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/RTree.h @@ -0,0 +1,108 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + namespace RTree + { + enum RTreeVariant + { + RV_LINEAR = 0x0, + RV_QUADRATIC, + RV_RSTAR + }; + + enum BulkLoadMethod + { + BLM_STR = 0x0 + }; + + enum PersistenObjectIdentifier + { + PersistentIndex = 0x1, + PersistentLeaf = 0x2 + }; + + enum RangeQueryType + { + ContainmentQuery = 0x1, + IntersectionQuery = 0x2 + }; + + class SIDX_DLL Data : public IData, public Tools::ISerializable + { + public: + Data(uint32_t len, uint8_t* pData, Region& r, id_type id); + ~Data() override; + + Data* clone() override; + id_type getIdentifier() const override; + void getShape(IShape** out) const override; + void getData(uint32_t& len, uint8_t** data) const override; + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + id_type m_id; + Region m_region; + uint8_t* m_pData; + uint32_t m_dataLength; + }; // Data + + SIDX_DLL ISpatialIndex* returnRTree(IStorageManager& ind, Tools::PropertySet& in); + SIDX_DLL ISpatialIndex* createNewRTree( + IStorageManager& sm, + double fillFactor, + uint32_t indexCapacity, + uint32_t leafCapacity, + uint32_t dimension, + RTreeVariant rv, + id_type& indexIdentifier + ); + SIDX_DLL ISpatialIndex* createAndBulkLoadNewRTree( + BulkLoadMethod m, + IDataStream& stream, + IStorageManager& sm, + double fillFactor, + uint32_t indexCapacity, + uint32_t leafCapacity, + uint32_t dimension, + RTreeVariant rv, + id_type& indexIdentifier + ); + SIDX_DLL ISpatialIndex* createAndBulkLoadNewRTree( + BulkLoadMethod m, + IDataStream& stream, + IStorageManager& sm, + Tools::PropertySet& ps, + id_type& indexIdentifier + ); + SIDX_DLL ISpatialIndex* loadRTree(IStorageManager& in, id_type indexIdentifier); + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Region.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Region.h new file mode 100644 index 0000000000000000000000000000000000000000..c5b4e295a83ab3331708dbe8d50e660e2a4db04f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Region.h @@ -0,0 +1,111 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL Region : public IShape, public Tools::IObject + { + public: + Region(); + Region(const double* pLow, const double* pHigh, uint32_t dimension); + Region(const Point& low, const Point& high); + Region(const Region& in); + ~Region() override; + + virtual Region& operator=(const Region& r); + virtual bool operator==(const Region&) const; + + // + // IObject interface + // + Region* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& length) override; + + // + // IShape interface + // + bool intersectsShape(const IShape& in) const override; + bool containsShape(const IShape& in) const override; + bool touchesShape(const IShape& in) const override; + void getCenter(Point& out) const override; + uint32_t getDimension() const override; + void getMBR(Region& out) const override; + double getArea() const override; + double getMinimumDistance(const IShape& in) const override; + + virtual bool intersectsRegion(const Region& in) const; + virtual bool containsRegion(const Region& in) const; + virtual bool touchesRegion(const Region& in) const; + virtual double getMinimumDistance(const Region& in) const; + + virtual bool intersectsLineSegment(const LineSegment& in) const; + + virtual bool containsPoint(const Point& in) const; + virtual bool touchesPoint(const Point& in) const; + virtual double getMinimumDistance(const Point& in) const; + + virtual Region getIntersectingRegion(const Region& r) const; + virtual double getIntersectingArea(const Region& in) const; + virtual double getMargin() const; + + virtual void combineRegion(const Region& in); + virtual void combinePoint(const Point& in); + virtual void getCombinedRegion(Region& out, const Region& in) const; + + virtual double getLow(uint32_t index) const; + virtual double getHigh(uint32_t index) const; + + virtual void makeInfinite(uint32_t dimension); + virtual void makeDimension(uint32_t dimension); + + static constexpr int local_dim = 3; + + private: + void initialize(const double* pLow, const double* pHigh, uint32_t dimension); + + public: + uint32_t m_dimension{0}; + double* m_pLow{nullptr}; + double* m_pHigh{nullptr}; + + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const Region& r); + + private: + double m_local[2*local_dim]; + }; // Region + + typedef Tools::PoolPointer RegionPtr; + SIDX_DLL std::ostream& operator<<(std::ostream& os, const Region& r); +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/SpatialIndex.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/SpatialIndex.h new file mode 100644 index 0000000000000000000000000000000000000000..8f4d3594783a0ed3c3087c1d56c7db17b483df93 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/SpatialIndex.h @@ -0,0 +1,265 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "tools/Tools.h" + +#ifndef M_PI_2 +#define M_PI_2 1.57079632679489661922 +#endif + +namespace SpatialIndex +{ + class Point; + class Ball; + class LineSegment; + class Region; + + + typedef int64_t id_type; + + enum CommandType + { + CT_NODEREAD = 0x0, + CT_NODEDELETE, + CT_NODEWRITE + }; + + class SIDX_DLL InvalidPageException : public Tools::Exception + { + public: + InvalidPageException(id_type id); + ~InvalidPageException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // InvalidPageException + + // + // Interfaces + // + + class SIDX_DLL IShape : public Tools::ISerializable + { + public: + virtual bool intersectsShape(const IShape& in) const = 0; + virtual bool containsShape(const IShape& in) const = 0; + virtual bool touchesShape(const IShape& in) const = 0; + virtual void getCenter(Point& out) const = 0; + virtual uint32_t getDimension() const = 0; + virtual void getMBR(Region& out) const = 0; + virtual double getArea() const = 0; + virtual double getMinimumDistance(const IShape& in) const = 0; + ~IShape() override = default; + }; // IShape + + class SIDX_DLL ITimeShape : public Tools::IInterval + { + public: + virtual bool intersectsShapeInTime(const ITimeShape& in) const = 0; + virtual bool intersectsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const = 0; + virtual bool containsShapeInTime(const ITimeShape& in) const = 0; + virtual bool containsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const = 0; + virtual bool touchesShapeInTime(const ITimeShape& in) const = 0; + virtual bool touchesShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const = 0; + virtual double getAreaInTime() const = 0; + virtual double getAreaInTime(const Tools::IInterval& ivI) const = 0; + virtual double getIntersectingAreaInTime(const ITimeShape& r) const = 0; + virtual double getIntersectingAreaInTime(const Tools::IInterval& ivI, const ITimeShape& r) const = 0; + ~ITimeShape() override = default; + }; // ITimeShape + + class SIDX_DLL IEvolvingShape + { + public: + virtual void getVMBR(Region& out) const = 0; + virtual void getMBRAtTime(double t, Region& out) const = 0; + virtual ~IEvolvingShape() = default; + }; // IEvolvingShape + + class SIDX_DLL IEntry : public Tools::IObject + { + public: + virtual id_type getIdentifier() const = 0; + virtual void getShape(IShape** out) const = 0; + ~IEntry() override = default; + }; // IEntry + + class SIDX_DLL INode : public IEntry, public Tools::ISerializable + { + public: + virtual uint32_t getChildrenCount() const = 0; + virtual id_type getChildIdentifier(uint32_t index) const = 0; + virtual void getChildData(uint32_t index, uint32_t& len, uint8_t** data) const = 0; + virtual void getChildShape(uint32_t index, IShape** out) const = 0; + virtual uint32_t getLevel() const = 0; + virtual bool isIndex() const = 0; + virtual bool isLeaf() const = 0; + ~INode() override = default; + }; // INode + + class SIDX_DLL IData : public IEntry + { + public: + virtual void getData(uint32_t& len, uint8_t** data) const = 0; + ~IData() override = default; + }; // IData + + class SIDX_DLL IDataStream : public Tools::IObjectStream + { + public: + IData* getNext() override = 0; + ~IDataStream() override = default; + }; // IDataStream + + class SIDX_DLL ICommand + { + public: + virtual void execute(const INode& in) = 0; + virtual ~ICommand() = default; + }; // ICommand + + class SIDX_DLL INearestNeighborComparator + { + public: + virtual double getMinimumDistance(const IShape& query, const IShape& entry) = 0; + virtual double getMinimumDistance(const IShape& query, const IData& data) = 0; + virtual ~INearestNeighborComparator() = default; + }; // INearestNeighborComparator + + class SIDX_DLL IStorageManager + { + public: + virtual void loadByteArray(const id_type id, uint32_t& len, uint8_t** data) = 0; + virtual void storeByteArray(id_type& id, const uint32_t len, const uint8_t* const data) = 0; + virtual void deleteByteArray(const id_type id) = 0; + virtual void flush() = 0; + virtual ~IStorageManager() = default; + }; // IStorageManager + + class SIDX_DLL IVisitor + { + public: + virtual void visitNode(const INode& in) = 0; + virtual void visitData(const IData& in) = 0; + virtual void visitData(std::vector& v) = 0; + virtual ~IVisitor() = default; + }; // IVisitor + + class SIDX_DLL IQueryStrategy + { + public: + virtual void getNextEntry(const IEntry& previouslyFetched, id_type& nextEntryToFetch, bool& bFetchNextEntry) = 0; + virtual ~IQueryStrategy() = default; + }; // IQueryStrategy + + class SIDX_DLL IStatistics + { + public: + virtual uint64_t getReads() const = 0; + virtual uint64_t getWrites() const = 0; + virtual uint32_t getNumberOfNodes() const = 0; + virtual uint64_t getNumberOfData() const = 0; + virtual ~IStatistics() = default; + }; // IStatistics + + class SIDX_DLL ISpatialIndex + { + public: + virtual void insertData(uint32_t len, const uint8_t* pData, const IShape& shape, id_type shapeIdentifier) = 0; + virtual bool deleteData(const IShape& shape, id_type shapeIdentifier) = 0; + virtual void internalNodesQuery(const IShape& query, IVisitor& v) = 0; + virtual void containsWhatQuery(const IShape& query, IVisitor& v) = 0; + virtual void intersectsWithQuery(const IShape& query, IVisitor& v) = 0; + virtual void pointLocationQuery(const Point& query, IVisitor& v) = 0; + virtual double nearestNeighborQuery(uint32_t k, const IShape& query, IVisitor& v, INearestNeighborComparator& nnc, double max_dist=0.0) = 0; + virtual double nearestNeighborQuery(uint32_t k, const IShape& query, IVisitor& v, double max_dist=0.0) = 0; + virtual void selfJoinQuery(const IShape& s, IVisitor& v) = 0; + virtual void queryStrategy(IQueryStrategy& qs) = 0; + virtual void getIndexProperties(Tools::PropertySet& out) const = 0; + virtual void addCommand(ICommand* in, CommandType ct) = 0; + virtual bool isIndexValid() = 0; + virtual void getStatistics(IStatistics** out) const = 0; + virtual void flush() = 0; + virtual ~ISpatialIndex() = default; + + }; // ISpatialIndex + + namespace StorageManager + { + enum StorageManagerConstants + { + EmptyPage = -0x1, + NewPage = -0x1 + }; + + class SIDX_DLL IBuffer : public IStorageManager + { + public: + virtual uint64_t getHits() = 0; + virtual void clear() = 0; + ~IBuffer() override = default; + }; // IBuffer + + SIDX_DLL IStorageManager* returnMemoryStorageManager(Tools::PropertySet& in); + SIDX_DLL IStorageManager* createNewMemoryStorageManager(); + + SIDX_DLL IStorageManager* returnDiskStorageManager(Tools::PropertySet& in); + SIDX_DLL IStorageManager* createNewDiskStorageManager(std::string& baseName, uint32_t pageSize); + SIDX_DLL IStorageManager* loadDiskStorageManager(std::string& baseName); + + SIDX_DLL IBuffer* returnRandomEvictionsBuffer(IStorageManager& ind, Tools::PropertySet& in); + SIDX_DLL IBuffer* createNewRandomEvictionsBuffer(IStorageManager& in, uint32_t capacity, bool bWriteThrough); + } + + // + // Global functions + // + SIDX_DLL std::ostream& operator<<(std::ostream&, const ISpatialIndex&); + SIDX_DLL std::ostream& operator<<(std::ostream&, const IStatistics&); +} + +#include "Point.h" +#include "Region.h" +#include "Ball.h" +#include "LineSegment.h" +#include "TimePoint.h" +#include "TimeRegion.h" +#include "MovingPoint.h" +#include "MovingRegion.h" +#include "RTree.h" +#include "MVRTree.h" +#include "TPRTree.h" +#include "Version.h" + + +// typedef SpatialIndex::Tools::PoolPointer RegionPtr; +// typedef SpatialIndex::Tools::PoolPointer PointPtr; +// typedef SpatialIndex::Tools::PoolPointer TimeRegionPtr; +// typedef SpatialIndex::Tools::PoolPointer MovingRegionPtr; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TPRTree.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TPRTree.h new file mode 100644 index 0000000000000000000000000000000000000000..7b743f94fa1970048ca19cd85dd16db4ee71e867 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TPRTree.h @@ -0,0 +1,85 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + + +#pragma once + +namespace SpatialIndex +{ + namespace TPRTree + { + enum TPRTreeVariant + { + TPRV_RSTAR = 0x2 + }; + + enum PersistenObjectIdentifier + { + PersistentIndex = 0x1, + PersistentLeaf = 0x2 + }; + + enum RangeQueryType + { + ContainmentQuery = 0x1, + IntersectionQuery = 0x2 + }; + + class SIDX_DLL Data : public IData, public Tools::ISerializable + { + public: + Data(uint32_t len, uint8_t* pData, MovingRegion& r, id_type id); + ~Data() override; + + Data* clone() override; + id_type getIdentifier() const override; + void getShape(IShape** out) const override; + void getData(uint32_t& len, uint8_t** data) const override; + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + id_type m_id; + MovingRegion m_region; + uint8_t* m_pData; + uint32_t m_dataLength; + }; // Data + + SIDX_DLL ISpatialIndex* returnTPRTree(IStorageManager& ind, Tools::PropertySet& in); + SIDX_DLL ISpatialIndex* createNewTPRTree( + IStorageManager& sm, + double fillFactor, + uint32_t indexCapacity, + uint32_t leafCapacity, + uint32_t dimension, + TPRTreeVariant rv, + double horizon, + id_type& indexIdentifier + ); + SIDX_DLL ISpatialIndex* loadTPRTree(IStorageManager& in, id_type indexIdentifier); + } +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimePoint.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimePoint.h new file mode 100644 index 0000000000000000000000000000000000000000..5db346c139cca8e6179c44fd03b0987e47fa7878 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimePoint.h @@ -0,0 +1,95 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL TimePoint : public Point, public ITimeShape + { + public: + TimePoint(); + TimePoint(const double* pCoords, const Tools::IInterval& ti, uint32_t dimension); + TimePoint(const double* pCoords, double tStart, double tEnd, uint32_t dimension); + TimePoint(const Point& p, const Tools::IInterval& ti); + TimePoint(const Point& p, double tStart, double tEnd); + TimePoint(const TimePoint& p); + ~TimePoint() override; + + virtual TimePoint& operator=(const TimePoint& p); + virtual bool operator==(const TimePoint& p) const; + + // + // IObject interface + // + TimePoint* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + // + // ITimeShape interface + // + bool intersectsShapeInTime(const ITimeShape& in) const override; + bool intersectsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + bool containsShapeInTime(const ITimeShape& in) const override; + bool containsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + bool touchesShapeInTime(const ITimeShape& in) const override; + bool touchesShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + double getAreaInTime() const override; + double getAreaInTime(const Tools::IInterval& ivI) const override; + double getIntersectingAreaInTime(const ITimeShape& r) const override; + double getIntersectingAreaInTime(const Tools::IInterval& ivI, const ITimeShape& r) const override; + + // + // IInterval interface + // + virtual Tools::IInterval& operator=(const Tools::IInterval&); + double getLowerBound() const override; + double getUpperBound() const override; + void setBounds(double, double) override; + bool intersectsInterval(const Tools::IInterval& ti) const override; + bool intersectsInterval(Tools::IntervalType t, const double start, const double end) const override; + bool containsInterval(const Tools::IInterval& ti) const override; + Tools::IntervalType getIntervalType() const override; + + void makeInfinite(uint32_t dimension) override; + void makeDimension(uint32_t dimension) override; + + public: + double m_startTime; + double m_endTime; + + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const TimePoint& pt); + }; // TimePoint + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const TimePoint& pt); +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimeRegion.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimeRegion.h new file mode 100644 index 0000000000000000000000000000000000000000..1da0ad9ca41b9b15eea776575fbafd9bf7718eb5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/TimeRegion.h @@ -0,0 +1,109 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +namespace SpatialIndex +{ + class SIDX_DLL TimeRegion : public Region, public ITimeShape + { + public: + TimeRegion(); + TimeRegion(const double* pLow, const double* pHigh, const Tools::IInterval& ti, uint32_t dimension); + TimeRegion(const double* pLow, const double* pHigh, double tStart, double tEnd, uint32_t dimension); + TimeRegion(const Point& low, const Point& high, const Tools::IInterval& ti); + TimeRegion(const Point& low, const Point& high, double tStart, double tEnd); + TimeRegion(const Region& in, const Tools::IInterval& ti); + TimeRegion(const Region& in, double tStart, double tEnd); + TimeRegion(const TimePoint& low, const TimePoint& high); + TimeRegion(const TimeRegion& in); + ~TimeRegion() override; + + virtual TimeRegion& operator=(const TimeRegion& r); + virtual bool operator==(const TimeRegion&) const; + + virtual bool intersectsRegionInTime(const TimeRegion& in) const; + virtual bool containsRegionInTime(const TimeRegion& in) const; + virtual bool touchesRegionInTime(const TimeRegion& in) const; + + virtual bool containsPointInTime(const TimePoint& in) const; + virtual bool touchesPointInTime(const TimePoint& in) const; + + virtual void combineRegionInTime(const TimeRegion& in); + virtual void getCombinedRegionInTime(TimeRegion& out, const TimeRegion& in) const; + + // + // IObject interface + // + TimeRegion* clone() override; + + // + // ISerializable interface + // + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& len) override; + + // + // ITimeShape interface + // + bool intersectsShapeInTime(const ITimeShape& in) const override; + bool intersectsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + bool containsShapeInTime(const ITimeShape& in) const override; + bool containsShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + bool touchesShapeInTime(const ITimeShape& in) const override; + bool touchesShapeInTime(const Tools::IInterval& ivI, const ITimeShape& in) const override; + double getAreaInTime() const override; + double getAreaInTime(const Tools::IInterval& ivI) const override; + double getIntersectingAreaInTime(const ITimeShape& r) const override; + double getIntersectingAreaInTime(const Tools::IInterval& ivI, const ITimeShape& r) const override; + + // + // IInterval interface + // + virtual Tools::IInterval& operator=(const Tools::IInterval&); + double getLowerBound() const override; + double getUpperBound() const override; + void setBounds(double, double) override; + bool intersectsInterval(const Tools::IInterval& ti) const override; + bool intersectsInterval(Tools::IntervalType t, const double start, const double end) const override; + bool containsInterval(const Tools::IInterval& ti) const override; + Tools::IntervalType getIntervalType() const override; + + void makeInfinite(uint32_t dimension) override; + void makeDimension(uint32_t dimension) override; + + public: + double m_startTime; + double m_endTime; + + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const TimeRegion& r); + }; // TimeRegion + + typedef Tools::PoolPointer TimeRegionPtr; + SIDX_DLL std::ostream& operator<<(std::ostream& os, const TimeRegion& r); +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Version.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Version.h new file mode 100644 index 0000000000000000000000000000000000000000..69fc0850baf5ebde070c7929a6bf887989b14cd1 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/Version.h @@ -0,0 +1,48 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2003, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#ifndef SIDX_VERSION_MAJOR +#define SIDX_VERSION_MAJOR 2 +#define SIDX_VERSION_MINOR 1 +#define SIDX_VERSION_REV 0 +#define SIDX_VERSION_BUILD 0 +#endif + +#ifndef SIDX_VERSION_NUM +#define SIDX_VERSION_NUM (SIDX_VERSION_MAJOR*1000+SIDX_VERSION_MINOR*100+SIDX_VERSION_REV*10+SIDX_VERSION_BUILD) +#endif + +#ifndef SIDX_RELEASE_DATE +#define SIDX_RELEASE_DATE 20241219 +#endif + +#ifndef SIDX_RELEASE_NAME +#define SIDX_RELEASE_NAME "2.1.0" +#endif + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/BoundsQuery.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/BoundsQuery.h new file mode 100644 index 0000000000000000000000000000000000000000..79fdcb82dbb560f07bdf5e2c3d5021bd7a281bdc --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/BoundsQuery.h @@ -0,0 +1,48 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement the bounds query. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL BoundsQuery : public SpatialIndex::IQueryStrategy +{ +private: + SpatialIndex::Region* m_bounds; + +public: + + BoundsQuery(); + ~BoundsQuery() { if (m_bounds != 0) delete m_bounds; } + void getNextEntry( const SpatialIndex::IEntry& entry, + SpatialIndex::id_type& nextEntry, + bool& hasNext); + + SpatialIndex::Region* GetBounds() const { return m_bounds; } +}; + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CountVisitor.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CountVisitor.h new file mode 100644 index 0000000000000000000000000000000000000000..eaaee8dd2c3904894958861e78165210fd299e2a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CountVisitor.h @@ -0,0 +1,48 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ objects to implement the count visitor. + * Author: Leonard Norrgård, leonard.norrgard@refactor.fi + ****************************************************************************** + * Copyright (c) 2010, Leonard Norrgård + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL CountVisitor : public SpatialIndex::IVisitor +{ +private: + uint64_t nResults; + +public: + + CountVisitor(); + ~CountVisitor(); + + uint64_t GetResultCount() const { return nResults; } + + void visitNode(const SpatialIndex::INode& n); + void visitData(const SpatialIndex::IData& d); + void visitData(std::vector& v); +}; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CustomStorage.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CustomStorage.h new file mode 100644 index 0000000000000000000000000000000000000000..fa670206bbd5f78e6da2a55ad580eac35ea8ff43 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/CustomStorage.h @@ -0,0 +1,84 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement the custom storage manager. + * Author: Matthias (nitro), nitro@dr-code.org + ****************************************************************************** + * Copyright (c) 2010, Matthias (nitro) + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +namespace SpatialIndex +{ + namespace StorageManager + { + struct SIDX_DLL CustomStorageManagerCallbacks + { + CustomStorageManagerCallbacks() + : context(0) + , createCallback(0) + , destroyCallback(0) + , loadByteArrayCallback(0) + , storeByteArrayCallback(0) + , deleteByteArrayCallback(0) + {} + + void* context; + void (*createCallback)( const void* context, int* errorCode ); + void (*destroyCallback)( const void* context, int* errorCode ); + void (*flushCallback)( const void* context, int* errorCode ); + void (*loadByteArrayCallback)( const void* context, const id_type page, uint32_t* len, uint8_t** data, int* errorCode ); + void (*storeByteArrayCallback)( const void* context, id_type* page, const uint32_t len, const uint8_t* const data, int* errorCode ); + void (*deleteByteArrayCallback)( const void* context, const id_type page, int* errorCode ); + }; + + class SIDX_DLL CustomStorageManager : public SpatialIndex::IStorageManager + { + public: + // I'd like this to be an enum, but casting between enums and ints is not nice + static const int NoError = 0; + static const int InvalidPageError = 1; + static const int IllegalStateError = 2; + + CustomStorageManager(Tools::PropertySet&); + + virtual ~CustomStorageManager(); + + virtual void flush(); + virtual void loadByteArray(const id_type page, uint32_t& len, uint8_t** data); + virtual void storeByteArray(id_type& page, const uint32_t len, const uint8_t* const data); + virtual void deleteByteArray(const id_type page); + + private: + CustomStorageManagerCallbacks callbacks; + + inline void processErrorCode(int errorCode, const id_type page); + }; // CustomStorageManager + + // factory function + IStorageManager* returnCustomStorageManager(Tools::PropertySet& in); + } +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/DataStream.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/DataStream.h new file mode 100644 index 0000000000000000000000000000000000000000..3334faff6ab0ee92d555b2e3ab1f7b74c4ec9e72 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/DataStream.h @@ -0,0 +1,56 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: Declarations to support stream loading via C API + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL DataStream : public SpatialIndex::IDataStream +{ +public: + DataStream(int (*readNext)(SpatialIndex::id_type* id, double **pMin, double **pMax, uint32_t *nDimension, const uint8_t **pData, size_t *nDataLength)); + ~DataStream(); + + SpatialIndex::IData* getNext(); + bool hasNext(); + + uint32_t size(); + void rewind(); + +protected: + SpatialIndex::RTree::Data* m_pNext; + SpatialIndex::id_type m_id; + +private: + int (*iterfunct)(SpatialIndex::id_type *id, double **pMin, double **pMax, uint32_t *nDimension, const uint8_t **pData, size_t *nDataLength); + + bool readData(); + bool m_bDoneReading; + +}; + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Error.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Error.h new file mode 100644 index 0000000000000000000000000000000000000000..e8cc647d6d0e70ef2a1b132ad2ca83f1ceb62e71 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Error.h @@ -0,0 +1,54 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement the error object. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL Error +{ +public: + + Error(int code, std::string const& message, std::string const& method); + + /// Copy constructor. + Error(Error const& other); + + /// Assignment operator. + Error& operator=(Error const& rhs); + + int GetCode() const { return m_code; } + const char* GetMessage() const { return m_message.c_str(); } + const char* GetMethod() const { return m_method.c_str(); } + +private: + + int m_code; + std::string m_message; + std::string m_method; +}; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/IdVisitor.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/IdVisitor.h new file mode 100644 index 0000000000000000000000000000000000000000..1a307d973dc8fc0f3aef13687e96231087e1e1c5 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/IdVisitor.h @@ -0,0 +1,51 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement a query ids only. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL IdVisitor : public SpatialIndex::IVisitor +{ +private: + std::vector m_vector; + uint64_t nResults; + +public: + + IdVisitor(); + ~IdVisitor(); + + uint64_t GetResultCount() const { return nResults; } + std::vector& GetResults() { return m_vector; } + void reset() { nResults = 0; m_vector.clear(); } + + void visitNode(const SpatialIndex::INode& n); + void visitData(const SpatialIndex::IData& d); + void visitData(std::vector& v); +}; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Index.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Index.h new file mode 100644 index 0000000000000000000000000000000000000000..e003af4a851ae852b458b2ade991038b2ba4a232 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Index.h @@ -0,0 +1,86 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement the wrapper. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + + +#include "sidx_export.h" +#include + +class SIDX_DLL Index +{ + +public: + Index(const Tools::PropertySet& poProperties); + Index(const Tools::PropertySet& poProperties, std::unique_ptr stream); + Index(const Tools::PropertySet& poProperties, int (*readNext)(SpatialIndex::id_type *id, double **pMin, double **pMax, uint32_t *nDimension, const uint8_t **pData, size_t* nDataLength)); + ~Index(); + + const Tools::PropertySet GetProperties() { index().getIndexProperties(m_properties); return m_properties;} + + bool insertFeature(uint64_t id, double *min, double *max); + + RTIndexType GetIndexType(); + void SetIndexType(RTIndexType v); + + RTStorageType GetIndexStorage(); + void SetIndexStorage(RTStorageType v); + + RTIndexVariant GetIndexVariant(); + void SetIndexVariant(RTIndexVariant v); + + int64_t GetResultSetOffset(); + void SetResultSetOffset(int64_t v); + + int64_t GetResultSetLimit(); + void SetResultSetLimit(int64_t v); + + void flush(); + + SpatialIndex::ISpatialIndex& index() {return *m_rtree;} + SpatialIndex::StorageManager::IBuffer& buffer() {return *m_buffer;} + +private: + + Index& operator=(const Index&); + Index(); + + void Initialize(); + SpatialIndex::IStorageManager* m_storage; + SpatialIndex::StorageManager::IBuffer* m_buffer; + SpatialIndex::ISpatialIndex* m_rtree; + + Tools::PropertySet m_properties; + int64_t m_resultSetLimit; + int64_t m_resultSetOffset; + + void Setup(); + SpatialIndex::IStorageManager* CreateStorage(); + SpatialIndex::StorageManager::IBuffer* CreateIndexBuffer(SpatialIndex::IStorageManager& storage); + SpatialIndex::ISpatialIndex* CreateIndex(); +}; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/LeafQuery.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/LeafQuery.h new file mode 100644 index 0000000000000000000000000000000000000000..9f30a0f3e3cb34906711e788c5f0dc87648998e4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/LeafQuery.h @@ -0,0 +1,73 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement a query of the index's leaves. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class LeafQueryResult; + +class SIDX_DLL LeafQuery : public SpatialIndex::IQueryStrategy +{ +private: + std::queue m_ids; + std::vector m_results; +public: + + LeafQuery(); + ~LeafQuery() { } + void getNextEntry( const SpatialIndex::IEntry& entry, + SpatialIndex::id_type& nextEntry, + bool& hasNext); + std::vector const& GetResults() const {return m_results;} +}; + +class SIDX_DLL LeafQueryResult +{ +private: + std::vector ids; + SpatialIndex::Region* bounds; + SpatialIndex::id_type m_id; + LeafQueryResult(); +public: + LeafQueryResult(SpatialIndex::id_type id) : bounds(0), m_id(id){} + ~LeafQueryResult() {if (bounds!=0) delete bounds;} + + /// Copy constructor. + LeafQueryResult(LeafQueryResult const& other); + + /// Assignment operator. + LeafQueryResult& operator=(LeafQueryResult const& rhs); + + std::vector const& GetIDs() const; + void SetIDs(std::vector& v); + const SpatialIndex::Region* GetBounds() const; + void SetBounds(const SpatialIndex::Region* b); + SpatialIndex::id_type getIdentifier() const {return m_id;} + void setIdentifier(uint32_t v) {m_id = v;} +}; diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/ObjVisitor.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/ObjVisitor.h new file mode 100644 index 0000000000000000000000000000000000000000..2c27d5a2c71a1616fa4da5f01f6f8132672e212f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/ObjVisitor.h @@ -0,0 +1,51 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement the object visitor. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "sidx_export.h" + +class SIDX_DLL ObjVisitor : public SpatialIndex::IVisitor +{ +private: + std::vector m_vector; + uint64_t nResults; + +public: + + ObjVisitor(); + ~ObjVisitor(); + + uint64_t GetResultCount() const { return nResults; } + std::vector& GetResults() { return m_vector; } + + void visitNode(const SpatialIndex::INode& n); + void visitData(const SpatialIndex::IData& d); + void visitData(std::vector& v); +}; + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Utility.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Utility.h new file mode 100644 index 0000000000000000000000000000000000000000..9962ceb4fe0d41934552059d6221b8ff247ba6d2 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/Utility.h @@ -0,0 +1,38 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement utilities. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#include "ObjVisitor.h" +#include "IdVisitor.h" +#include "sidx_export.h" + +#pragma once + +SIDX_DLL Tools::PropertySet* GetDefaults(); + +SIDX_DLL void Page_ResultSet_Ids(IdVisitor& visitor, int64_t** ids, int64_t nStart, int64_t nResultLimit, uint64_t* nResults); +SIDX_DLL void Page_ResultSet_Obj(ObjVisitor& visitor, IndexItemH** items, int64_t nStart, int64_t nResultLimit, uint64_t* nResults); diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_api.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_api.h new file mode 100644 index 0000000000000000000000000000000000000000..0042b99d1c2c26121f898c2553e32aa8b9f25ef7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_api.h @@ -0,0 +1,423 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C API. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#ifndef SIDX_API_H_INCLUDED +#define SIDX_API_H_INCLUDED + +#define SIDX_C_API 1 + +#include "sidx_config.h" + +#include + +IDX_C_START + +SIDX_DLL IndexH Index_Create(IndexPropertyH properties); + +SIDX_DLL IndexH Index_CreateWithStream( IndexPropertyH properties, + int (*readNext)(int64_t *id, double **pMin, double **pMax, uint32_t *nDimension, const uint8_t **pData, size_t *nDataLength) + ); + +SIDX_DLL IndexH Index_CreateWithArray(IndexPropertyH properties, uint64_t n, uint32_t dimension, uint64_t i_stri, uint64_t d_i_stri, uint64_t d_j_stri, int64_t *ids, double *mins, double *maxs); + +SIDX_DLL void Index_Destroy(IndexH index); +SIDX_DLL IndexPropertyH Index_GetProperties(IndexH index); + +SIDX_DLL RTError Index_DeleteData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + uint32_t nDimension); + +SIDX_C_DLL RTError Index_DeleteTPData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension + ); + +SIDX_C_DLL RTError Index_DeleteMVRData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension + ); + +SIDX_DLL RTError Index_InsertData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + uint32_t nDimension, + const uint8_t* pData, + size_t nDataLength); + +SIDX_C_DLL RTError Index_InsertTPData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + const uint8_t* pData, + size_t nDataLength); + +SIDX_C_DLL RTError Index_InsertMVRData( IndexH index, + int64_t id, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + const uint8_t* pData, + size_t nDataLength); + +SIDX_DLL uint32_t Index_IsValid(IndexH index); + +SIDX_C_DLL RTError Index_TPIntersects_obj( IndexH index, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_MVRIntersects_obj( IndexH index, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_DLL RTError Index_Intersects_obj( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_Contains_obj( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_TPIntersects_id( IndexH index, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + int64_t** ids, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_MVRIntersects_id( IndexH index, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + int64_t** ids, + uint64_t* nResults); + +SIDX_DLL RTError Index_Intersects_id( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + int64_t** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_Intersects_id_v(IndexH index, + int64_t n, + uint32_t d, + uint64_t idsz, + uint64_t d_i_stri, + uint64_t d_j_stri, + const double* mins, + const double* maxs, + int64_t* ids, + uint64_t* cnts, + int64_t* nr); + +SIDX_C_DLL RTError Index_Contains_id(IndexH index, + double *pdMin, + double *pdMax, + uint32_t nDimension, + int64_t **ids, + uint64_t *nResults); + +SIDX_C_DLL RTError Index_TPIntersects_count( IndexH index, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_MVRIntersects_count( IndexH index, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + uint64_t* nResults); + +SIDX_DLL RTError Index_Intersects_count( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_Contains_count( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_TPNearestNeighbors_obj(IndexH index, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_MVRNearestNeighbors_obj(IndexH index, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_DLL RTError Index_NearestNeighbors_obj(IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_TPNearestNeighbors_id(IndexH index, + double* pdMin, + double* pdMax, + double* pdVMin, + double* pdVMax, + double tStart, + double tEnd, + uint32_t nDimension, + int64_t** ids, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_MVRNearestNeighbors_id(IndexH index, + double* pdMin, + double* pdMax, + double tStart, + double tEnd, + uint32_t nDimension, + int64_t** ids, + uint64_t* nResults); + +SIDX_DLL RTError Index_NearestNeighbors_id( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + int64_t** items, + uint64_t* nResults); + +SIDX_C_DLL RTError Index_NearestNeighbors_id_v(IndexH index, + int64_t knn, + int64_t n, + uint32_t d, + uint64_t idsz, + uint64_t d_i_stri, + uint64_t d_j_stri, + const double* mins, + const double* maxs, + int64_t* ids, + uint64_t* cnts, + double* dists, + int64_t* nr); + +SIDX_DLL RTError Index_Intersects_internal( IndexH index, + double* pdMin, + double* pdMax, + uint32_t nDimension, + IndexItemH** items, + uint64_t* nResults); + +SIDX_DLL RTError Index_GetBounds( IndexH index, + double** ppdMin, + double** ppdMax, + uint32_t* nDimension); + + +SIDX_C_DLL RTError Index_GetLeaves( IndexH index, + uint32_t* nLeafNodes, + uint32_t** nLeafSizes, + int64_t** nLeafIDs, + int64_t*** nLeafChildIDs, + double*** pppdMin, + double*** pppdMax, + uint32_t* nDimension); + +SIDX_DLL RTError Index_SetResultSetOffset(IndexH index, int64_t value); +SIDX_DLL int64_t Index_GetResultSetOffset(IndexH index); + +SIDX_DLL RTError Index_SetResultSetLimit(IndexH index, int64_t value); +SIDX_DLL int64_t Index_GetResultSetLimit(IndexH index); + +SIDX_DLL void Index_DestroyObjResults(IndexItemH* results, uint32_t nResults); +SIDX_DLL void Index_ClearBuffer(IndexH index); +SIDX_DLL void Index_Free(void* object); +SIDX_DLL void Index_Flush(IndexH index); + +SIDX_DLL void IndexItem_Destroy(IndexItemH item); +SIDX_DLL int64_t IndexItem_GetID(IndexItemH item); + +SIDX_DLL RTError IndexItem_GetData(IndexItemH item, uint8_t** data, uint64_t* length); + +SIDX_DLL RTError IndexItem_GetBounds( IndexItemH item, + double** ppdMin, + double** ppdMax, + uint32_t* nDimension); + +SIDX_DLL IndexPropertyH IndexProperty_Create(void); +SIDX_DLL void IndexProperty_Destroy(IndexPropertyH hProp); + +SIDX_DLL RTError IndexProperty_SetIndexType(IndexPropertyH iprop, RTIndexType value); +SIDX_DLL RTIndexType IndexProperty_GetIndexType(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetDimension(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetDimension(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetIndexVariant(IndexPropertyH iprop, RTIndexVariant value); +SIDX_DLL RTIndexVariant IndexProperty_GetIndexVariant(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetIndexStorage(IndexPropertyH iprop, RTStorageType value); +SIDX_DLL RTStorageType IndexProperty_GetIndexStorage(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetPagesize(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetPagesize(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetIndexCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetIndexCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetLeafCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetLeafCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetLeafPoolCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetLeafPoolCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetIndexPoolCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetIndexPoolCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetRegionPoolCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetRegionPoolCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetPointPoolCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetPointPoolCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetBufferingCapacity(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetBufferingCapacity(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetEnsureTightMBRs(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetEnsureTightMBRs(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetOverwrite(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetOverwrite(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetNearMinimumOverlapFactor(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetNearMinimumOverlapFactor(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetWriteThrough(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetWriteThrough(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetFillFactor(IndexPropertyH iprop, double value); +SIDX_DLL double IndexProperty_GetFillFactor(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetSplitDistributionFactor(IndexPropertyH iprop, double value); +SIDX_DLL double IndexProperty_GetSplitDistributionFactor(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetTPRHorizon(IndexPropertyH iprop, double value); +SIDX_DLL double IndexProperty_GetTPRHorizon(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetReinsertFactor(IndexPropertyH iprop, double value); +SIDX_DLL double IndexProperty_GetReinsertFactor(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetFileName(IndexPropertyH iprop, const char* value); +SIDX_DLL char* IndexProperty_GetFileName(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetFileNameExtensionDat(IndexPropertyH iprop, const char* value); +SIDX_DLL char* IndexProperty_GetFileNameExtensionDat(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetFileNameExtensionIdx(IndexPropertyH iprop, const char* value); +SIDX_DLL char* IndexProperty_GetFileNameExtensionIdx(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetCustomStorageCallbacksSize(IndexPropertyH iprop, uint32_t value); +SIDX_DLL uint32_t IndexProperty_GetCustomStorageCallbacksSize(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetCustomStorageCallbacks(IndexPropertyH iprop, const void* value); +SIDX_DLL void* IndexProperty_GetCustomStorageCallbacks(IndexPropertyH iprop); + +SIDX_DLL RTError IndexProperty_SetIndexID(IndexPropertyH iprop, int64_t value); +SIDX_DLL int64_t IndexProperty_GetIndexID(IndexPropertyH iprop); + +SIDX_C_DLL void* SIDX_NewBuffer(size_t bytes); +SIDX_C_DLL void SIDX_DeleteBuffer(void* buffer); + +SIDX_DLL RTError IndexProperty_SetResultSetLimit(IndexPropertyH iprop, uint64_t value); +SIDX_DLL uint64_t IndexProperty_GetResultSetLimit(IndexPropertyH iprop); + +SIDX_C_DLL char* SIDX_Version(void); + +SIDX_C_DLL char* Error_GetLastErrorMsg(void); + +IDX_C_END + +#endif diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_config.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_config.h new file mode 100644 index 0000000000000000000000000000000000000000..153e2ea5f9847a3137cf26c9810d475b17eeee7f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_config.h @@ -0,0 +1,112 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C API configuration + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#ifndef SIDX_CONFIG_H_INCLUDED +#define SIDX_CONFIG_H_INCLUDED + + + +#ifdef _MSC_VER + +#if _MSC_VER <= 1500 + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; +#else + #include +#endif + + #include + #define STRDUP _strdup + #include + +#else + + #include + #define SIDX_THREAD __thread + #define STRDUP strdup +#endif + +#include + +#include "sidx_export.h" + +typedef enum +{ + RT_None = 0, + RT_Debug = 1, + RT_Warning = 2, + RT_Failure = 3, + RT_Fatal = 4 +} RTError; + +typedef enum +{ + RT_RTree = 0, + RT_MVRTree = 1, + RT_TPRTree = 2, + RT_InvalidIndexType = -99 +} RTIndexType; + +typedef enum +{ + RT_Memory = 0, + RT_Disk = 1, + RT_Custom = 2, + RT_InvalidStorageType = -99 +} RTStorageType; + +typedef enum +{ + RT_Linear = 0, + RT_Quadratic = 1, + RT_Star = 2, + RT_InvalidIndexVariant = -99 +} RTIndexVariant; + + +#ifdef __cplusplus +# define IDX_C_START extern "C" { +# define IDX_C_END } +#else +# define IDX_C_START +# define IDX_C_END +#endif + +typedef struct IndexS *IndexH; +typedef struct SpatialIndex_IData *IndexItemH; +typedef struct Tools_PropertySet *IndexPropertyH; + + + +#endif diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_export.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_export.h new file mode 100644 index 0000000000000000000000000000000000000000..7b0a393647e32e49e8b70eaaaf8afd8a5f0e449d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_export.h @@ -0,0 +1,44 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement utilities. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2014, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#ifndef SIDX_C_DLL +#if defined(_MSC_VER) && defined(SIDX_DLL_EXPORT) +# define SIDX_C_DLL __declspec(dllexport) +# define SIDX_DLL __declspec(dllexport) +#else +# if defined(USE_GCC_VISIBILITY_FLAG) +# define SIDX_C_DLL __attribute__ ((visibility("default"))) +# define SIDX_DLL __attribute__ ((visibility("default"))) +# else +# define SIDX_C_DLL +# define SIDX_DLL +# endif +#endif +#endif diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_impl.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..df665b9fb6c09424f2b0b2258e317535c4299dd0 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/capi/sidx_impl.h @@ -0,0 +1,47 @@ +/****************************************************************************** + * Project: libsidx - A C API wrapper around libspatialindex + * Purpose: C++ object declarations to implement utilities. + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2009, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#include +#include +#include +#include +#include +#include + +#include "../SpatialIndex.h" +#include "sidx_config.h" +#include "Utility.h" +#include "ObjVisitor.h" +#include "IdVisitor.h" +#include "CountVisitor.h" +#include "BoundsQuery.h" +#include "LeafQuery.h" +#include "Error.h" +#include "DataStream.h" +#include "Index.h" +#include "CustomStorage.h" diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PointerPool.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PointerPool.h new file mode 100644 index 0000000000000000000000000000000000000000..4611122d34e0e1a9b34c735abbfaf44f85178ee4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PointerPool.h @@ -0,0 +1,95 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "PoolPointer.h" + +namespace Tools +{ + template class PointerPool + { + public: + explicit PointerPool(uint32_t capacity) : m_capacity(capacity) + { + } + + ~PointerPool() + { + assert(m_pool.size() <= m_capacity); + + while (! m_pool.empty()) + { + X* x = m_pool.top(); m_pool.pop(); + delete x; + } + } + + PoolPointer acquire() + { + X* p = nullptr; + + if (! m_pool.empty()) + { + p = m_pool.top(); m_pool.pop(); + } + else + { + p = new X(); + } + + return PoolPointer(p, this); + } + + void release(X* p) + { + if (m_pool.size() < m_capacity) + { + m_pool.push(p); + } + else + { + delete p; + } + + assert(m_pool.size() <= m_capacity); + } + + uint32_t getCapacity() const { return m_capacity; } + void setCapacity(uint32_t c) + { + assert (c >= 0); + m_capacity = c; + } + + private: + uint32_t m_capacity; + std::stack m_pool; + + }; +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PoolPointer.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PoolPointer.h new file mode 100644 index 0000000000000000000000000000000000000000..7597017599c4c086c2ff81c5440dc84a767ea1c9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/PoolPointer.h @@ -0,0 +1,102 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + +#include "PointerPool.h" + +namespace Tools +{ + template class PointerPool; + + template class PoolPointer + { + public: + explicit PoolPointer(X* p = nullptr) : m_pointer(p), m_pPool(nullptr) { m_prev = m_next = this; } + explicit PoolPointer(X* p, PointerPool* pPool) noexcept : m_pointer(p), m_pPool(pPool) { m_prev = m_next = this; } + ~PoolPointer() { release(); } + PoolPointer(const PoolPointer& p) noexcept { acquire(p); } + PoolPointer& operator=(const PoolPointer& p) + { + if (this != &p) + { + release(); + acquire(p); + } + return *this; + } + + X& operator*() const noexcept { return *m_pointer; } + X* operator->() const noexcept { return m_pointer; } + X* get() const noexcept { return m_pointer; } + bool unique() const noexcept { return m_prev ? m_prev == this : true; } + void relinquish() noexcept + { + m_pPool = nullptr; + m_pointer = nullptr; + release(); + } + + private: + X* m_pointer; + mutable const PoolPointer* m_prev; + mutable const PoolPointer* m_next; + PointerPool* m_pPool; + + void acquire(const PoolPointer& p) noexcept + { + m_pPool = p.m_pPool; + m_pointer = p.m_pointer; + m_next = p.m_next; + m_next->m_prev = this; + m_prev = &p; + #ifndef mutable + p.m_next = this; + #else + (const_cast*>(&p))->m_next = this; + #endif + } + + void release() + { + if (unique()) + { + if (m_pPool != nullptr) m_pPool->release(m_pointer); + else delete m_pointer; + } + else + { + m_prev->m_next = m_next; + m_next->m_prev = m_prev; + m_prev = m_next = nullptr; + } + m_pointer = nullptr; + m_pPool = nullptr; + } + }; +} + diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/Tools.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/Tools.h new file mode 100644 index 0000000000000000000000000000000000000000..07c1926e8c15a33cb5cb2b8c744f963804feb183 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/Tools.h @@ -0,0 +1,501 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Marios Hadjieleftheriou, mhadji@gmail.com + ****************************************************************************** + * Copyright (c) 2004, Marios Hadjieleftheriou + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + +#pragma once + + +#if (defined _WIN32 || defined _WIN64 || defined WIN32 || defined WIN64) && (defined _MSC_VER) && (_MSC_VER < 1900) && !defined __GNUC__ + typedef __int8 int8_t; + typedef __int16 int16_t; + typedef __int32 int32_t; + typedef __int64 int64_t; + typedef unsigned __int8 uint8_t; + typedef unsigned __int16 uint16_t; + typedef unsigned __int32 uint32_t; + typedef unsigned __int64 uint64_t; + +#else + #include +#endif + +#if (defined _WIN32 || defined _WIN64 || defined WIN32 || defined WIN64) && !defined __GNUC__ + #ifdef SIDX_DLL_EXPORT + #define SIDX_DLL __declspec(dllexport) + #else + #define SIDX_DLL + #endif + + // Nuke this annoying warning. See http://www.unknownroad.com/rtfm/VisualStudio/warningC4251.html +#pragma warning( disable: 4251 ) + +#else + #define SIDX_DLL +#endif + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "PointerPool.h" +#include "PoolPointer.h" + +namespace Tools +{ + enum IntervalType + { + IT_RIGHTOPEN = 0x0, + IT_LEFTOPEN, + IT_OPEN, + IT_CLOSED + }; + + enum VariantType + { + VT_LONG = 0x0, + VT_BYTE, + VT_SHORT, + VT_FLOAT, + VT_DOUBLE, + VT_CHAR, + VT_USHORT, + VT_ULONG, + VT_INT, + VT_UINT, + VT_BOOL, + VT_PCHAR, + VT_PVOID, + VT_EMPTY, + VT_LONGLONG, + VT_ULONGLONG, + VT_PWCHAR + }; + + enum FileMode + { + APPEND = 0x0, + CREATE + }; + + // + // Exceptions + // + class SIDX_DLL Exception + { + public: + virtual std::string what() = 0; + virtual ~Exception() = default; + }; + + class SIDX_DLL IndexOutOfBoundsException : public Exception + { + public: + IndexOutOfBoundsException(size_t i); + ~IndexOutOfBoundsException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // IndexOutOfBoundsException + + class SIDX_DLL IllegalArgumentException : public Exception + { + public: + IllegalArgumentException(std::string s); + ~IllegalArgumentException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // IllegalArgumentException + + class SIDX_DLL IllegalStateException : public Exception + { + public: + IllegalStateException(std::string s); + ~IllegalStateException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // IllegalStateException + + class SIDX_DLL EndOfStreamException : public Exception + { + public: + EndOfStreamException(std::string s); + ~EndOfStreamException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // EndOfStreamException + + class SIDX_DLL ResourceLockedException : public Exception + { + public: + ResourceLockedException(std::string s); + ~ResourceLockedException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // ResourceLockedException + + class SIDX_DLL NotSupportedException : public Exception + { + public: + NotSupportedException(std::string s); + ~NotSupportedException() override = default; + std::string what() override; + + private: + std::string m_error; + }; // NotSupportedException + + // + // Interfaces + // + class SIDX_DLL IInterval + { + public: + virtual ~IInterval() = default; + + virtual double getLowerBound() const = 0; + virtual double getUpperBound() const = 0; + virtual void setBounds(double, double) = 0; + virtual bool intersectsInterval(const IInterval&) const = 0; + virtual bool intersectsInterval(IntervalType type, const double start, const double end) const = 0; + virtual bool containsInterval(const IInterval&) const = 0; + virtual IntervalType getIntervalType() const = 0; + }; // IInterval + + class SIDX_DLL IObject + { + public: + virtual ~IObject() = default; + + virtual IObject* clone() = 0; + // return a new object that is an exact copy of this one. + // IMPORTANT: do not return the this pointer! + }; // IObject + + class SIDX_DLL ISerializable + { + public: + virtual ~ISerializable() = default; + + virtual uint32_t getByteArraySize() = 0; + // returns the size of the required uint8_t array. + virtual void loadFromByteArray(const uint8_t* data) = 0; + // load this object using the uint8_t array. + virtual void storeToByteArray(uint8_t** data, uint32_t& length) = 0; + // store this object in the uint8_t array. + }; + + class SIDX_DLL IComparable + { + public: + virtual ~IComparable() = default; + + virtual bool operator<(const IComparable& o) const = 0; + virtual bool operator>(const IComparable& o) const = 0; + virtual bool operator==(const IComparable& o) const = 0; + }; //IComparable + + class SIDX_DLL IObjectComparator + { + public: + virtual ~IObjectComparator() = default; + + virtual int compare(IObject* o1, IObject* o2) = 0; + }; // IObjectComparator + + class SIDX_DLL IObjectStream + { + public: + virtual ~IObjectStream() = default; + + virtual IObject* getNext() = 0; + // returns a pointer to the next entry in the + // stream or 0 at the end of the stream. + + virtual bool hasNext() = 0; + // returns true if there are more items in the stream. + + virtual uint32_t size() = 0; + // returns the total number of entries available in the stream. + + virtual void rewind() = 0; + // sets the stream pointer to the first entry, if possible. + }; // IObjectStream + + // + // Classes & Functions + // + + class SIDX_DLL Variant + { + public: + Variant(); + + VariantType m_varType{VT_EMPTY}; + + union + { + int16_t iVal; // VT_SHORT + int32_t lVal; // VT_LONG + int64_t llVal; // VT_LONGLONG + uint8_t bVal; // VT_BYTE + float fltVal; // VT_FLOAT + double dblVal; // VT_DOUBLE + char cVal; // VT_CHAR + uint16_t uiVal; // VT_USHORT + uint32_t ulVal; // VT_ULONG + uint64_t ullVal; // VT_ULONGLONG + bool blVal; // VT_BOOL + char* pcVal; // VT_PCHAR + void* pvVal; // VT_PVOID + wchar_t* pwcVal; + } m_val; + }; // Variant + + class SIDX_DLL PropertySet; + SIDX_DLL std::ostream& operator<<(std::ostream& os, const Tools::PropertySet& p); + + class SIDX_DLL PropertySet : public ISerializable + { + public: + PropertySet(); + PropertySet(const uint8_t* data); + ~PropertySet() override; + + Variant getProperty(std::string property) const; + void setProperty(std::string property, Variant const& v); + void removeProperty(std::string property); + + uint32_t getByteArraySize() override; + void loadFromByteArray(const uint8_t* data) override; + void storeToByteArray(uint8_t** data, uint32_t& length) override; + + private: + std::map m_propertySet; +// #ifdef HAVE_PTHREAD_H +// pthread_rwlock_t m_rwLock; +// #else +// bool m_rwLock; +// #endif + friend SIDX_DLL std::ostream& operator<<(std::ostream& os, const Tools::PropertySet& p); + }; // PropertySet + + // does not support degenerate intervals. + class SIDX_DLL Interval : public IInterval + { + public: + Interval(); + Interval(IntervalType, double, double); + Interval(double, double); + Interval(const Interval&); + ~Interval() override = default; + virtual IInterval& operator=(const IInterval&); + + virtual bool operator==(const Interval&) const; + virtual bool operator!=(const Interval&) const; + double getLowerBound() const override; + double getUpperBound() const override; + void setBounds(double, double) override; + bool intersectsInterval(const IInterval&) const override; + bool intersectsInterval(IntervalType type, const double start, const double end) const override; + bool containsInterval(const IInterval&) const override; + IntervalType getIntervalType() const override; + + IntervalType m_type{IT_RIGHTOPEN}; + double m_low{0.0}; + double m_high{0.0}; + }; // Interval + + SIDX_DLL std::ostream& operator<<(std::ostream& os, const Tools::Interval& iv); + + class SIDX_DLL Random + { + public: + Random(); + Random(uint32_t seed, uint16_t xsubi0); + virtual ~Random(); + + int32_t nextUniformLong(); + // returns a uniformly distributed long. + uint32_t nextUniformUnsignedLong(); + // returns a uniformly distributed unsigned long. + int32_t nextUniformLong(int32_t low, int32_t high); + // returns a uniformly distributed long in the range [low, high). + uint32_t nextUniformUnsignedLong(uint32_t low, uint32_t high); + // returns a uniformly distributed unsigned long in the range [low, high). + int64_t nextUniformLongLong(); + // returns a uniformly distributed long long. + uint64_t nextUniformUnsignedLongLong(); + // returns a uniformly distributed unsigned long long. + int64_t nextUniformLongLong(int64_t low, int64_t high); + // returns a uniformly distributed unsigned long long in the range [low, high). + uint64_t nextUniformUnsignedLongLong(uint64_t low, uint64_t high); + // returns a uniformly distributed unsigned long long in the range [low, high). + int16_t nextUniformShort(); + // returns a uniformly distributed short. + uint16_t nextUniformUnsignedShort(); + // returns a uniformly distributed unsigned short. + double nextUniformDouble(); + // returns a uniformly distributed double in the range [0, 1). + double nextUniformDouble(double low, double high); + // returns a uniformly distributed double in the range [low, high). + + bool flipCoin(); + + private: + void initDrand(uint32_t seed, uint16_t xsubi0); + + uint16_t* m_pBuffer; + }; // Random + + #if HAVE_PTHREAD_H + class SIDX_DLL LockGuard + { + public: + LockGuard(pthread_mutex_t* pLock); + ~LockGuard(); + + private: + pthread_mutex_t* m_pLock; + }; // LockGuard + #endif + + class SIDX_DLL BufferedFile + { + public: + BufferedFile(uint32_t u32BufferSize = 16384); + virtual ~BufferedFile(); + + virtual void close(); + virtual bool eof(); + virtual void rewind() = 0; + virtual void seek(std::fstream::off_type offset) = 0; + + protected: + std::fstream m_file; + char* m_buffer; + uint32_t m_u32BufferSize; + bool m_bEOF{true}; + }; + + class SIDX_DLL BufferedFileReader : public BufferedFile + { + public: + BufferedFileReader(); + BufferedFileReader(const std::string& sFileName, uint32_t u32BufferSize = 32768); + ~BufferedFileReader() override; + + virtual void open(const std::string& sFileName); + void rewind() override; + void seek(std::fstream::off_type offset) override; + + virtual uint8_t readUInt8(); + virtual uint16_t readUInt16(); + virtual uint32_t readUInt32(); + virtual uint64_t readUInt64(); + virtual float readFloat(); + virtual double readDouble(); + virtual bool readBoolean(); + virtual std::string readString(); + virtual void readBytes(uint32_t u32Len, uint8_t** pData); + }; + + class SIDX_DLL BufferedFileWriter : public BufferedFile + { + public: + BufferedFileWriter(); + BufferedFileWriter(const std::string& sFileName, FileMode mode = CREATE, uint32_t u32BufferSize = 32768); + ~BufferedFileWriter() override; + + virtual void open(const std::string& sFileName, FileMode mode = CREATE); + void rewind() override; + void seek(std::fstream::off_type offset) override; + + virtual void write(uint8_t i); + virtual void write(uint16_t i); + virtual void write(uint32_t i); + virtual void write(uint64_t i); + virtual void write(float i); + virtual void write(double i); + virtual void write(bool b); + virtual void write(const std::string& s); + virtual void write(uint32_t u32Len, uint8_t* pData); + }; + + class SIDX_DLL TemporaryFile + { + public: + TemporaryFile(); + virtual ~TemporaryFile(); + + void rewindForReading(); + void rewindForWriting(); + bool eof(); + std::string getFileName() const; + + uint8_t readUInt8(); + uint16_t readUInt16(); + uint32_t readUInt32(); + uint64_t readUInt64(); + float readFloat(); + double readDouble(); + std::string readString(); + void readBytes(uint32_t u32Len, uint8_t** pData); + + void write(uint8_t i); + void write(uint16_t i); + void write(uint32_t i); + void write(uint64_t i); + void write(float i); + void write(double i); + void write(const std::string& s); + void write(uint32_t u32Len, uint8_t* pData); + + private: + std::string m_sFile; + BufferedFile* m_pFile; + }; +} diff --git a/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/rand48.h b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/rand48.h new file mode 100644 index 0000000000000000000000000000000000000000..46ff3226a0b77ac6adf2e7e6733d0797dc1a0cb4 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/rtree/include/spatialindex/tools/rand48.h @@ -0,0 +1,89 @@ +/****************************************************************************** + * Project: libspatialindex - A C++ library for spatial indexing + * Author: Howard Butler, hobu.inc@gmail.com + ****************************************************************************** + * Copyright (c) 2011, Howard Butler + * + * All rights reserved. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the "Software"), + * to deal in the Software without restriction, including without limitation + * the rights to use, copy, modify, merge, publish, distribute, sublicense, + * and/or sell copies of the Software, and to permit persons to whom the + * Software is furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL + * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER + * DEALINGS IN THE SOFTWARE. +******************************************************************************/ + + +#pragma once + +/* Only define this stuff if we're not ANDROID */ +#ifndef ANDROID + +#ifndef HAVE_SRAND48 + +#if HAVE_FEATURES_H +#include +#ifndef __THROW +/* copy-pasted from sys/cdefs.h */ +/* GCC can always grok prototypes. For C++ programs we add throw() +to help it optimize the function calls. But this works only with +gcc 2.8.x and egcs. For gcc 3.2 and up we even mark C functions +as non-throwing using a function attribute since programs can use +the -fexceptions options for C code as well. */ +# if !defined __cplusplus && __GNUC_PREREQ (3, 3) +# define __THROW __attribute__ ((__nothrow__)) +# define __NTH(fct) __attribute__ ((__nothrow__)) fct +# else +# if defined __cplusplus && __GNUC_PREREQ (2,8) +# define __THROW throw () +# define __NTH(fct) fct throw () +# else +# define __THROW +# define __NTH(fct) fct +# endif +# endif +#endif +#endif + +#ifndef __THROW +# define __THROW +#endif + +#ifndef __NTH +# define __NTH(fct) fct +#endif + +extern void srand48(long int seed) __THROW; + +extern unsigned short *seed48(unsigned short xseed[3]) __THROW; + +extern long nrand48(unsigned short xseed[3]) __THROW; + +extern long mrand48(void) __THROW; + +extern long lrand48(void) __THROW; + +extern void lcong48(unsigned short p[7]) __THROW; + +extern long jrand48(unsigned short xseed[3]) __THROW; + +extern double erand48(unsigned short xseed[3]) __THROW; + +extern double drand48(void) __THROW; + +#endif + +/* Only define this stuff if we're not ANDROID */ +#endif diff --git a/data/miniconda3/lib/python3.13/site-packages/secretstorage-3.4.0.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/secretstorage-3.4.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a343a622c0fbd345079ec24bae6eadb29a00b978 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/secretstorage-3.4.0.dist-info/licenses/LICENSE @@ -0,0 +1,25 @@ +Copyright 2012-2018 Dmitry Shachnev +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. +3. Neither the name of the University nor the names of its contributors may be + used to endorse or promote products derived from this software without + specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY +DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON +ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/data/miniconda3/lib/python3.13/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..7a4a3ea2424c09fbe48d455aed1eaa94d9124835 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/tenacity-9.1.4.dist-info/licenses/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e960fe2655bfd4a1ad0154a5c130996edd48cd7b Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_parser.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_parser.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b8bbd6311fdd533aad31087d2f0d7bde23958e34 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_parser.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_re.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_re.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4752e32adfaab3b02b88d9a566ab2457817e35e9 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_re.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_types.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_types.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f2e1621e8561750ee1759189be48514fb30a155c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/tomli/__pycache__/_types.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/typer-0.20.0.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/typer-0.20.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/typer-0.20.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/typer_slim-0.20.0.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/typer_slim-0.20.0.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a7694736cf37716aafec14b24aa8d6316ebe07a3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/typer_slim-0.20.0.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2019 Sebastián Ramírez + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE b/data/miniconda3/lib/python3.13/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..e825ad51621c5e34d370ba64f13f6854d89456a6 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/typing_inspection-0.4.2.dist-info/licenses/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pydantic Services Inc. 2025 to present + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f349f1ce8298554686a89bdbe094934f3121e40a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..50807685d37b5a4af2ed686eecb258920fbff83a Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/introspection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8a19adcee725357a4a252debb05f56b824db5d3d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/typing_inspection/__pycache__/typing_objects.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..46ba584ec7d209469464fd26a64ef310312c221f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__main__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__main__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..815ce8cb287170178433e3333c544bcb3a57da45 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/__main__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/auth.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d00aa804b6bc3d8f036138ec6e1ec62af40cdb90 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/auth.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/cli.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/cli.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae6d25a1aa4328293bab19e58d713e8f61650c89 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/cli.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0afcf0531ae31ad6d72af4dada65a42a4952d43f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/connection.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e26b0313fa35fad1466c9cdb76e01ba3be6255a0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/connection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/datastructures.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/datastructures.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f23e9bb437252be45048cc6dce0194460baf8b35 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/datastructures.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7bb5f8bd351b899e3a9aa831f3ce272fe6a75c8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/frames.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/frames.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3271433d3e5663854a91b52d5be79c2285bc5ab Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/frames.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/headers.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/headers.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5479fa883300fb1dd57a5a53deba8b79366a2b85 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/headers.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e52449f0ac2d8b69e00b1d7944adf7a44f5098d7 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http11.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http11.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..09a6481c9e7ff0b048654b081a5c308c7cb1c89e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/http11.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/imports.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/imports.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..88a75437fc68ceade74ac740317bbfb9db27305c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/imports.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/protocol.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/protocol.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b15ac8657f0902627202ecaefea0cb2a3083fded Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/protocol.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/proxy.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/proxy.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f5fb9fffc5c922ae580454a9539204fc6ced184c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/proxy.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/server.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bb8bd9334b35579638ceb57c5999674b1cc6c4c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/server.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/streams.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/streams.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..da50c9266d5fafd0562ab67ba7cb9036d5c57929 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/streams.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/typing.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/typing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6cfcde9f0ec9e81b11bc7951c3eaa23e8a0f312 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/typing.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/uri.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/uri.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8b3aee73340dcfdbe9d52d407dde556dcdd63a74 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/uri.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4e547acbef7871abe212c87b452f2358508d6062 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/version.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/version.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d45054e7d52048ec22ce71f019ae37f25d1c1341 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/__pycache__/version.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__init__.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..421ca83a653365534e40b6e0c148dec691f74aca Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a0da7878bad6507620585348a6affbc5a884a11c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/async_timeout.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c18599209d43a0fe054857fbbe7a16b54afc16f Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..665130aa8ffd4f0eaf107b2082051b600b7bb201 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/compatibility.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/connection.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c1367e5da7a38283c41e2dad176f1bb42a240b11 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/connection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/messages.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/messages.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..de22068c65eb2486d6c841bdb725e10ffc094fc0 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/messages.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/router.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/router.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..11bce54a161bd9791ce811c2d12e69fe5d95b6c6 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/router.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/server.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bd000961c90b90f42dc4d29f76207ee34906a216 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/__pycache__/server.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/async_timeout.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/async_timeout.py new file mode 100644 index 0000000000000000000000000000000000000000..6ffa899695637829dd5d3c7b58c68683000fc35d --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/async_timeout.py @@ -0,0 +1,282 @@ +# From https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py +# Licensed under the Apache License (Apache-2.0) + +import asyncio +import enum +import sys +import warnings +from types import TracebackType +from typing import Optional, Type + + +if sys.version_info >= (3, 11): + from typing import final +else: + # From https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + # Licensed under the Python Software Foundation License (PSF-2.0) + + # @final exists in 3.8+, but we backport it for all versions + # before 3.11 to keep support for the __final__ attribute. + # See https://bugs.python.org/issue46342 + def final(f): + """This decorator can be used to indicate to type checkers that + the decorated method cannot be overridden, and decorated class + cannot be subclassed. For example: + + class Base: + @final + def done(self) -> None: + ... + class Sub(Base): + def done(self) -> None: # Error reported by type checker + ... + @final + class Leaf: + ... + class Other(Leaf): # Error reported by type checker + ... + + There is no runtime checking of these properties. The decorator + sets the ``__final__`` attribute to ``True`` on the decorated object + to allow runtime introspection. + """ + try: + f.__final__ = True + except (AttributeError, TypeError): + # Skip the attribute silently if it is not writable. + # AttributeError happens if the object has __slots__ or a + # read-only property, TypeError if it's a builtin class. + pass + return f + + # End https://github.com/python/typing_extensions/blob/main/src/typing_extensions.py + + +if sys.version_info >= (3, 11): + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + task.uncancel() + +else: + + def _uncancel_task(task: "asyncio.Task[object]") -> None: + pass + + +__version__ = "4.0.3" + + +__all__ = ("timeout", "timeout_at", "Timeout") + + +def timeout(delay: Optional[float]) -> "Timeout": + """timeout context manager. + + Useful in cases when you want to apply timeout logic around block + of code or in cases when asyncio.wait_for is not suitable. For example: + + >>> async with timeout(0.001): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + delay - value in seconds or None to disable timeout logic + """ + loop = asyncio.get_running_loop() + if delay is not None: + deadline = loop.time() + delay # type: Optional[float] + else: + deadline = None + return Timeout(deadline, loop) + + +def timeout_at(deadline: Optional[float]) -> "Timeout": + """Schedule the timeout at absolute time. + + deadline argument points on the time in the same clock system + as loop.time(). + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + + >>> async with timeout_at(loop.time() + 10): + ... async with aiohttp.get('https://github.com') as r: + ... await r.text() + + + """ + loop = asyncio.get_running_loop() + return Timeout(deadline, loop) + + +class _State(enum.Enum): + INIT = "INIT" + ENTER = "ENTER" + TIMEOUT = "TIMEOUT" + EXIT = "EXIT" + + +@final +class Timeout: + # Internal class, please don't instantiate it directly + # Use timeout() and timeout_at() public factories instead. + # + # Implementation note: `async with timeout()` is preferred + # over `with timeout()`. + # While technically the Timeout class implementation + # doesn't need to be async at all, + # the `async with` statement explicitly points that + # the context manager should be used from async function context. + # + # This design allows to avoid many silly misusages. + # + # TimeoutError is raised immediately when scheduled + # if the deadline is passed. + # The purpose is to time out as soon as possible + # without waiting for the next await expression. + + __slots__ = ("_deadline", "_loop", "_state", "_timeout_handler", "_task") + + def __init__( + self, deadline: Optional[float], loop: asyncio.AbstractEventLoop + ) -> None: + self._loop = loop + self._state = _State.INIT + + self._task: Optional["asyncio.Task[object]"] = None + self._timeout_handler = None # type: Optional[asyncio.Handle] + if deadline is None: + self._deadline = None # type: Optional[float] + else: + self.update(deadline) + + def __enter__(self) -> "Timeout": + warnings.warn( + "with timeout() is deprecated, use async with timeout() instead", + DeprecationWarning, + stacklevel=2, + ) + self._do_enter() + return self + + def __exit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + async def __aenter__(self) -> "Timeout": + self._do_enter() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]], + exc_val: Optional[BaseException], + exc_tb: Optional[TracebackType], + ) -> Optional[bool]: + self._do_exit(exc_type) + return None + + @property + def expired(self) -> bool: + """Is timeout expired during execution?""" + return self._state == _State.TIMEOUT + + @property + def deadline(self) -> Optional[float]: + return self._deadline + + def reject(self) -> None: + """Reject scheduled timeout if any.""" + # cancel is maybe better name but + # task.cancel() raises CancelledError in asyncio world. + if self._state not in (_State.INIT, _State.ENTER): + raise RuntimeError(f"invalid state {self._state.value}") + self._reject() + + def _reject(self) -> None: + self._task = None + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._timeout_handler = None + + def shift(self, delay: float) -> None: + """Advance timeout on delay seconds. + + The delay can be negative. + + Raise RuntimeError if shift is called when deadline is not scheduled + """ + deadline = self._deadline + if deadline is None: + raise RuntimeError("cannot shift timeout if deadline is not scheduled") + self.update(deadline + delay) + + def update(self, deadline: float) -> None: + """Set deadline to absolute value. + + deadline argument points on the time in the same clock system + as loop.time(). + + If new deadline is in the past the timeout is raised immediately. + + Please note: it is not POSIX time but a time with + undefined starting base, e.g. the time of the system power on. + """ + if self._state == _State.EXIT: + raise RuntimeError("cannot reschedule after exit from context manager") + if self._state == _State.TIMEOUT: + raise RuntimeError("cannot reschedule expired timeout") + if self._timeout_handler is not None: + self._timeout_handler.cancel() + self._deadline = deadline + if self._state != _State.INIT: + self._reschedule() + + def _reschedule(self) -> None: + assert self._state == _State.ENTER + deadline = self._deadline + if deadline is None: + return + + now = self._loop.time() + if self._timeout_handler is not None: + self._timeout_handler.cancel() + + self._task = asyncio.current_task() + if deadline <= now: + self._timeout_handler = self._loop.call_soon(self._on_timeout) + else: + self._timeout_handler = self._loop.call_at(deadline, self._on_timeout) + + def _do_enter(self) -> None: + if self._state != _State.INIT: + raise RuntimeError(f"invalid state {self._state.value}") + self._state = _State.ENTER + self._reschedule() + + def _do_exit(self, exc_type: Optional[Type[BaseException]]) -> None: + if exc_type is asyncio.CancelledError and self._state == _State.TIMEOUT: + assert self._task is not None + _uncancel_task(self._task) + self._timeout_handler = None + self._task = None + raise asyncio.TimeoutError + # timeout has not expired + self._state = _State.EXIT + self._reject() + return None + + def _on_timeout(self) -> None: + assert self._task is not None + self._task.cancel() + self._state = _State.TIMEOUT + # drop the reference early + self._timeout_handler = None + + +# End https://github.com/aio-libs/async-timeout/blob/master/async_timeout/__init__.py diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/client.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/client.py new file mode 100644 index 0000000000000000000000000000000000000000..05947f3a07e99e3b02fe3e5fe24be3a01bc58092 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/client.py @@ -0,0 +1,804 @@ +from __future__ import annotations + +import asyncio +import logging +import os +import socket +import ssl as ssl_module +import traceback +import urllib.parse +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, Literal, cast + +from ..client import ClientProtocol, backoff +from ..datastructures import HeadersLike +from ..exceptions import ( + InvalidMessage, + InvalidProxyMessage, + InvalidProxyStatus, + InvalidStatus, + ProxyError, + SecurityError, +) +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .compatibility import TimeoutError, asyncio_timeout +from .connection import Connection + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + +MAX_REDIRECTS = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + +class ClientConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` coroutines + for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`connect`. + + Args: + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ClientProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.response_rcvd: asyncio.Future[None] = self.loop.create_future() + + async def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + ) -> None: + """ + Perform the opening handshake. + + """ + async with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + await asyncio.wait( + [self.response_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + +def process_exception(exc: Exception) -> Exception | None: + """ + Determine whether a connection error is retryable or fatal. + + When reconnecting automatically with ``async for ... in connect(...)``, if a + connection attempt fails, :func:`process_exception` is called to determine + whether to retry connecting or to raise the exception. + + This function defines the default behavior, which is to retry on: + + * :exc:`EOFError`, :exc:`OSError`, :exc:`asyncio.TimeoutError`: network + errors; + * :exc:`~websockets.exceptions.InvalidStatus` when the status code is 500, + 502, 503, or 504: server or proxy errors. + + All other exceptions are considered fatal. + + You can change this behavior with the ``process_exception`` argument of + :func:`connect`. + + Return :obj:`None` if the exception is retryable i.e. when the error could + be transient and trying to reconnect with the same parameters could succeed. + The exception will be logged at the ``INFO`` level. + + Return an exception, either ``exc`` or a new exception, if the exception is + fatal i.e. when trying to reconnect will most likely produce the same error. + That exception will be raised, breaking out of the retry loop. + + """ + # This catches python-socks' ProxyConnectionError and ProxyTimeoutError. + # Remove asyncio.TimeoutError when dropping Python < 3.11. + if isinstance(exc, (OSError, TimeoutError, asyncio.TimeoutError)): + return None + if isinstance(exc, InvalidMessage) and isinstance(exc.__cause__, EOFError): + return None + if isinstance(exc, InvalidStatus) and exc.response.status_code in [ + 500, # Internal Server Error + 502, # Bad Gateway + 503, # Service Unavailable + 504, # Gateway Timeout + ]: + return None + return exc + + +# This is spelled in lower case because it's exposed as a callable in the API. +class connect: + """ + Connect to the WebSocket server at ``uri``. + + This coroutine returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as an asynchronous context manager:: + + from websockets.asyncio.client import connect + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + If the connection fails with a transient error, it is retried with + exponential backoff. If it fails with a fatal error, the exception is + raised, breaking out of the loop. + + The connection is closed automatically after each iteration of the loop. + + Args: + uri: URI of the WebSocket server. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + process_exception: When reconnecting automatically, tell whether an + error is transient or fatal. The default behavior is defined by + :func:`process_exception`. Refer to its documentation for details. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS settings. + When connecting to a ``wss://`` URI, if ``ssl`` isn't provided, a TLS + context is created with :func:`~ssl.create_default_context`. + + * You can set ``server_hostname`` to override the host name from ``uri`` in + the TLS handshake. + + * You can set ``host`` and ``port`` to connect to a different host and port + from those found in ``uri``. This only changes the destination of the TCP + connection. The host name from ``uri`` is still used in the TLS handshake + for secure connections and in the ``Host`` header. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_connection` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_connection` method) to create a suitable + client socket and customize it. + + When using a proxy: + + * Prefix keyword arguments with ``proxy_`` for configuring TLS between the + client and an HTTPS proxy: ``proxy_ssl``, ``proxy_server_hostname``, + ``proxy_ssl_handshake_timeout``, and ``proxy_ssl_shutdown_timeout``. + * Use the standard keyword arguments for configuring TLS between the proxy + and the WebSocket server: ``ssl``, ``server_hostname``, + ``ssl_handshake_timeout``, and ``ssl_shutdown_timeout``. + * Other keyword arguments are used only for connecting to the proxy. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + InvalidProxy: If ``proxy`` isn't a valid proxy. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + def __init__( + self, + uri: str, + *, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + process_exception: Callable[[Exception], Exception | None] = process_exception, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + # Other keyword arguments are passed to loop.create_connection + **kwargs: Any, + ) -> None: + self.uri = uri + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if logger is None: + logger = logging.getLogger("websockets.client") + + if create_connection is None: + create_connection = ClientConnection + + def protocol_factory(uri: WebSocketURI) -> ClientConnection: + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ClientProtocol( + uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + self.proxy = proxy + self.protocol_factory = protocol_factory + self.additional_headers = additional_headers + self.user_agent_header = user_agent_header + self.process_exception = process_exception + self.open_timeout = open_timeout + self.logger = logger + self.connection_kwargs = kwargs + + async def create_connection(self) -> ClientConnection: + """Create TCP or Unix connection.""" + loop = asyncio.get_running_loop() + kwargs = self.connection_kwargs.copy() + + ws_uri = parse_uri(self.uri) + + proxy = self.proxy + if kwargs.get("unix", False): + proxy = None + if kwargs.get("sock") is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + def factory() -> ClientConnection: + return self.protocol_factory(ws_uri) + + if ws_uri.secure: + kwargs.setdefault("ssl", True) + kwargs.setdefault("server_hostname", ws_uri.host) + if kwargs.get("ssl") is None: + raise ValueError("ssl=None is incompatible with a wss:// URI") + else: + if kwargs.get("ssl") is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + if kwargs.pop("unix", False): + _, connection = await loop.create_unix_connection(factory, **kwargs) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = await connect_socks_proxy( + proxy_parsed, + ws_uri, + local_addr=kwargs.pop("local_addr", None), + ) + # Initialize WebSocket connection via the proxy. + _, connection = await loop.create_connection( + factory, + sock=sock, + **kwargs, + ) + elif proxy_parsed.scheme[:4] == "http": + # Split keyword arguments between the proxy and the server. + all_kwargs, proxy_kwargs, kwargs = kwargs, {}, {} + for key, value in all_kwargs.items(): + if key.startswith("ssl") or key == "server_hostname": + kwargs[key] = value + elif key.startswith("proxy_"): + proxy_kwargs[key[6:]] = value + else: + proxy_kwargs[key] = value + # Validate the proxy_ssl argument. + if proxy_parsed.scheme == "https": + proxy_kwargs.setdefault("ssl", True) + if proxy_kwargs.get("ssl") is None: + raise ValueError( + "proxy_ssl=None is incompatible with an https:// proxy" + ) + else: + if proxy_kwargs.get("ssl") is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + transport = await connect_http_proxy( + proxy_parsed, + ws_uri, + user_agent_header=self.user_agent_header, + **proxy_kwargs, + ) + # Initialize WebSocket connection via the proxy. + connection = factory() + transport.set_protocol(connection) + ssl = kwargs.pop("ssl", None) + if ssl is True: + ssl = ssl_module.create_default_context() + if ssl is not None: + new_transport = await loop.start_tls( + transport, connection, ssl, **kwargs + ) + assert new_transport is not None # help mypy + transport = new_transport + connection.connection_made(transport) + else: + raise AssertionError("unsupported proxy") + else: + # Connect to the server directly. + if kwargs.get("sock") is None: + kwargs.setdefault("host", ws_uri.host) + kwargs.setdefault("port", ws_uri.port) + # Initialize WebSocket connection. + _, connection = await loop.create_connection(factory, **kwargs) + return connection + + def process_redirect(self, exc: Exception) -> Exception | str: + """ + Determine whether a connection error is a redirect that can be followed. + + Return the new URI if it's a valid redirect. Else, return an exception. + + """ + if not ( + isinstance(exc, InvalidStatus) + and exc.response.status_code + in [ + 300, # Multiple Choices + 301, # Moved Permanently + 302, # Found + 303, # See Other + 307, # Temporary Redirect + 308, # Permanent Redirect + ] + and "Location" in exc.response.headers + ): + return exc + + old_ws_uri = parse_uri(self.uri) + new_uri = urllib.parse.urljoin(self.uri, exc.response.headers["Location"]) + new_ws_uri = parse_uri(new_uri) + + # If connect() received a socket, it is closed and cannot be reused. + if self.connection_kwargs.get("sock") is not None: + return ValueError( + f"cannot follow redirect to {new_uri} with a preexisting socket" + ) + + # TLS downgrade is forbidden. + if old_ws_uri.secure and not new_ws_uri.secure: + return SecurityError(f"cannot follow redirect to non-secure URI {new_uri}") + + # Apply restrictions to cross-origin redirects. + if ( + old_ws_uri.secure != new_ws_uri.secure + or old_ws_uri.host != new_ws_uri.host + or old_ws_uri.port != new_ws_uri.port + ): + # Cross-origin redirects on Unix sockets don't quite make sense. + if self.connection_kwargs.get("unix", False): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with a Unix socket" + ) + + # Cross-origin redirects when host and port are overridden are ill-defined. + if ( + self.connection_kwargs.get("host") is not None + or self.connection_kwargs.get("port") is not None + ): + return ValueError( + f"cannot follow cross-origin redirect to {new_uri} " + f"with an explicit host or port" + ) + + return new_uri + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, ClientConnection]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> ClientConnection: + try: + async with asyncio_timeout(self.open_timeout): + for _ in range(MAX_REDIRECTS): + self.connection = await self.create_connection() + try: + await self.connection.handshake( + self.additional_headers, + self.user_agent_header, + ) + except asyncio.CancelledError: + self.connection.transport.abort() + raise + except Exception as exc: + # Always close the connection even though keep-alive is + # the default in HTTP/1.1 because create_connection ties + # opening the network connection with initializing the + # protocol. In the current design of connect(), there is + # no easy way to reuse the network connection that works + # in every case nor to reinitialize the protocol. + self.connection.transport.abort() + + uri_or_exc = self.process_redirect(exc) + # Response is a valid redirect; follow it. + if isinstance(uri_or_exc, str): + self.uri = uri_or_exc + continue + # Response isn't a valid redirect; raise the exception. + if uri_or_exc is exc: + raise + else: + raise uri_or_exc from exc + + else: + self.connection.start_keepalive() + return self.connection + else: + raise SecurityError(f"more than {MAX_REDIRECTS} redirects") + + except TimeoutError as exc: + # Re-raise exception with an informative error message. + raise TimeoutError("timed out during opening handshake") from exc + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + # async with connect(...) as ...: ... + + async def __aenter__(self) -> ClientConnection: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.connection.close() + + # async for ... in connect(...): + + async def __aiter__(self) -> AsyncIterator[ClientConnection]: + delays: Generator[float] | None = None + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Determine whether the exception is retryable or fatal. + # The API of process_exception is "return an exception or None"; + # "raise an exception" is also supported because it's a frequent + # mistake. It isn't documented in order to keep the API simple. + try: + new_exc = self.process_exception(exc) + except Exception as raised_exc: + new_exc = raised_exc + + # The connection failed with a fatal error. + # Raise the exception and exit the loop. + if new_exc is exc: + raise + if new_exc is not None: + raise new_exc from exc + + # The connection failed with a retryable error. + # Start or continue backoff and reconnect. + if delays is None: + delays = backoff() + delay = next(delays) + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(delay) + continue + + else: + # The connection succeeded. Reset backoff. + delays = None + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> connect: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` argument is provided, to + ``wss://localhost/``. + + """ + if uri is None: + if kwargs.get("ssl") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.async_.asyncio import Proxy as SocksProxy + +except ImportError: + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + async def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + # connect() is documented to raise OSError. + # socks_proxy.connect() doesn't raise TimeoutError; it gets canceled. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return await socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except OSError: + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +class HTTPProxyConnection(asyncio.Protocol): + def __init__( + self, + ws_uri: WebSocketURI, + proxy: Proxy, + user_agent_header: str | None = None, + ): + self.ws_uri = ws_uri + self.proxy = proxy + self.user_agent_header = user_agent_header + + self.reader = StreamReader() + self.parser = Response.parse( + self.reader.read_line, + self.reader.read_exact, + self.reader.read_to_eof, + proxy=True, + ) + + loop = asyncio.get_running_loop() + self.response: asyncio.Future[Response] = loop.create_future() + + def run_parser(self) -> None: + try: + next(self.parser) + except StopIteration as exc: + response = exc.value + if 200 <= response.status_code < 300: + self.response.set_result(response) + else: + self.response.set_exception(InvalidProxyStatus(response)) + except Exception as exc: + proxy_exc = InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) + proxy_exc.__cause__ = exc + self.response.set_exception(proxy_exc) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.transport = transport + self.transport.write( + prepare_connect_request(self.proxy, self.ws_uri, self.user_agent_header) + ) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + self.run_parser() + + def eof_received(self) -> None: + self.reader.feed_eof() + self.run_parser() + + def connection_lost(self, exc: Exception | None) -> None: + self.reader.feed_eof() + if exc is not None: + self.response.set_exception(exc) + + +async def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + user_agent_header: str | None = None, + **kwargs: Any, +) -> asyncio.Transport: + transport, protocol = await asyncio.get_running_loop().create_connection( + lambda: HTTPProxyConnection(ws_uri, proxy, user_agent_header), + proxy.host, + proxy.port, + **kwargs, + ) + + try: + # This raises exceptions if the connection to the proxy fails. + await protocol.response + except Exception: + transport.close() + raise + + return transport diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/compatibility.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/compatibility.py new file mode 100644 index 0000000000000000000000000000000000000000..e17000069d530bdde8de5194e0d8257a5c5d1770 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/compatibility.py @@ -0,0 +1,30 @@ +from __future__ import annotations + +import sys + + +__all__ = ["TimeoutError", "aiter", "anext", "asyncio_timeout", "asyncio_timeout_at"] + + +if sys.version_info[:2] >= (3, 11): + TimeoutError = TimeoutError + aiter = aiter + anext = anext + from asyncio import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) + +else: # Python < 3.11 + from asyncio import TimeoutError + + def aiter(async_iterable): + return type(async_iterable).__aiter__(async_iterable) + + async def anext(async_iterator): + return await type(async_iterator).__anext__(async_iterator) + + from .async_timeout import ( + timeout as asyncio_timeout, # noqa: F401 + timeout_at as asyncio_timeout_at, # noqa: F401 + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/connection.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..205a2be50871cbc2cb85144421587a57a58bc725 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/connection.py @@ -0,0 +1,1247 @@ +from __future__ import annotations + +import asyncio +import collections +import contextlib +import logging +import random +import struct +import sys +import traceback +import uuid +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from types import TracebackType +from typing import Any, Literal, cast, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .compatibility import ( + TimeoutError, + aiter, + anext, + asyncio_timeout, + asyncio_timeout_at, +) +from .messages import Assembler + + +__all__ = ["Connection"] + + +class Connection(asyncio.Protocol): + """ + :mod:`asyncio` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.asyncio.client.ClientConnection` or + :class:`~websockets.asyncio.server.ServerConnection`. + + """ + + def __init__( + self, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + self.max_queue_high, self.max_queue_low = max_queue, None + else: + self.max_queue_high, self.max_queue_low = max_queue + if isinstance(write_limit, int): + self.write_limit_high, self.write_limit_low = write_limit, None + else: + self.write_limit_high, self.write_limit_low = write_limit + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Event loop running this connection. + self.loop = asyncio.get_running_loop() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages: Assembler # initialized in connection_made + + # Deadline for the closing handshake. + self.close_deadline: float | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task that sends keepalive pings. None when ping_interval is None. + self.keepalive_task: asyncio.Task[None] | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Completed when the TCP connection is closed and the WebSocket + # connection state becomes CLOSED. + self.connection_lost_waiter: asyncio.Future[None] = self.loop.create_future() + + # Adapted from asyncio.FlowControlMixin. + self.paused: bool = False + self.drain_waiters: collections.deque[asyncio.Future[None]] = ( + collections.deque() + ) + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.transport.get_extra_info("peername") + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + async def __aenter__(self) -> Connection: + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + await self.close() + else: + await self.close(CloseCode.INTERNAL_ERROR) + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages asynchronously in an + infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + @overload + async def recv(self, decode: Literal[True]) -> str: ... + + @overload + async def recv(self, decode: Literal[False]) -> bytes: ... + + @overload + async def recv(self, decode: bool | None = None) -> Data: ... + + async def recv(self, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing data. The next + invocation of :meth:`recv` will return the next message. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return await self.recv_messages.get(decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def recv_streaming(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + asynchronous iterator that yields each fragment as it is received. This + iterator must be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Canceling :meth:`recv_streaming` before receiving the first frame is + safe. Canceling it after receiving one or more frames leaves the + iterator in a partially consumed state, making the connection unusable. + Instead, you should close the connection with :meth:`close`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two coroutines call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + async for frame in self.recv_messages.get_iter(decode): + yield frame + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another coroutine " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + async with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from self.recv_exc + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable or asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and the + effect is more obvious: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self.send_in_progress is not None: + await asyncio.shield(self.send_in_progress) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + async with self.send_context(): + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + async with self.send_context(): + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + # Fragmented message -- async iterator. + + elif isinstance(message, AsyncIterable): + achunks = aiter(message) + try: + chunk = await anext(achunks) + except StopAsyncIteration: + return + + assert self.send_in_progress is None + self.send_in_progress = self.loop.create_future() + try: + # First fragment. + if isinstance(chunk, str): + if text is False: + async with self.send_context(): + self.protocol.send_binary(chunk.encode(), fin=False) + else: + async with self.send_context(): + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + if text is True: + async with self.send_context(): + self.protocol.send_text(chunk, fin=False) + else: + async with self.send_context(): + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("async iterable must contain bytes or str") + + # Other fragments + async for chunk in achunks: + if isinstance(chunk, str) and encode: + async with self.send_context(): + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + async with self.send_context(): + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("async iterable must contain uniform types") + + # Final fragment. + async with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + finally: + self.send_in_progress.set_result(None) + self.send_in_progress = None + + else: + raise TypeError("data must be str, bytes, iterable, or async iterable") + + async def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + async with self.send_context(): + if self.send_in_progress is not None: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + :meth:`wait_closed` waits for the closing handshake to complete and for + the TCP connection to terminate. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_received = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_received + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = self.loop.create_future() + ping_timestamp = self.loop.time() + # The event loop's default clock is time.monotonic(). Its resolution + # is a bit low on Windows (~16ms). This is improved in Python 3.13. + self.pending_pings[data] = (pong_received, ping_timestamp) + self.protocol.send_ping(data) + return pong_received + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + async with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = self.loop.time() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_received, ping_timestamp) in self.pending_pings.items(): + ping_ids.append(ping_id) + latency = pong_timestamp - ping_timestamp + if not pong_received.done(): + pong_received.set_result(latency) + if ping_id == data: + self.latency = latency + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Raise ConnectionClosed in pending pings when the connection is closed. + + """ + assert self.protocol.state is CLOSED + exc = self.protocol.close_exc + + for pong_received, _ping_timestamp in self.pending_pings.values(): + if not pong_received.done(): + pong_received.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_received.cancel() + + self.pending_pings.clear() + + async def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + latency = 0.0 + try: + while True: + # If self.ping_timeout > latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + await asyncio.sleep(self.ping_interval - latency) + + # This cannot raise ConnectionClosed when the connection is + # closing because ping(), via send_context(), waits for the + # connection to be closed before raising ConnectionClosed. + # However, connection_lost() cancels keepalive_task before + # it gets a chance to resume excuting. + pong_received = await self.ping() + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # connection_lost cancels keepalive immediately + # after setting a ConnectionClosed exception on + # pong_received. A CancelledError is raised here, + # not a ConnectionClosed exception. + latency = await pong_received + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + async with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + raise AssertionError( + "send_context() should wait for connection_lost(), " + "which cancels keepalive()" + ) + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a task, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + self.keepalive_task = self.loop.create_task(self.keepalive()) + + @contextlib.asynccontextmanager + async def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> AsyncIterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` checks that the connection is open; on + exit, it writes outgoing data to the socket:: + + async with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the transport and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING), self.close_deadline is still None. + assert self.close_deadline is None + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + # Write outgoing data to the socket with flow control. + try: + self.send_data() + await self.drain() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + raise_close_exc = True + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + try: + async with asyncio_timeout_at(self.close_deadline): + await asyncio.shield(self.connection_lost_waiter) + except TimeoutError: + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the transport in order to get + # proper exception reporting. + raise_close_exc = True + self.set_recv_exc(original_exc) + + # If an error occurred, close the transport to terminate the connection and + # raise an exception. + if raise_close_exc: + self.transport.abort() + # Wait for the protocol state to be CLOSED before accessing close_exc. + await asyncio.shield(self.connection_lost_waiter) + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + """ + for data in self.protocol.data_to_send(): + if data: + self.transport.write(data) + else: + # Half-close the TCP connection when possible i.e. no TLS. + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # OSError is plausible. uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except Exception: # pragma: no cover + pass + # Else, close the TCP connection. + else: # pragma: no cover + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method must be called only from connection callbacks. + + """ + if self.recv_exc is None: + self.recv_exc = exc + + # asyncio.Protocol methods + + # Connection callbacks + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + transport = cast(asyncio.Transport, transport) + self.recv_messages = Assembler( + self.max_queue_high, + self.max_queue_low, + pause=transport.pause_reading, + resume=transport.resume_reading, + ) + transport.set_write_buffer_limits( + self.write_limit_high, + self.write_limit_low, + ) + self.transport = transport + + def connection_lost(self, exc: Exception | None) -> None: + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + self.set_recv_exc(exc) + + # Abort recv() and pending pings with a ConnectionClosed exception. + self.recv_messages.close() + self.terminate_pending_pings() + + if self.keepalive_task is not None: + self.keepalive_task.cancel() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: # pragma: no cover + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + # Flow control callbacks + + def pause_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert not self.paused + self.paused = True + + def resume_writing(self) -> None: # pragma: no cover + # Adapted from asyncio.streams.FlowControlMixin + assert self.paused + self.paused = False + for waiter in self.drain_waiters: + if not waiter.done(): + waiter.set_result(None) + + async def drain(self) -> None: # pragma: no cover + # We don't check if the connection is closed because we call drain() + # immediately after write() and write() would fail in that case. + + # Adapted from asyncio.streams.StreamWriter + # Yield to the event loop so that connection_lost() may be called. + if self.transport.is_closing(): + await asyncio.sleep(0) + + # Adapted from asyncio.streams.FlowControlMixin + if self.paused: + waiter = self.loop.create_future() + self.drain_waiters.append(waiter) + try: + await waiter + finally: + self.drain_waiters.remove(waiter) + + # Streaming protocol callbacks + + def data_received(self, data: bytes) -> None: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the transport. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug("! error while sending data", exc_info=True) + self.set_recv_exc(exc) + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + if self.close_timeout is not None: + self.close_deadline = self.loop.time() + self.close_timeout + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + def eof_received(self) -> None: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + # The WebSocket protocol has its own closing handshake: endpoints close + # the TCP or TLS connection after sending and receiving a close frame. + # As a consequence, they never need to write after receiving EOF, so + # there's no reason to keep the transport open by returning True. + # Besides, that doesn't work on TLS connections. + + +# broadcast() is defined in the connection module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# Connection class. + + +def broadcast( + connections: Iterable[Connection], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.asyncio.connection.Connection.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if isinstance(message, str): + send_method = "send_text" + message = message.encode() + elif isinstance(message, BytesLike): + send_method = "send_binary" + else: + raise TypeError("data must be str or bytes") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions: list[Exception] = [] + + for connection in connections: + exception: Exception + + if connection.protocol.state is not OPEN: + continue + + if connection.send_in_progress is not None: + if raise_exceptions: + exception = ConcurrencyError("sending a fragmented message") + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + # Call connection.protocol.send_text or send_binary. + # Either way, message is already converted to bytes. + getattr(connection.protocol, send_method)(message) + connection.send_data() + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + connection.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.asyncio.server" diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/messages.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..f27cb2e7c8724434652f15be0a7efbdd49cf8951 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/messages.py @@ -0,0 +1,316 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +from collections.abc import AsyncIterator, Iterable +from typing import Any, Callable, Generic, Literal, TypeVar, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + +T = TypeVar("T") + + +class SimpleQueue(Generic[T]): + """ + Simplified version of :class:`asyncio.Queue`. + + Provides only the subset of functionality needed by :class:`Assembler`. + + """ + + def __init__(self) -> None: + self.loop = asyncio.get_running_loop() + self.get_waiter: asyncio.Future[None] | None = None + self.queue: collections.deque[T] = collections.deque() + + def __len__(self) -> int: + return len(self.queue) + + def put(self, item: T) -> None: + """Put an item into the queue.""" + self.queue.append(item) + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_result(None) + + async def get(self, block: bool = True) -> T: + """Remove and return an item from the queue, waiting if necessary.""" + if not self.queue: + if not block: + raise EOFError("stream of frames ended") + assert self.get_waiter is None, "cannot call get() concurrently" + self.get_waiter = self.loop.create_future() + try: + await self.get_waiter + finally: + self.get_waiter.cancel() + self.get_waiter = None + return self.queue.popleft() + + def reset(self, items: Iterable[T]) -> None: + """Put back items into an empty, idle queue.""" + assert self.get_waiter is None, "cannot reset() while get() is running" + assert not self.queue, "cannot reset() while queue isn't empty" + self.queue.extend(items) + + def abort(self) -> None: + """Close the queue, raising EOFError in get() if necessary.""" + if self.get_waiter is not None and not self.get_waiter.done(): + self.get_waiter.set_exception(EOFError("stream of frames ended")) + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Queue of incoming frames. + self.frames: SimpleQueue[Frame] = SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + @overload + async def get(self, decode: Literal[True]) -> str: ... + + @overload + async def get(self, decode: Literal[False]) -> bytes: ... + + @overload + async def get(self, decode: bool | None = None) -> Data: ... + + async def get(self, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or is canceled. + + try: + # Fetch the first frame. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.frames.reset(frames) + raise + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> AsyncIterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> AsyncIterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: ... + + async def get_iter(self, decode: bool | None = None) -> AsyncIterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` asynchronously yields a + :class:`str` or :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or is canceled. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + try: + frame = await self.frames.get(not self.closed) + except asyncio.CancelledError: + self.get_in_progress = False + raise + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + # We cannot handle asyncio.CancelledError because we don't buffer + # previous fragments — we're streaming them. Canceling get_iter() + # here will leave the assembler in a stuck state. Future calls to + # get() or get_iter() will raise ConcurrencyError. + frame = await self.frames.get(not self.closed) + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + # Check for "> high" to support high = 0. + if len(self.frames) > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + # Check for "<= low" to support low = 0. + if len(self.frames) <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + if self.closed: + return + + self.closed = True + + # Unblock get() or get_iter(). + self.frames.abort() diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/router.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/router.py new file mode 100644 index 0000000000000000000000000000000000000000..49d2a40feee03ebcda5e05dc43eebeb27ccecab7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/router.py @@ -0,0 +1,219 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Awaitable, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.asyncio.router import route + from werkzeug.routing import Map, Rule + + async def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with route(url_map, ...) as server: + await stop + + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] = router.route_request + else: + + async def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if isinstance(response, Awaitable): + response = await response + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Awaitable[Server]: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.asyncio.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + async def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return await connection.handler(connection, **connection.handler_kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/server.py b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef9bd807f102e05bbc3de212768bfed1679d8764 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/asyncio/server.py @@ -0,0 +1,997 @@ +from __future__ import annotations + +import asyncio +import hmac +import http +import logging +import re +import socket +import sys +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .compatibility import asyncio_timeout +from .connection import Connection, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "ServerConnection", + "Server", + "basic_auth", +] + + +class ServerConnection(Connection): + """ + :mod:`asyncio` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, ``max_queue``, + and ``write_limit`` arguments have the same meaning as in :func:`serve`. + + Args: + protocol: Sans-I/O connection. + server: Server that manages this connection. + + """ + + def __init__( + self, + protocol: ServerProtocol, + server: Server, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + ) -> None: + self.protocol: ServerProtocol + super().__init__( + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + self.server = server + self.request_rcvd: asyncio.Future[None] = self.loop.create_future() + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], Awaitable[None]] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + async def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + ) -> None: + """ + Perform the opening handshake. + + """ + await asyncio.wait( + [self.request_rcvd, self.connection_lost_waiter], + return_when=asyncio.FIRST_COMPLETED, + ) + + if self.request is not None: + async with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + if self.server.is_serving(): + self.response = self.protocol.accept(self.request) + else: + self.response = self.protocol.reject( + http.HTTPStatus.SERVICE_UNAVAILABLE, + "Server is shutting down.\n", + ) + else: + assert isinstance(response, Response) # help mypy + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + if isinstance(response, Awaitable): + response = await response + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + assert isinstance(response, Response) # help mypy + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set_result(None) + # Later events - frames. + else: + super().process_event(event) + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + super().connection_made(transport) + self.server.start_connection_handler(self) + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. ``process_response`` may be a function or a + coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + *, + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + open_timeout: float | None = 10, + logger: LoggerLike | None = None, + ) -> None: + self.loop = asyncio.get_running_loop() + self.handler = handler + self.process_request = process_request + self.process_response = process_response + self.server_header = server_header + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.handlers: dict[ServerConnection, asyncio.Task[None]] = {} + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] = self.loop.create_future() + + @property + def connections(self) -> set[ServerConnection]: + """ + Set of active connections. + + This property contains all connections that completed the opening + handshake successfully and didn't start the closing handshake yet. + It can be useful in combination with :func:`~broadcast`. + + """ + return {connection for connection in self.handlers if connection.state is OPEN} + + def wrap(self, server: asyncio.Server) -> None: + """ + Attach to a given :class:`asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`Server` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + async def conn_handler(self, connection: ServerConnection) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller that can handle exceptions, + it attempts to log relevant ones. + + It guarantees that the TCP connection is closed before exiting. + + """ + try: + async with asyncio_timeout(self.open_timeout): + try: + await connection.handshake( + self.process_request, + self.process_response, + self.server_header, + ) + except asyncio.CancelledError: + connection.transport.abort() + raise + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.transport.abort() + return + + if connection.protocol.state is not OPEN: + # process_request or process_response rejected the handshake. + connection.transport.abort() + return + + try: + connection.start_keepalive() + await self.handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + await connection.close(CloseCode.INTERNAL_ERROR) + else: + await connection.close() + + except TimeoutError: + # When the opening handshake times out, there's nothing to log. + pass + + except Exception: # pragma: no cover + # Don't leak connections on unexpected errors. + connection.transport.abort() + + finally: + # Registration is tied to the lifecycle of conn_handler() because + # the server waits for connection handlers to terminate, even if + # all connections are already closed. + del self.handlers[connection] + + def start_connection_handler(self, connection: ServerConnection) -> None: + """ + Register a connection with this server. + + """ + # The connection must be registered in self.handlers immediately. + # If it was registered in conn_handler(), a race condition could + # happen when closing the server after scheduling conn_handler() + # but before it starts executing. + self.handlers[connection] = self.loop.create_task(self.conn_handler(connection)) + + def close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Close the server. + + * Close the underlying :class:`asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, close + existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with code 1001 (going away). + ``code`` and ``reason`` can be customized, for example to use code + 1012 (service restart). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections, code, reason) + ) + + async def _close( + self, + close_connections: bool = True, + code: CloseCode | int = CloseCode.GOING_AWAY, + reason: str = "", + ) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`asyncio.Server` object to stop accepting new connections and + then closes open connections. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + # After server.close(), handshake() closes OPENING connections with an + # HTTP 503 error. + + if close_connections: + # Close OPEN connections with code 1001 by default. + close_tasks = [ + asyncio.create_task(connection.close(code, reason)) + for connection in self.handlers + if connection.protocol.state is not CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.handlers: + await asyncio.wait(self.handlers.values()) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~ServerConnection.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~ServerConnection.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: # pragma: no cover + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> tuple[socket.socket, ...]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> Server: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +# This is spelled in lower case because it's exposed as a callable in the API. +class serve: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler`` coroutine. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This coroutine returns a :class:`Server` whose API mirrors + :class:`asyncio.Server`. Treat it as an asynchronous context manager to + ensure that the server will be closed:: + + from websockets.asyncio.server import serve + + def handler(websocket): + ... + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(handler, host, port): + await stop + + Alternatively, call :meth:`~Server.serve_forever` to serve requests and + cancel it to stop the server:: + + server = await serve(handler, host, port) + await server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_request`` may be a function or a coroutine. + process_response: Intercept the response during the opening handshake. + Return an HTTP response to force the response or :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + ``process_response`` may be a function or a coroutine. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + write_limit: High-water mark of write buffer in bytes. It is passed to + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`. It defaults + to 32 KiB. You may pass a ``(high, low)`` tuple to set the + high-water and low-water marks. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to provide a preexisting TCP socket. You may call + :func:`socket.create_server` (not to be confused with the event loop's + :meth:`~asyncio.loop.create_server` method) to create a suitable server + socket and customize it. + + * You can set ``start_serving`` to ``False`` to start accepting connections + only after you call :meth:`~Server.start_serving()` or + :meth:`~Server.serve_forever()`. + + """ + + def __init__( + self, + handler: Callable[[ServerConnection], Awaitable[None]], + host: str | None = None, + port: int | None = None, + *, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Awaitable[Response | None] | Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + write_limit: int | tuple[int, int | None] = 2**15, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + # Other keyword arguments are passed to loop.create_server + **kwargs: Any, + ) -> None: + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + self.server = Server( + handler, + process_request=process_request, + process_response=process_response, + server_header=server_header, + open_timeout=open_timeout, + logger=logger, + ) + + if kwargs.get("ssl") is not None: + kwargs.setdefault("ssl_handshake_timeout", open_timeout) + if sys.version_info[:2] >= (3, 11): # pragma: no branch + kwargs.setdefault("ssl_shutdown_timeout", close_timeout) + + def factory() -> ServerConnection: + """ + Create an asyncio protocol for managing a WebSocket connection. + + """ + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # This is a protocol in the Sans-I/O implementation of websockets. + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + # This is a connection in websockets and a protocol in asyncio. + connection = create_connection( + protocol, + self.server, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + write_limit=write_limit, + ) + return connection + + loop = asyncio.get_running_loop() + if kwargs.pop("unix", False): + self.create_server = loop.create_unix_server(factory, **kwargs) + else: + # mypy cannot tell that kwargs must provide sock when port is None. + self.create_server = loop.create_server(factory, host, port, **kwargs) # type: ignore[arg-type] + + # async with serve(...) as ...: ... + + async def __aenter__(self) -> Server: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.server.close() + await self.server.wait_closed() + + # ... = await serve(...) + + def __await__(self) -> Generator[Any, None, Server]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> Server: + server = await self.create_server + self.server.wrap(server) + return self.server + + # ... = yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +def unix_serve( + handler: Callable[[ServerConnection], Awaitable[None]], + path: str | None = None, + **kwargs: Any, +) -> Awaitable[Server]: + """ + Create a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool] | bool] | None = None, +) -> Callable[[ServerConnection, Request], Awaitable[Response | None]]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.asyncio.server import basic_auth, serve + + async with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function or coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + async def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + valid_credentials = check_credentials(username, password) + if isinstance(valid_credentials, Awaitable): + valid_credentials = await valid_credentials + + if not valid_credentials: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__init__.py b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02838b98a5335322daad566de9c0d9d0843fc49a --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__init__.py @@ -0,0 +1,4 @@ +from .base import * + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96340afadf683b95ac3819ad8443bc8380d104de Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/base.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/base.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..edb70129055f7d6a5dfe771318967fb21e3fc199 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/base.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d46dcd56a056a9f8e329ccfbd4db3558515b1fd4 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/__pycache__/permessage_deflate.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/base.py b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/base.py new file mode 100644 index 0000000000000000000000000000000000000000..2fdc59f0fdae4d28fdcf18b6f9edf8d62ad22f01 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/base.py @@ -0,0 +1,123 @@ +from __future__ import annotations + +from collections.abc import Sequence + +from ..frames import Frame +from ..typing import ExtensionName, ExtensionParameter + + +__all__ = ["Extension", "ClientExtensionFactory", "ServerExtensionFactory"] + + +class Extension: + """ + Base class for extensions. + + """ + + name: ExtensionName + """Extension identifier.""" + + def decode(self, frame: Frame, *, max_size: int | None = None) -> Frame: + """ + Decode an incoming frame. + + Args: + frame: Incoming frame. + max_size: Maximum payload size in bytes. + + Returns: + Decoded frame. + + Raises: + PayloadTooBig: If decoding the payload exceeds ``max_size``. + + """ + raise NotImplementedError + + def encode(self, frame: Frame) -> Frame: + """ + Encode an outgoing frame. + + Args: + frame: Outgoing frame. + + Returns: + Encoded frame. + + """ + raise NotImplementedError + + +class ClientExtensionFactory: + """ + Base class for client-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build parameters to send to the server for this extension. + + Returns: + Parameters to send to the server. + + """ + raise NotImplementedError + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> Extension: + """ + Process parameters received from the server. + + Args: + params: Parameters received from the server for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + An extension instance. + + Raises: + NegotiationError: If parameters aren't acceptable. + + """ + raise NotImplementedError + + +class ServerExtensionFactory: + """ + Base class for server-side extension factories. + + """ + + name: ExtensionName + """Extension identifier.""" + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], Extension]: + """ + Process parameters received from the client. + + Args: + params: Parameters received from the client for this extension. + accepted_extensions: List of previously accepted extensions. + + Returns: + To accept the offer, parameters to send to the client for this + extension and an extension instance. + + Raises: + NegotiationError: To reject the offer, if parameters received from + the client aren't acceptable. + + """ + raise NotImplementedError diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/permessage_deflate.py b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/permessage_deflate.py new file mode 100644 index 0000000000000000000000000000000000000000..2bc63d79929321007578d3e1d96338f099fad085 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/extensions/permessage_deflate.py @@ -0,0 +1,699 @@ +from __future__ import annotations + +import zlib +from collections.abc import Sequence +from typing import Any, Literal + +from .. import frames +from ..exceptions import ( + DuplicateParameter, + InvalidParameterName, + InvalidParameterValue, + NegotiationError, + PayloadTooBig, + ProtocolError, +) +from ..typing import BytesLike, ExtensionName, ExtensionParameter +from .base import ClientExtensionFactory, Extension, ServerExtensionFactory + + +__all__ = [ + "PerMessageDeflate", + "ClientPerMessageDeflateFactory", + "enable_client_permessage_deflate", + "ServerPerMessageDeflateFactory", + "enable_server_permessage_deflate", +] + +_EMPTY_UNCOMPRESSED_BLOCK = b"\x00\x00\xff\xff" + +_MAX_WINDOW_BITS_VALUES = [str(bits) for bits in range(8, 16)] + + +class PerMessageDeflate(Extension): + """ + Per-Message Deflate extension. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + remote_no_context_takeover: bool, + local_no_context_takeover: bool, + remote_max_window_bits: int, + local_max_window_bits: int, + compress_settings: dict[Any, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension. + + """ + if compress_settings is None: + compress_settings = {} + + assert remote_no_context_takeover in [False, True] + assert local_no_context_takeover in [False, True] + assert 8 <= remote_max_window_bits <= 15 + assert 8 <= local_max_window_bits <= 15 + assert "wbits" not in compress_settings + + self.remote_no_context_takeover = remote_no_context_takeover + self.local_no_context_takeover = local_no_context_takeover + self.remote_max_window_bits = remote_max_window_bits + self.local_max_window_bits = local_max_window_bits + self.compress_settings = compress_settings + + if not self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + if not self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # To handle continuation frames properly, we must keep track of + # whether that initial frame was encoded. + self.decode_cont_data = False + # There's no need for self.encode_cont_data because we always encode + # outgoing frames, so it would always be True. + + def __repr__(self) -> str: + return ( + f"PerMessageDeflate(" + f"remote_no_context_takeover={self.remote_no_context_takeover}, " + f"local_no_context_takeover={self.local_no_context_takeover}, " + f"remote_max_window_bits={self.remote_max_window_bits}, " + f"local_max_window_bits={self.local_max_window_bits})" + ) + + def decode( + self, + frame: frames.Frame, + *, + max_size: int | None = None, + ) -> frames.Frame: + """ + Decode an incoming frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Handle continuation data frames: + # - skip if the message isn't encoded + # - reset "decode continuation data" flag if it's a final frame + if frame.opcode is frames.OP_CONT: + if not self.decode_cont_data: + return frame + if frame.fin: + self.decode_cont_data = False + + # Handle text and binary data frames: + # - skip if the message isn't encoded + # - unset the rsv1 flag on the first frame of a compressed message + # - set "decode continuation data" flag if it's a non-final frame + else: + if not frame.rsv1: + return frame + if not frame.fin: + self.decode_cont_data = True + + # Re-initialize per-message decoder. + if self.remote_no_context_takeover: + self.decoder = zlib.decompressobj(wbits=-self.remote_max_window_bits) + + # Uncompress data. Protect against zip bombs by preventing zlib from + # decompressing more than max_length bytes (except when the limit is + # disabled with max_size = None). + data: BytesLike + if frame.fin and len(frame.data) < 2044: + # Profiling shows that appending four bytes, which makes a copy, is + # faster than calling decompress() again when data is less than 2kB. + data = bytes(frame.data) + _EMPTY_UNCOMPRESSED_BLOCK + else: + data = frame.data + max_length = 0 if max_size is None else max_size + try: + data = self.decoder.decompress(data, max_length) + if self.decoder.unconsumed_tail: + assert max_size is not None # help mypy + raise PayloadTooBig(None, max_size) + if frame.fin and len(frame.data) >= 2044: + # This cannot generate additional data. + self.decoder.decompress(_EMPTY_UNCOMPRESSED_BLOCK) + except zlib.error as exc: + raise ProtocolError("decompression failed") from exc + + # Allow garbage collection of the decoder if it won't be reused. + if frame.fin and self.remote_no_context_takeover: + del self.decoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Unset the rsv1 flag on the first frame of a compressed message. + False, + frame.rsv2, + frame.rsv3, + ) + + def encode(self, frame: frames.Frame) -> frames.Frame: + """ + Encode an outgoing frame. + + """ + # Skip control frames. + if frame.opcode in frames.CTRL_OPCODES: + return frame + + # Since we always encode messages, there's no "encode continuation + # data" flag similar to "decode continuation data" at this time. + + if frame.opcode is not frames.OP_CONT: + # Re-initialize per-message decoder. + if self.local_no_context_takeover: + self.encoder = zlib.compressobj( + wbits=-self.local_max_window_bits, + **self.compress_settings, + ) + + # Compress data. + data: BytesLike + data = self.encoder.compress(frame.data) + self.encoder.flush(zlib.Z_SYNC_FLUSH) + if frame.fin: + # Sync flush generates between 5 or 6 bytes, ending with the bytes + # 0x00 0x00 0xff 0xff, which must be removed. + assert data[-4:] == _EMPTY_UNCOMPRESSED_BLOCK + # Making a copy is faster than memoryview(a)[:-4] until 2kB. + if len(data) < 2048: + data = data[:-4] + else: + data = memoryview(data)[:-4] + + # Allow garbage collection of the encoder if it won't be reused. + if frame.fin and self.local_no_context_takeover: + del self.encoder + + return frames.Frame( + frame.opcode, + data, + frame.fin, + # Set the rsv1 flag on the first frame of a compressed message. + frame.opcode is not frames.OP_CONT, + frame.rsv2, + frame.rsv3, + ) + + +def _build_parameters( + server_no_context_takeover: bool, + client_no_context_takeover: bool, + server_max_window_bits: int | None, + client_max_window_bits: int | Literal[True] | None, +) -> list[ExtensionParameter]: + """ + Build a list of ``(name, value)`` pairs for some compression parameters. + + """ + params: list[ExtensionParameter] = [] + if server_no_context_takeover: + params.append(("server_no_context_takeover", None)) + if client_no_context_takeover: + params.append(("client_no_context_takeover", None)) + if server_max_window_bits: + params.append(("server_max_window_bits", str(server_max_window_bits))) + if client_max_window_bits is True: # only in handshake requests + params.append(("client_max_window_bits", None)) + elif client_max_window_bits: + params.append(("client_max_window_bits", str(client_max_window_bits))) + return params + + +def _extract_parameters( + params: Sequence[ExtensionParameter], *, is_server: bool +) -> tuple[bool, bool, int | None, int | Literal[True] | None]: + """ + Extract compression parameters from a list of ``(name, value)`` pairs. + + If ``is_server`` is :obj:`True`, ``client_max_window_bits`` may be + provided without a value. This is only allowed in handshake requests. + + """ + server_no_context_takeover: bool = False + client_no_context_takeover: bool = False + server_max_window_bits: int | None = None + client_max_window_bits: int | Literal[True] | None = None + + for name, value in params: + if name == "server_no_context_takeover": + if server_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + server_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "client_no_context_takeover": + if client_no_context_takeover: + raise DuplicateParameter(name) + if value is None: + client_no_context_takeover = True + else: + raise InvalidParameterValue(name, value) + + elif name == "server_max_window_bits": + if server_max_window_bits is not None: + raise DuplicateParameter(name) + if value in _MAX_WINDOW_BITS_VALUES: + server_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + elif name == "client_max_window_bits": + if client_max_window_bits is not None: + raise DuplicateParameter(name) + if is_server and value is None: # only in handshake requests + client_max_window_bits = True + elif value in _MAX_WINDOW_BITS_VALUES: + client_max_window_bits = int(value) + else: + raise InvalidParameterValue(name, value) + + else: + raise InvalidParameterName(name) + + return ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) + + +class ClientPerMessageDeflateFactory(ClientExtensionFactory): + """ + Client-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15, or :obj:`True` to indicate support without + setting a limit. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | Literal[True] | None = True, + compress_settings: dict[str, Any] | None = None, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not ( + client_max_window_bits is None + or client_max_window_bits is True + or 8 <= client_max_window_bits <= 15 + ): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set client_max_window_bits instead" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + + def get_request_params(self) -> Sequence[ExtensionParameter]: + """ + Build request parameters. + + """ + return _build_parameters( + self.server_no_context_takeover, + self.client_no_context_takeover, + self.server_max_window_bits, + self.client_max_window_bits, + ) + + def process_response_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> PerMessageDeflate: + """ + Process response parameters. + + Return an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"received duplicate {self.name}") + + # Request parameters are available in instance variables. + + # Load response parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=False) + + # After comparing the request and the response, the final + # configuration must be available in the local variables. + + # server_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False Error! + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + raise NegotiationError("expected server_no_context_takeover") + + # client_no_context_takeover + # + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value + # True True True + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None Error! + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + raise NegotiationError("unsupported server_max_window_bits") + + # client_max_window_bits + + # Req. Resp. Result + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 Error! + # True None None + # True 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.client_max_window_bits: + raise NegotiationError("unsupported client_max_window_bits") + + return PerMessageDeflate( + server_no_context_takeover, # remote_no_context_takeover + client_no_context_takeover, # local_no_context_takeover + server_max_window_bits or 15, # remote_max_window_bits + client_max_window_bits or 15, # local_max_window_bits + self.compress_settings, + ) + + +def enable_client_permessage_deflate( + extensions: Sequence[ClientExtensionFactory] | None, +) -> Sequence[ClientExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in client extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + extension_factory.name == ClientPerMessageDeflateFactory.name + for extension_factory in extensions + ): + extensions = list(extensions) + [ + ClientPerMessageDeflateFactory( + compress_settings={"memLevel": 5}, + ) + ] + return extensions + + +class ServerPerMessageDeflateFactory(ServerExtensionFactory): + """ + Server-side extension factory for the Per-Message Deflate extension. + + Parameters behave as described in `section 7.1 of RFC 7692`_. + + .. _section 7.1 of RFC 7692: https://datatracker.ietf.org/doc/html/rfc7692#section-7.1 + + Set them to :obj:`True` to include them in the negotiation offer without a + value or to an integer value to include them with this value. + + Args: + server_no_context_takeover: Prevent server from using context takeover. + client_no_context_takeover: Prevent client from using context takeover. + server_max_window_bits: Maximum size of the server's LZ77 sliding window + in bits, between 8 and 15. + client_max_window_bits: Maximum size of the client's LZ77 sliding window + in bits, between 8 and 15. + compress_settings: Additional keyword arguments for :func:`zlib.compressobj`, + excluding ``wbits``. + require_client_max_window_bits: Do not enable compression at all if + client doesn't advertise support for ``client_max_window_bits``; + the default behavior is to enable compression without enforcing + ``client_max_window_bits``. + + """ + + name = ExtensionName("permessage-deflate") + + def __init__( + self, + server_no_context_takeover: bool = False, + client_no_context_takeover: bool = False, + server_max_window_bits: int | None = None, + client_max_window_bits: int | None = None, + compress_settings: dict[str, Any] | None = None, + require_client_max_window_bits: bool = False, + ) -> None: + """ + Configure the Per-Message Deflate extension factory. + + """ + if not (server_max_window_bits is None or 8 <= server_max_window_bits <= 15): + raise ValueError("server_max_window_bits must be between 8 and 15") + if not (client_max_window_bits is None or 8 <= client_max_window_bits <= 15): + raise ValueError("client_max_window_bits must be between 8 and 15") + if compress_settings is not None and "wbits" in compress_settings: + raise ValueError( + "compress_settings must not include wbits, " + "set server_max_window_bits instead" + ) + if client_max_window_bits is None and require_client_max_window_bits: + raise ValueError( + "require_client_max_window_bits is enabled, " + "but client_max_window_bits isn't configured" + ) + + self.server_no_context_takeover = server_no_context_takeover + self.client_no_context_takeover = client_no_context_takeover + self.server_max_window_bits = server_max_window_bits + self.client_max_window_bits = client_max_window_bits + self.compress_settings = compress_settings + self.require_client_max_window_bits = require_client_max_window_bits + + def process_request_params( + self, + params: Sequence[ExtensionParameter], + accepted_extensions: Sequence[Extension], + ) -> tuple[list[ExtensionParameter], PerMessageDeflate]: + """ + Process request parameters. + + Return response params and an extension instance. + + """ + if any(other.name == self.name for other in accepted_extensions): + raise NegotiationError(f"skipped duplicate {self.name}") + + # Load request parameters in local variables. + ( + server_no_context_takeover, + client_no_context_takeover, + server_max_window_bits, + client_max_window_bits, + ) = _extract_parameters(params, is_server=True) + + # Configuration parameters are available in instance variables. + + # After comparing the request and the configuration, the response must + # be available in the local variables. + + # server_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True + # True False True - must change value to True + # True True True + + if self.server_no_context_takeover: + if not server_no_context_takeover: + server_no_context_takeover = True + + # client_no_context_takeover + # + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # False False False + # False True True (or False) + # True False True - must change value to True + # True True True (or False) + + if self.client_no_context_takeover: + if not client_no_context_takeover: + client_no_context_takeover = True + + # server_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None 8≤M≤15 M + # 8≤N≤15 None N - must change value + # 8≤N≤15 8≤M≤N M + # 8≤N≤15 N self.server_max_window_bits: + server_max_window_bits = self.server_max_window_bits + + # client_max_window_bits + + # Config Req. Resp. + # ------ ------ -------------------------------------------------- + # None None None + # None True None - must change value + # None 8≤M≤15 M (or None) + # 8≤N≤15 None None or Error! + # 8≤N≤15 True N - must change value + # 8≤N≤15 8≤M≤N M (or None) + # 8≤N≤15 N Sequence[ServerExtensionFactory]: + """ + Enable Per-Message Deflate with default settings in server extensions. + + If the extension is already present, perhaps with non-default settings, + the configuration isn't changed. + + """ + if extensions is None: + extensions = [] + if not any( + ext_factory.name == ServerPerMessageDeflateFactory.name + for ext_factory in extensions + ): + extensions = list(extensions) + [ + ServerPerMessageDeflateFactory( + server_max_window_bits=12, + client_max_window_bits=12, + compress_settings={"memLevel": 5}, + ) + ] + return extensions diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__init__.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ad9aa25064f626754bda8a8bb149d974002a064e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__init__.py @@ -0,0 +1,11 @@ +from __future__ import annotations + +import warnings + + +warnings.warn( # deprecated in 14.0 - 2024-11-09 + "websockets.legacy is deprecated; " + "see https://websockets.readthedocs.io/en/stable/howto/upgrade.html " + "for upgrade instructions", + DeprecationWarning, +) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0fc0ec5ed46e3be447b178379167be8b45b4df63 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/auth.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/auth.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..581f151763955508361b7d7757c5dbdb82545649 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/auth.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..65668ef700768fa3f1c76730e1b34d375d6a16fa Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/exceptions.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/exceptions.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1845037be1619325d6054bcd311399c6428de123 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/exceptions.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/framing.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/framing.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6dceba01bbd07a43b1a2bc5f1a13aedef5d0b784 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/framing.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/handshake.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/handshake.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2f6b493c3e511890c01d403d0448dc2ebb54ad5d Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/handshake.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/http.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/http.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0f49d5d4c4adaeea7c072cbd3fa37ab97b38008 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/http.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/protocol.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/protocol.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..aea1b7e11c712126f402367522b3a7e5b5bd791e Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/protocol.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/server.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1388f13930548c4db1f3c8057cffb39005eff488 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/__pycache__/server.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/auth.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/auth.py new file mode 100644 index 0000000000000000000000000000000000000000..a262fcd791bc66a1ad0ee9389faed1c62c69e2be --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/auth.py @@ -0,0 +1,190 @@ +from __future__ import annotations + +import functools +import hmac +import http +from collections.abc import Awaitable, Iterable +from typing import Any, Callable, cast + +from ..datastructures import Headers +from ..exceptions import InvalidHeader +from ..headers import build_www_authenticate_basic, parse_authorization_basic +from .server import HTTPResponse, WebSocketServerProtocol + + +__all__ = ["BasicAuthWebSocketServerProtocol", "basic_auth_protocol_factory"] + +Credentials = tuple[str, str] + + +def is_credentials(value: Any) -> bool: + try: + username, password = value + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +class BasicAuthWebSocketServerProtocol(WebSocketServerProtocol): + """ + WebSocket server protocol that enforces HTTP Basic Auth. + + """ + + realm: str = "" + """ + Scope of protection. + + If provided, it should contain only ASCII characters because the + encoding of non-ASCII characters is undefined. + """ + + username: str | None = None + """Username of the authenticated user.""" + + def __init__( + self, + *args: Any, + realm: str | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + **kwargs: Any, + ) -> None: + if realm is not None: + self.realm = realm # shadow class attribute + self._check_credentials = check_credentials + super().__init__(*args, **kwargs) + + async def check_credentials(self, username: str, password: str) -> bool: + """ + Check whether credentials are authorized. + + This coroutine may be overridden in a subclass, for example to + authenticate against a database or an external service. + + Args: + username: HTTP Basic Auth username. + password: HTTP Basic Auth password. + + Returns: + :obj:`True` if the handshake should continue; + :obj:`False` if it should fail with an HTTP 401 error. + + """ + if self._check_credentials is not None: + return await self._check_credentials(username, password) + + return False + + async def process_request( + self, + path: str, + request_headers: Headers, + ) -> HTTPResponse | None: + """ + Check HTTP Basic Auth and return an HTTP 401 response if needed. + + """ + try: + authorization = request_headers["Authorization"] + except KeyError: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Missing credentials\n", + ) + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Unsupported credentials\n", + ) + + if not await self.check_credentials(username, password): + return ( + http.HTTPStatus.UNAUTHORIZED, + [("WWW-Authenticate", build_www_authenticate_basic(self.realm))], + b"Invalid credentials\n", + ) + + self.username = username + + return await super().process_request(path, request_headers) + + +def basic_auth_protocol_factory( + realm: str | None = None, + credentials: Credentials | Iterable[Credentials] | None = None, + check_credentials: Callable[[str, str], Awaitable[bool]] | None = None, + create_protocol: Callable[..., BasicAuthWebSocketServerProtocol] | None = None, +) -> Callable[..., BasicAuthWebSocketServerProtocol]: + """ + Protocol factory that enforces HTTP Basic Auth. + + :func:`basic_auth_protocol_factory` is designed to integrate with + :func:`~websockets.legacy.server.serve` like this:: + + serve( + ..., + create_protocol=basic_auth_protocol_factory( + realm="my dev server", + credentials=("hello", "iloveyou"), + ) + ) + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. + Refer to section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Coroutine that verifies credentials. + It receives ``username`` and ``password`` arguments + and returns a :class:`bool`. One of ``credentials`` or + ``check_credentials`` must be provided but not both. + create_protocol: Factory that creates the protocol. By default, this + is :class:`BasicAuthWebSocketServerProtocol`. It can be replaced + by a subclass. + Raises: + TypeError: If the ``credentials`` or ``check_credentials`` argument is + wrong. + + """ + if (credentials is None) == (check_credentials is None): + raise TypeError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(Credentials, credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[Credentials], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + async def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + if create_protocol is None: + create_protocol = BasicAuthWebSocketServerProtocol + + # Help mypy and avoid this error: "type[BasicAuthWebSocketServerProtocol] | + # Callable[..., BasicAuthWebSocketServerProtocol]" not callable [misc] + create_protocol = cast( + Callable[..., BasicAuthWebSocketServerProtocol], create_protocol + ) + return functools.partial( + create_protocol, + realm=realm, + check_credentials=check_credentials, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/client.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/client.py new file mode 100644 index 0000000000000000000000000000000000000000..575c84519c35b3aa25481a5a3abf45b9719df630 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/client.py @@ -0,0 +1,703 @@ +from __future__ import annotations + +import asyncio +import functools +import logging +import os +import random +import traceback +import urllib.parse +import warnings +from collections.abc import AsyncIterator, Generator, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike +from ..exceptions import ( + InvalidHeader, + InvalidHeaderValue, + InvalidMessage, + NegotiationError, + SecurityError, +) +from ..extensions import ClientExtensionFactory, Extension +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import ( + build_authorization_basic, + build_extension, + build_host, + build_subprotocol, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import USER_AGENT +from ..typing import ExtensionHeader, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .exceptions import InvalidStatusCode, RedirectHandshake +from .handshake import build_request, check_response +from .http import read_response +from .protocol import WebSocketCommonProtocol + + +__all__ = ["connect", "unix_connect", "WebSocketClientProtocol"] + + +class WebSocketClientProtocol(WebSocketCommonProtocol): + """ + WebSocket client connection. + + :class:`WebSocketClientProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + See :func:`connect` for the documentation of ``logger``, ``origin``, + ``extensions``, ``subprotocols``, ``extra_headers``, and + ``user_agent_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = True + side = "client" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.client") + super().__init__(logger=logger, **kwargs) + self.origin = origin + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.user_agent_header = user_agent_header + + def write_http_request(self, path: str, headers: Headers) -> None: + """ + Write request line and headers to the HTTP request. + + """ + self.path = path + self.request_headers = headers + + if self.debug: + self.logger.debug("> GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + + # Since the path and headers only contain ASCII characters, + # we can keep this simple. + request = f"GET {path} HTTP/1.1\r\n" + request += str(headers) + + self.transport.write(request.encode()) + + async def read_http_response(self) -> tuple[int, Headers]: + """ + Read status line and headers from the HTTP response. + + If the response contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET response. + + """ + try: + status_code, reason, headers = await read_response(self.reader) + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP response") from exc + + if self.debug: + self.logger.debug("< HTTP/1.1 %d %s", status_code, reason) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.response_headers = headers + + return status_code, self.response_headers + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ClientExtensionFactory] | None, + ) -> list[Extension]: + """ + Handle the Sec-WebSocket-Extensions HTTP response header. + + Check that each extension is supported, as well as its parameters. + + Return the list of accepted extensions. + + Raise :exc:`~websockets.exceptions.InvalidHandshake` to abort the + connection. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension accepted by + the server, we check for a match with each extension available in the + client configuration. If no match is found, an exception is raised. + + If several variants of the same extension are accepted by the server, + it may be configured several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + """ + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values: + if available_extensions is None: + raise NegotiationError("no extensions supported") + + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, response_params in parsed_header_values: + for extension_factory in available_extensions: + # Skip non-matching extensions based on their name. + if extension_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + extension = extension_factory.process_response_params( + response_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the server sent. Fail the connection. + else: + raise NegotiationError( + f"Unsupported extension: " + f"name = {name}, params = {response_params}" + ) + + return accepted_extensions + + @staticmethod + def process_subprotocol( + headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP response header. + + Check that it contains exactly one supported subprotocol. + + Return the selected subprotocol. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values: + if available_subprotocols is None: + raise NegotiationError("no subprotocols supported") + + parsed_header_values: Sequence[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + if len(parsed_header_values) > 1: + raise InvalidHeaderValue( + "Sec-WebSocket-Protocol", + f"multiple values: {', '.join(parsed_header_values)}", + ) + + subprotocol = parsed_header_values[0] + + if subprotocol not in available_subprotocols: + raise NegotiationError(f"unsupported subprotocol: {subprotocol}") + + return subprotocol + + async def handshake( + self, + wsuri: WebSocketURI, + origin: Origin | None = None, + available_extensions: Sequence[ClientExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + ) -> None: + """ + Perform the client side of the opening handshake. + + Args: + wsuri: URI of the WebSocket server. + origin: Value of the ``Origin`` header. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + request_headers = Headers() + + request_headers["Host"] = build_host(wsuri.host, wsuri.port, wsuri.secure) + + if wsuri.user_info: + request_headers["Authorization"] = build_authorization_basic( + *wsuri.user_info + ) + + if origin is not None: + request_headers["Origin"] = origin + + key = build_request(request_headers) + + if available_extensions is not None: + extensions_header = build_extension( + [ + (extension_factory.name, extension_factory.get_request_params()) + for extension_factory in available_extensions + ] + ) + request_headers["Sec-WebSocket-Extensions"] = extensions_header + + if available_subprotocols is not None: + protocol_header = build_subprotocol(available_subprotocols) + request_headers["Sec-WebSocket-Protocol"] = protocol_header + + if self.extra_headers is not None: + request_headers.update(self.extra_headers) + + if self.user_agent_header: + request_headers.setdefault("User-Agent", self.user_agent_header) + + self.write_http_request(wsuri.resource_name, request_headers) + + status_code, response_headers = await self.read_http_response() + if status_code in (301, 302, 303, 307, 308): + if "Location" not in response_headers: + raise InvalidHeader("Location") + raise RedirectHandshake(response_headers["Location"]) + elif status_code != 101: + raise InvalidStatusCode(status_code, response_headers) + + check_response(response_headers, key) + + self.extensions = self.process_extensions( + response_headers, available_extensions + ) + + self.subprotocol = self.process_subprotocol( + response_headers, available_subprotocols + ) + + self.connection_open() + + +class Connect: + """ + Connect to the WebSocket server at ``uri``. + + Awaiting :func:`connect` yields a :class:`WebSocketClientProtocol` which + can then be used to send and receive messages. + + :func:`connect` can be used as a asynchronous context manager:: + + async with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + :func:`connect` can be used as an infinite asynchronous iterator to + reconnect automatically on errors:: + + async for websocket in connect(...): + try: + ... + except websockets.exceptions.ConnectionClosed: + continue + + The connection is closed automatically after each iteration of the loop. + + If an error occurs while establishing the connection, :func:`connect` + retries with exponential backoff. The backoff delay starts at three + seconds and increases up to one minute. + + If an error occurs in the body of the loop, you can handle the exception + and :func:`connect` will reconnect with the next iteration; or you can + let the exception bubble up and break out of the loop. This lets you + decide which errors trigger a reconnection and which errors are fatal. + + Args: + uri: URI of the WebSocket server. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketClientProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers: Arbitrary HTTP headers to add to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_connection` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enforce TLS + settings. When connecting to a ``wss://`` URI, if ``ssl`` isn't + provided, a TLS context is created + with :func:`~ssl.create_default_context`. + + * You can set ``host`` and ``port`` to connect to a different host and + port from those found in ``uri``. This only changes the destination of + the TCP connection. The host name from ``uri`` is still used in the TLS + handshake for secure connections and in the ``Host`` header. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + ~asyncio.TimeoutError: If the opening handshake times out. + + """ + + MAX_REDIRECTS_ALLOWED = int(os.environ.get("WEBSOCKETS_MAX_REDIRECTS", "10")) + + def __init__( + self, + uri: str, + *, + create_protocol: Callable[..., WebSocketClientProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketClientProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketClientProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + wsuri = parse_uri(uri) + if wsuri.secure: + kwargs.setdefault("ssl", True) + elif kwargs.get("ssl") is not None: + raise ValueError( + "connect() received a ssl argument for a ws:// URI, " + "use a wss:// URI to enable TLS" + ) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketClientProtocol] | + # Callable[..., WebSocketClientProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketClientProtocol], create_protocol) + factory = functools.partial( + create_protocol, + logger=logger, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + user_agent_header=user_agent_header, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + host=wsuri.host, + port=wsuri.port, + secure=wsuri.secure, + legacy_recv=legacy_recv, + loop=_loop, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + create_connection = functools.partial( + loop.create_unix_connection, factory, path, **kwargs + ) + else: + host: str | None + port: int | None + if kwargs.get("sock") is None: + host, port = wsuri.host, wsuri.port + else: + # If sock is given, host and port shouldn't be specified. + host, port = None, None + if kwargs.get("ssl"): + kwargs.setdefault("server_hostname", wsuri.host) + # If host and port are given, override values from the URI. + host = kwargs.pop("host", host) + port = kwargs.pop("port", port) + create_connection = functools.partial( + loop.create_connection, factory, host, port, **kwargs + ) + + self.open_timeout = open_timeout + if logger is None: + logger = logging.getLogger("websockets.client") + self.logger = logger + + # This is a coroutine function. + self._create_connection = create_connection + self._uri = uri + self._wsuri = wsuri + + def handle_redirect(self, uri: str) -> None: + # Update the state of this instance to connect to a new URI. + old_uri = self._uri + old_wsuri = self._wsuri + new_uri = urllib.parse.urljoin(old_uri, uri) + new_wsuri = parse_uri(new_uri) + + # Forbid TLS downgrade. + if old_wsuri.secure and not new_wsuri.secure: + raise SecurityError("redirect from WSS to WS") + + same_origin = ( + old_wsuri.secure == new_wsuri.secure + and old_wsuri.host == new_wsuri.host + and old_wsuri.port == new_wsuri.port + ) + + # Rewrite secure, host, and port for cross-origin redirects. + # This preserves connection overrides with the host and port + # arguments if the redirect points to the same host and port. + if not same_origin: + factory = self._create_connection.args[0] + # Support TLS upgrade. + if not old_wsuri.secure and new_wsuri.secure: + factory.keywords["secure"] = True + self._create_connection.keywords.setdefault("ssl", True) + # Replace secure, host, and port arguments of the protocol factory. + factory = functools.partial( + factory.func, + *factory.args, + **dict(factory.keywords, host=new_wsuri.host, port=new_wsuri.port), + ) + # Replace secure, host, and port arguments of create_connection. + self._create_connection = functools.partial( + self._create_connection.func, + *(factory, new_wsuri.host, new_wsuri.port), + **self._create_connection.keywords, + ) + + # Set the new WebSocket URI. This suffices for same-origin redirects. + self._uri = new_uri + self._wsuri = new_wsuri + + # async for ... in connect(...): + + BACKOFF_INITIAL = float(os.environ.get("WEBSOCKETS_BACKOFF_INITIAL_DELAY", "5")) + BACKOFF_MIN = float(os.environ.get("WEBSOCKETS_BACKOFF_MIN_DELAY", "3.1")) + BACKOFF_MAX = float(os.environ.get("WEBSOCKETS_BACKOFF_MAX_DELAY", "90.0")) + BACKOFF_FACTOR = float(os.environ.get("WEBSOCKETS_BACKOFF_FACTOR", "1.618")) + + async def __aiter__(self) -> AsyncIterator[WebSocketClientProtocol]: + backoff_delay = self.BACKOFF_MIN / self.BACKOFF_FACTOR + while True: + try: + async with self as protocol: + yield protocol + except Exception as exc: + # Add a random initial delay between 0 and 5 seconds. + # See 7.2.3. Recovering from Abnormal Closure in RFC 6455. + if backoff_delay == self.BACKOFF_MIN: + initial_delay = random.random() * self.BACKOFF_INITIAL + self.logger.info( + "connect failed; reconnecting in %.1f seconds: %s", + initial_delay, + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(initial_delay) + else: + self.logger.info( + "connect failed again; retrying in %d seconds: %s", + int(backoff_delay), + traceback.format_exception_only(exc)[0].strip(), + ) + await asyncio.sleep(int(backoff_delay)) + # Increase delay with truncated exponential backoff. + backoff_delay = backoff_delay * self.BACKOFF_FACTOR + backoff_delay = min(backoff_delay, self.BACKOFF_MAX) + continue + else: + # Connection succeeded - reset backoff delay + backoff_delay = self.BACKOFF_MIN + + # async with connect(...) as ...: + + async def __aenter__(self) -> WebSocketClientProtocol: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + await self.protocol.close() + + # ... = await connect(...) + + def __await__(self) -> Generator[Any, None, WebSocketClientProtocol]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketClientProtocol: + async with asyncio_timeout(self.open_timeout): + for _redirects in range(self.MAX_REDIRECTS_ALLOWED): + _transport, protocol = await self._create_connection() + try: + await protocol.handshake( + self._wsuri, + origin=protocol.origin, + available_extensions=protocol.available_extensions, + available_subprotocols=protocol.available_subprotocols, + extra_headers=protocol.extra_headers, + ) + except RedirectHandshake as exc: + protocol.fail_connection() + await protocol.wait_closed() + self.handle_redirect(exc.uri) + # Avoid leaking a connected socket when the handshake fails. + except (Exception, asyncio.CancelledError): + protocol.fail_connection() + await protocol.wait_closed() + raise + else: + self.protocol = protocol + return protocol + else: + raise SecurityError("too many redirects") + + # ... = yield from connect(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +connect = Connect + + +def unix_connect( + path: str | None = None, + uri: str = "ws://localhost/", + **kwargs: Any, +) -> Connect: + """ + Similar to :func:`connect`, but for connecting to a Unix socket. + + This function builds upon the event loop's + :meth:`~asyncio.loop.create_unix_connection` method. + + It is only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server; the host is used in the TLS + handshake for secure connections and in the ``Host`` header. + + """ + return connect(uri=uri, path=path, unix=True, **kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/exceptions.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/exceptions.py new file mode 100644 index 0000000000000000000000000000000000000000..29a2525b4e73b788f773682ce0b88e13eafc6e26 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/exceptions.py @@ -0,0 +1,71 @@ +import http + +from .. import datastructures +from ..exceptions import ( + InvalidHandshake, + # InvalidMessage was incorrectly moved here in versions 14.0 and 14.1. + InvalidMessage, # noqa: F401 + ProtocolError as WebSocketProtocolError, # noqa: F401 +) +from ..typing import StatusLike + + +class InvalidStatusCode(InvalidHandshake): + """ + Raised when a handshake response status code is invalid. + + """ + + def __init__(self, status_code: int, headers: datastructures.Headers) -> None: + self.status_code = status_code + self.headers = headers + + def __str__(self) -> str: + return f"server rejected WebSocket connection: HTTP {self.status_code}" + + +class AbortHandshake(InvalidHandshake): + """ + Raised to abort the handshake on purpose and return an HTTP response. + + This exception is an implementation detail. + + The public API is + :meth:`~websockets.legacy.server.WebSocketServerProtocol.process_request`. + + Attributes: + status (~http.HTTPStatus): HTTP status code. + headers (Headers): HTTP response headers. + body (bytes): HTTP response body. + """ + + def __init__( + self, + status: StatusLike, + headers: datastructures.HeadersLike, + body: bytes = b"", + ) -> None: + # If a user passes an int instead of an HTTPStatus, fix it automatically. + self.status = http.HTTPStatus(status) + self.headers = datastructures.Headers(headers) + self.body = body + + def __str__(self) -> str: + return ( + f"HTTP {self.status:d}, {len(self.headers)} headers, {len(self.body)} bytes" + ) + + +class RedirectHandshake(InvalidHandshake): + """ + Raised when a handshake gets redirected. + + This exception is an implementation detail. + + """ + + def __init__(self, uri: str) -> None: + self.uri = uri + + def __str__(self) -> str: + return f"redirect to {self.uri}" diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/framing.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/framing.py new file mode 100644 index 0000000000000000000000000000000000000000..452d2fb34dc45577401321ce76d6a030d2e49597 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/framing.py @@ -0,0 +1,224 @@ +from __future__ import annotations + +import struct +from collections.abc import Awaitable, Sequence +from typing import Any, Callable, NamedTuple + +from .. import extensions, frames +from ..exceptions import PayloadTooBig, ProtocolError +from ..typing import BytesLike, DataLike + + +try: + from ..speedups import apply_mask +except ImportError: + from ..utils import apply_mask + + +class Frame(NamedTuple): + fin: bool + opcode: frames.Opcode + data: BytesLike + rsv1: bool = False + rsv2: bool = False + rsv3: bool = False + + @property + def new_frame(self) -> frames.Frame: + return frames.Frame( + self.opcode, + self.data, + self.fin, + self.rsv1, + self.rsv2, + self.rsv3, + ) + + def __str__(self) -> str: + return str(self.new_frame) + + def check(self) -> None: + return self.new_frame.check() + + @classmethod + async def read( + cls, + reader: Callable[[int], Awaitable[bytes]], + *, + mask: bool, + max_size: int | None = None, + extensions: Sequence[extensions.Extension] | None = None, + ) -> Frame: + """ + Read a WebSocket frame. + + Args: + reader: Coroutine that reads exactly the requested number of + bytes, unless the end of file is reached. + mask: Whether the frame should be masked i.e. whether the read + happens on the server side. + max_size: Maximum payload size in bytes. + extensions: List of extensions, applied in reverse order. + + Raises: + PayloadTooBig: If the frame exceeds ``max_size``. + ProtocolError: If the frame contains incorrect values. + + """ + + # Read the header. + data = await reader(2) + head1, head2 = struct.unpack("!BB", data) + + # While not Pythonic, this is marginally faster than calling bool(). + fin = True if head1 & 0b10000000 else False + rsv1 = True if head1 & 0b01000000 else False + rsv2 = True if head1 & 0b00100000 else False + rsv3 = True if head1 & 0b00010000 else False + + try: + opcode = frames.Opcode(head1 & 0b00001111) + except ValueError as exc: + raise ProtocolError("invalid opcode") from exc + + if (True if head2 & 0b10000000 else False) != mask: + raise ProtocolError("incorrect masking") + + length = head2 & 0b01111111 + if length == 126: + data = await reader(2) + (length,) = struct.unpack("!H", data) + elif length == 127: + data = await reader(8) + (length,) = struct.unpack("!Q", data) + if max_size is not None and length > max_size: + raise PayloadTooBig(length, max_size) + if mask: + mask_bits = await reader(4) + + # Read the data. + data = await reader(length) + if mask: + data = apply_mask(data, mask_bits) + + new_frame = frames.Frame(opcode, data, fin, rsv1, rsv2, rsv3) + + if extensions is None: + extensions = [] + for extension in reversed(extensions): + new_frame = extension.decode(new_frame, max_size=max_size) + + new_frame.check() + + return cls( + new_frame.fin, + new_frame.opcode, + new_frame.data, + new_frame.rsv1, + new_frame.rsv2, + new_frame.rsv3, + ) + + def write( + self, + write: Callable[[bytes], Any], + *, + mask: bool, + extensions: Sequence[extensions.Extension] | None = None, + ) -> None: + """ + Write a WebSocket frame. + + Args: + frame: Frame to write. + write: Function that writes bytes. + mask: Whether the frame should be masked i.e. whether the write + happens on the client side. + extensions: List of extensions, applied in order. + + Raises: + ProtocolError: If the frame contains incorrect values. + + """ + # The frame is written in a single call to write in order to prevent + # TCP fragmentation. See #68 for details. This also makes it safe to + # send frames concurrently from multiple coroutines. + write(self.new_frame.serialize(mask=mask, extensions=extensions)) + + +def prepare_data(data: DataLike) -> tuple[int, BytesLike]: + """ + Convert a string or byte-like object to an opcode and a bytes-like object. + + This function is designed for data frames. + + If ``data`` is a :class:`str`, return ``OP_TEXT`` and a :class:`bytes` + object encoding ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return ``OP_BINARY`` and a bytes-like + object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return frames.Opcode.TEXT, data.encode() + elif isinstance(data, BytesLike): + return frames.Opcode.BINARY, data + else: + raise TypeError("data must be str or bytes-like") + + +def prepare_ctrl(data: DataLike) -> bytes: + """ + Convert a string or byte-like object to bytes. + + This function is designed for ping and pong frames. + + If ``data`` is a :class:`str`, return a :class:`bytes` object encoding + ``data`` in UTF-8. + + If ``data`` is a bytes-like object, return a :class:`bytes` object. + + Raises: + TypeError: If ``data`` doesn't have a supported type. + + """ + if isinstance(data, str): + return data.encode() + elif isinstance(data, BytesLike): + return bytes(data) + else: + raise TypeError("data must be str or bytes-like") + + +# Backwards compatibility with previously documented public APIs +encode_data = prepare_ctrl + +# Backwards compatibility with previously documented public APIs +from ..frames import Close # noqa: E402 F401, I001 + + +def parse_close(data: bytes) -> tuple[int, str]: + """ + Parse the payload from a close frame. + + Returns: + Close code and reason. + + Raises: + ProtocolError: If data is ill-formed. + UnicodeDecodeError: If the reason isn't valid UTF-8. + + """ + close = Close.parse(data) + return close.code, close.reason + + +def serialize_close(code: int, reason: str) -> bytes: + """ + Serialize the payload for a close frame. + + """ + return Close(code, reason).serialize() diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/handshake.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/handshake.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7157c010720733ca42d363cd810c354bf9d221 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/handshake.py @@ -0,0 +1,158 @@ +from __future__ import annotations + +import base64 +import binascii + +from ..datastructures import Headers, MultipleValuesError +from ..exceptions import InvalidHeader, InvalidHeaderValue, InvalidUpgrade +from ..headers import parse_connection, parse_upgrade +from ..typing import ConnectionOption, UpgradeProtocol +from ..utils import accept_key as accept, generate_key + + +__all__ = ["build_request", "check_request", "build_response", "check_response"] + + +def build_request(headers: Headers) -> str: + """ + Build a handshake request to send to the server. + + Update request headers passed in argument. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`check_response`. + + """ + key = generate_key() + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Key"] = key + headers["Sec-WebSocket-Version"] = "13" + return key + + +def check_request(headers: Headers) -> str: + """ + Check a handshake request received from the client. + + This function doesn't verify that the request is an HTTP/1.1 or higher GET + request and doesn't perform ``Host`` and ``Origin`` checks. These controls + are usually performed earlier in the HTTP request handling code. They're + the responsibility of the caller. + + Args: + headers: Handshake request headers. + + Returns: + ``key`` that must be passed to :func:`build_response`. + + Raises: + InvalidHandshake: If the handshake request is invalid. + Then, the server must return a 400 Bad Request error. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", ", ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_key = headers["Sec-WebSocket-Key"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Key") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Key", "multiple values") from exc + + try: + raw_key = base64.b64decode(s_w_key.encode(), validate=True) + except binascii.Error as exc: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) from exc + if len(raw_key) != 16: + raise InvalidHeaderValue("Sec-WebSocket-Key", s_w_key) + + try: + s_w_version = headers["Sec-WebSocket-Version"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Version") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Version", "multiple values") from exc + + if s_w_version != "13": + raise InvalidHeaderValue("Sec-WebSocket-Version", s_w_version) + + return s_w_key + + +def build_response(headers: Headers, key: str) -> None: + """ + Build a handshake response to send to the client. + + Update response headers passed in argument. + + Args: + headers: Handshake response headers. + key: Returned by :func:`check_request`. + + """ + headers["Upgrade"] = "websocket" + headers["Connection"] = "Upgrade" + headers["Sec-WebSocket-Accept"] = accept(key) + + +def check_response(headers: Headers, key: str) -> None: + """ + Check a handshake response received from the server. + + This function doesn't verify that the response is an HTTP/1.1 or higher + response with a 101 status code. These controls are the responsibility of + the caller. + + Args: + headers: Handshake response headers. + key: Returned by :func:`build_request`. + + Raises: + InvalidHandshake: If the handshake response is invalid. + + """ + connection: list[ConnectionOption] = sum( + [parse_connection(value) for value in headers.get_all("Connection")], [] + ) + + if not any(value.lower() == "upgrade" for value in connection): + raise InvalidUpgrade("Connection", " ".join(connection)) + + upgrade: list[UpgradeProtocol] = sum( + [parse_upgrade(value) for value in headers.get_all("Upgrade")], [] + ) + + # For compatibility with non-strict implementations, ignore case when + # checking the Upgrade header. The RFC always uses "websocket", except + # in section 11.2. (IANA registration) where it uses "WebSocket". + if not (len(upgrade) == 1 and upgrade[0].lower() == "websocket"): + raise InvalidUpgrade("Upgrade", ", ".join(upgrade)) + + try: + s_w_accept = headers["Sec-WebSocket-Accept"] + except KeyError as exc: + raise InvalidHeader("Sec-WebSocket-Accept") from exc + except MultipleValuesError as exc: + raise InvalidHeader("Sec-WebSocket-Accept", "multiple values") from exc + + if s_w_accept != accept(key): + raise InvalidHeaderValue("Sec-WebSocket-Accept", s_w_accept) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/http.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/http.py new file mode 100644 index 0000000000000000000000000000000000000000..a7c8a927e177d36f6a54bcc293dc853e2e15e736 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/http.py @@ -0,0 +1,201 @@ +from __future__ import annotations + +import asyncio +import os +import re + +from ..datastructures import Headers +from ..exceptions import SecurityError + + +__all__ = ["read_request", "read_response"] + +MAX_NUM_HEADERS = int(os.environ.get("WEBSOCKETS_MAX_NUM_HEADERS", "128")) +MAX_LINE_LENGTH = int(os.environ.get("WEBSOCKETS_MAX_LINE_LENGTH", "8192")) + + +def d(value: bytes) -> str: + """ + Decode a bytestring for interpolating into an error message. + + """ + return value.decode(errors="backslashreplace") + + +# See https://datatracker.ietf.org/doc/html/rfc7230#appendix-B. + +# Regex for validating header names. + +_token_re = re.compile(rb"[-!#$%&\'*+.^_`|~0-9a-zA-Z]+") + +# Regex for validating header values. + +# We don't attempt to support obsolete line folding. + +# Include HTAB (\x09), SP (\x20), VCHAR (\x21-\x7e), obs-text (\x80-\xff). + +# The ABNF is complicated because it attempts to express that optional +# whitespace is ignored. We strip whitespace and don't revalidate that. + +# See also https://www.rfc-editor.org/errata_search.php?rfc=7230&eid=4189 + +_value_re = re.compile(rb"[\x09\x20-\x7e\x80-\xff]*") + + +async def read_request(stream: asyncio.StreamReader) -> tuple[str, Headers]: + """ + Read an HTTP/1.1 GET request and return ``(path, headers)``. + + ``path`` isn't URL-decoded or validated in any way. + + ``path`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the request body because + WebSocket handshake requests don't have one. If the request contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the request from. + + Raises: + EOFError: If the connection is closed without a full HTTP request. + SecurityError: If the request exceeds a security limit. + ValueError: If the request isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.1 + + # Parsing is simple because fixed values are expected for method and + # version and because path isn't checked. Since WebSocket software tends + # to implement HTTP/1.1 strictly, there's little need for lenient parsing. + + try: + request_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP request line") from exc + + try: + method, raw_path, version = request_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP request line: {d(request_line)}") from None + + if method != b"GET": + raise ValueError(f"unsupported HTTP method: {d(method)}") + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + path = raw_path.decode("ascii", "surrogateescape") + + headers = await read_headers(stream) + + return path, headers + + +async def read_response(stream: asyncio.StreamReader) -> tuple[int, str, Headers]: + """ + Read an HTTP/1.1 response and return ``(status_code, reason, headers)``. + + ``reason`` and ``headers`` are expected to contain only ASCII characters. + Other characters are represented with surrogate escapes. + + :func:`read_request` doesn't attempt to read the response body because + WebSocket handshake responses don't have one. If the response contains a + body, it may be read from ``stream`` after this coroutine returns. + + Args: + stream: Input to read the response from. + + Raises: + EOFError: If the connection is closed without a full HTTP response. + SecurityError: If the response exceeds a security limit. + ValueError: If the response isn't well formatted. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2 + + # As in read_request, parsing is simple because a fixed value is expected + # for version, status_code is a 3-digit number, and reason can be ignored. + + try: + status_line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP status line") from exc + + try: + version, raw_status_code, raw_reason = status_line.split(b" ", 2) + except ValueError: # not enough values to unpack (expected 3, got 1-2) + raise ValueError(f"invalid HTTP status line: {d(status_line)}") from None + + if version != b"HTTP/1.1": + raise ValueError(f"unsupported HTTP version: {d(version)}") + try: + status_code = int(raw_status_code) + except ValueError: # invalid literal for int() with base 10 + raise ValueError(f"invalid HTTP status code: {d(raw_status_code)}") from None + if not 100 <= status_code < 1000: + raise ValueError(f"unsupported HTTP status code: {d(raw_status_code)}") + if not _value_re.fullmatch(raw_reason): + raise ValueError(f"invalid HTTP reason phrase: {d(raw_reason)}") + reason = raw_reason.decode() + + headers = await read_headers(stream) + + return status_code, reason, headers + + +async def read_headers(stream: asyncio.StreamReader) -> Headers: + """ + Read HTTP headers from ``stream``. + + Non-ASCII characters are represented with surrogate escapes. + + """ + # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 + + # We don't attempt to support obsolete line folding. + + headers = Headers() + for _ in range(MAX_NUM_HEADERS + 1): + try: + line = await read_line(stream) + except EOFError as exc: + raise EOFError("connection closed while reading HTTP headers") from exc + if line == b"": + break + + try: + raw_name, raw_value = line.split(b":", 1) + except ValueError: # not enough values to unpack (expected 2, got 1) + raise ValueError(f"invalid HTTP header line: {d(line)}") from None + if not _token_re.fullmatch(raw_name): + raise ValueError(f"invalid HTTP header name: {d(raw_name)}") + raw_value = raw_value.strip(b" \t") + if not _value_re.fullmatch(raw_value): + raise ValueError(f"invalid HTTP header value: {d(raw_value)}") + + name = raw_name.decode("ascii") # guaranteed to be ASCII at this point + value = raw_value.decode("ascii", "surrogateescape") + headers[name] = value + + else: + raise SecurityError("too many HTTP headers") + + return headers + + +async def read_line(stream: asyncio.StreamReader) -> bytes: + """ + Read a single line from ``stream``. + + CRLF is stripped from the return value. + + """ + # Security: this is bounded by the StreamReader's limit (default = 32 KiB). + line = await stream.readline() + # Security: this guarantees header values are small (hard-coded = 8 KiB) + if len(line) > MAX_LINE_LENGTH: + raise SecurityError("line too long") + # Not mandatory but safe - https://datatracker.ietf.org/doc/html/rfc7230#section-3.5 + if not line.endswith(b"\r\n"): + raise EOFError("line without CRLF") + return line[:-2] diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/protocol.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..ab4ec6bcec9ee886a97815239376dff0d166d8f9 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/protocol.py @@ -0,0 +1,1635 @@ +from __future__ import annotations + +import asyncio +import codecs +import collections +import logging +import random +import ssl +import struct +import sys +import time +import traceback +import uuid +import warnings +from collections.abc import AsyncIterable, AsyncIterator, Awaitable, Iterable, Mapping +from typing import Any, Callable, Deque, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers +from ..exceptions import ( + ConnectionClosed, + ConnectionClosedError, + ConnectionClosedOK, + InvalidState, + PayloadTooBig, + ProtocolError, +) +from ..extensions import Extension +from ..frames import ( + OK_CLOSE_CODES, + OP_BINARY, + OP_CLOSE, + OP_CONT, + OP_PING, + OP_PONG, + OP_TEXT, + Close, + CloseCode, + Opcode, +) +from ..protocol import State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .framing import Frame, prepare_ctrl, prepare_data + + +__all__ = ["WebSocketCommonProtocol"] + + +# In order to ensure consistency, the code always checks the current value of +# WebSocketCommonProtocol.state before assigning a new value and never yields +# between the check and the assignment. + + +class WebSocketCommonProtocol(asyncio.Protocol): + """ + WebSocket connection. + + :class:`WebSocketCommonProtocol` provides APIs shared between WebSocket + servers and clients. You shouldn't use it directly. Instead, use + :class:`~websockets.legacy.client.WebSocketClientProtocol` or + :class:`~websockets.legacy.server.WebSocketServerProtocol`. + + This documentation focuses on low-level details that aren't covered in the + documentation of :class:`~websockets.legacy.client.WebSocketClientProtocol` + and :class:`~websockets.legacy.server.WebSocketServerProtocol` for the sake + of simplicity. + + Once the connection is open, a Ping_ frame is sent every ``ping_interval`` + seconds. This serves as a keepalive. It helps keeping the connection open, + especially in the presence of proxies with short timeouts on inactive + connections. Set ``ping_interval`` to :obj:`None` to disable this behavior. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + If the corresponding Pong_ frame isn't received within ``ping_timeout`` + seconds, the connection is considered unusable and is closed with code 1011. + This ensures that the remote endpoint remains responsive. Set + ``ping_timeout`` to :obj:`None` to disable this behavior. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + See the discussion of :doc:`keepalive <../../topics/keepalive>` for details. + + The ``close_timeout`` parameter defines a maximum wait time for completing + the closing handshake and terminating the TCP connection. For legacy + reasons, :meth:`close` completes in at most ``5 * close_timeout`` seconds + for clients and ``4 * close_timeout`` for servers. + + ``close_timeout`` is a parameter of the protocol because websockets usually + calls :meth:`close` implicitly upon exit: + + * on the client side, when using :func:`~websockets.legacy.client.connect` + as a context manager; + * on the server side, when the connection handler terminates. + + To apply a timeout to any other API, wrap it in :func:`~asyncio.timeout` or + :func:`~asyncio.wait_for`. + + The ``max_size`` parameter enforces the maximum size for incoming messages + in bytes. The default value is 1 MiB. If a larger message is received, + :meth:`recv` will raise :exc:`~websockets.exceptions.ConnectionClosedError` + and the connection will be closed with code 1009. + + The ``max_queue`` parameter sets the maximum length of the queue that + holds incoming messages. The default value is ``32``. Messages are added + to an in-memory queue when they're received; then :meth:`recv` pops from + that queue. In order to prevent excessive memory consumption when + messages are received faster than they can be processed, the queue must + be bounded. If the queue fills up, the protocol stops processing incoming + data until :meth:`recv` is called. In this situation, various receive + buffers (at least in :mod:`asyncio` and in the OS) will fill up, then the + TCP receive window will shrink, slowing down transmission to avoid packet + loss. + + Since Python can use up to 4 bytes of memory to represent a single + character, each connection may use up to ``4 * max_size * max_queue`` + bytes of memory to store incoming messages. By default, this is 128 MiB. + You may want to lower the limits, depending on your application's + requirements. + + The ``read_limit`` argument sets the high-water limit of the buffer for + incoming bytes. The low-water limit is half the high-water limit. The + default value is 64 KiB, half of asyncio's default (based on the current + implementation of :class:`~asyncio.StreamReader`). + + The ``write_limit`` argument sets the high-water limit of the buffer for + outgoing bytes. The low-water limit is a quarter of the high-water limit. + The default value is 64 KiB, equal to asyncio's default (based on the + current implementation of ``FlowControlMixin``). + + See the discussion of :doc:`memory usage <../../topics/memory>` for details. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.protocol")``. + See the :doc:`logging guide <../../topics/logging>` for details. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + For legacy reasons, the actual timeout is 4 or 5 times larger. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. + max_queue: Maximum number of incoming messages in receive buffer. + :obj:`None` disables the limit. + read_limit: High-water mark of read buffer in bytes. + write_limit: High-water mark of write buffer in bytes. + + """ + + # There are only two differences between the client-side and server-side + # behavior: masking the payload and closing the underlying TCP connection. + # Set is_client = True/False and side = "client"/"server" to pick a side. + is_client: bool + side: str = "undefined" + + def __init__( + self, + *, + logger: LoggerLike | None = None, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + # The following arguments are kept only for backwards compatibility. + host: str | None = None, + port: int | None = None, + secure: bool | None = None, + legacy_recv: bool = False, + loop: asyncio.AbstractEventLoop | None = None, + timeout: float | None = None, + ) -> None: + if legacy_recv: # pragma: no cover + warnings.warn("legacy_recv is deprecated", DeprecationWarning) + + # Backwards compatibility: close_timeout used to be called timeout. + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: the loop parameter used to be supported. + if loop is None: + loop = asyncio.get_event_loop() + else: + warnings.warn("remove loop argument", DeprecationWarning) + + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + self.max_size = max_size + self.max_queue = max_queue + self.read_limit = read_limit + self.write_limit = write_limit + + # Unique identifier. For logs. + self.id: uuid.UUID = uuid.uuid4() + """Unique identifier of the connection. Useful in logs.""" + + # Logger or LoggerAdapter for this connection. + if logger is None: + logger = logging.getLogger("websockets.protocol") + self.logger: LoggerLike = logging.LoggerAdapter(logger, {"websocket": self}) + """Logger for this connection.""" + + # Track if DEBUG is enabled. Shortcut logging calls if it isn't. + self.debug = logger.isEnabledFor(logging.DEBUG) + + self.loop = loop + + self._host = host + self._port = port + self._secure = secure + self.legacy_recv = legacy_recv + + # Configure read buffer limits. The high-water limit is defined by + # ``self.read_limit``. The ``limit`` argument controls the line length + # limit and half the buffer limit of :class:`~asyncio.StreamReader`. + # That's why it must be set to half of ``self.read_limit``. + self.reader = asyncio.StreamReader(limit=read_limit // 2, loop=loop) + + # Copied from asyncio.FlowControlMixin + self._paused = False + self._drain_waiter: asyncio.Future[None] | None = None + + # This class implements the data transfer and closing handshake, which + # are shared between the client-side and the server-side. + # Subclasses implement the opening handshake and, on success, execute + # :meth:`connection_open` to change the state to OPEN. + self.state = State.CONNECTING + if self.debug: + self.logger.debug("= connection is CONNECTING") + + # HTTP protocol parameters. + self.path: str + """Path of the opening handshake request.""" + self.request_headers: Headers + """Opening handshake request headers.""" + self.response_headers: Headers + """Opening handshake response headers.""" + + # WebSocket protocol parameters. + self.extensions: list[Extension] = [] + self.subprotocol: Subprotocol | None = None + """Subprotocol, if one was negotiated.""" + + # Close code and reason, set when a close frame is sent or received. + self.close_rcvd: Close | None = None + self.close_sent: Close | None = None + self.close_rcvd_then_sent: bool | None = None + + # Completed when the connection state becomes CLOSED. Translates the + # :meth:`connection_lost` callback to a :class:`~asyncio.Future` + # that can be awaited. (Other :class:`~asyncio.Protocol` callbacks are + # translated by ``self.stream_reader``). + self.connection_lost_waiter: asyncio.Future[None] = loop.create_future() + + # Queue of received messages. + self.messages: Deque[Data] = collections.deque() + self._pop_message_waiter: asyncio.Future[None] | None = None + self._put_message_waiter: asyncio.Future[None] | None = None + + # Protect sending fragmented messages. + self._fragmented_message_waiter: asyncio.Future[None] | None = None + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pings: dict[bytes, tuple[asyncio.Future[float], float]] = {} + + self.latency: float = 0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Task running the data transfer. + self.transfer_data_task: asyncio.Task[None] + + # Exception that occurred during data transfer, if any. + self.transfer_data_exc: BaseException | None = None + + # Task sending keepalive pings. + self.keepalive_ping_task: asyncio.Task[None] + + # Task closing the TCP connection. + self.close_connection_task: asyncio.Task[None] + + # Copied from asyncio.FlowControlMixin + async def _drain_helper(self) -> None: # pragma: no cover + if self.connection_lost_waiter.done(): + raise ConnectionResetError("Connection lost") + if not self._paused: + return + waiter = self._drain_waiter + assert waiter is None or waiter.cancelled() + waiter = self.loop.create_future() + self._drain_waiter = waiter + await waiter + + # Copied from asyncio.StreamWriter + async def _drain(self) -> None: # pragma: no cover + if self.reader is not None: + exc = self.reader.exception() + if exc is not None: + raise exc + if self.transport is not None: + if self.transport.is_closing(): + # Yield to the event loop so connection_lost() may be + # called. Without this, _drain_helper() would return + # immediately, and code that calls + # write(...); yield from drain() + # in a loop would never call connection_lost(), so it + # would not see an error when the socket is closed. + await asyncio.sleep(0) + await self._drain_helper() + + def connection_open(self) -> None: + """ + Callback when the WebSocket opening handshake completes. + + Enter the OPEN state and start the data transfer phase. + + """ + # 4.1. The WebSocket Connection is Established. + assert self.state is State.CONNECTING + self.state = State.OPEN + if self.debug: + self.logger.debug("= connection is OPEN") + # Start the task that receives incoming WebSocket messages. + self.transfer_data_task = self.loop.create_task(self.transfer_data()) + # Start the task that sends pings at regular intervals. + self.keepalive_ping_task = self.loop.create_task(self.keepalive_ping()) + # Start the task that eventually closes the TCP connection. + self.close_connection_task = self.loop.create_task(self.close_connection()) + + @property + def host(self) -> str | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[0] instead of host", DeprecationWarning) + return self._host + + @property + def port(self) -> int | None: + alternative = "remote_address" if self.is_client else "local_address" + warnings.warn(f"use {alternative}[1] instead of port", DeprecationWarning) + return self._port + + @property + def secure(self) -> bool | None: + warnings.warn("don't use secure", DeprecationWarning) + return self._secure + + # Public API + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getsockname`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("sockname") + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family; + see :meth:`~socket.socket.getpeername`. + + :obj:`None` if the TCP connection isn't established yet. + + """ + try: + transport = self.transport + except AttributeError: + return None + else: + return transport.get_extra_info("peername") + + @property + def open(self) -> bool: + """ + :obj:`True` when the connection is open; :obj:`False` otherwise. + + This attribute may be used to detect disconnections. However, this + approach is discouraged per the EAFP_ principle. Instead, you should + handle :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + .. _EAFP: https://docs.python.org/3/glossary.html#term-eafp + + """ + return self.state is State.OPEN and not self.transfer_data_task.done() + + @property + def closed(self) -> bool: + """ + :obj:`True` when the connection is closed; :obj:`False` otherwise. + + Be aware that both :attr:`open` and :attr:`closed` are :obj:`False` + during the opening and closing sequences. + + """ + return self.state is State.CLOSED + + @property + def close_code(self) -> int | None: + """ + WebSocket close code, defined in `section 7.1.5 of RFC 6455`_. + + .. _section 7.1.5 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return CloseCode.ABNORMAL_CLOSURE + else: + return self.close_rcvd.code + + @property + def close_reason(self) -> str | None: + """ + WebSocket close reason, defined in `section 7.1.6 of RFC 6455`_. + + .. _section 7.1.6 of RFC 6455: + https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + + :obj:`None` if the connection isn't closed yet. + + """ + if self.state is not State.CLOSED: + return None + elif self.close_rcvd is None: + return "" + else: + return self.close_rcvd.reason + + async def __aiter__(self) -> AsyncIterator[Data]: + """ + Iterate on incoming messages. + + The iterator exits normally when the connection is closed with the close + code 1000 (OK) or 1001 (going away) or without a close code. + + It raises a :exc:`~websockets.exceptions.ConnectionClosedError` + exception when the connection is closed with any other code. + + """ + try: + while True: + yield await self.recv() + except ConnectionClosedOK: + return + + async def recv(self) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + Canceling :meth:`recv` is safe. There's no risk of losing the next + message. The next invocation of :meth:`recv` will return it. + + This makes it possible to enforce a timeout by wrapping :meth:`recv` in + :func:`~asyncio.timeout` or :func:`~asyncio.wait_for`. + + Returns: + A string (:class:`str`) for a Text_ frame. A bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If two coroutines call :meth:`recv` concurrently. + + """ + if self._pop_message_waiter is not None: + raise RuntimeError( + "cannot call recv while another coroutine " + "is already waiting for the next message" + ) + + # Don't await self.ensure_open() here: + # - messages could be available in the queue even if the connection + # is closed; + # - messages could be received before the closing frame even if the + # connection is closing. + + # Wait until there's a message in the queue (if necessary) or the + # connection is closed. + while len(self.messages) <= 0: + pop_message_waiter: asyncio.Future[None] = self.loop.create_future() + self._pop_message_waiter = pop_message_waiter + try: + # If asyncio.wait() is canceled, it doesn't cancel + # pop_message_waiter and self.transfer_data_task. + await asyncio.wait( + [pop_message_waiter, self.transfer_data_task], + return_when=asyncio.FIRST_COMPLETED, + ) + finally: + self._pop_message_waiter = None + + # If asyncio.wait(...) exited because self.transfer_data_task + # completed before receiving a new message, raise a suitable + # exception (or return None if legacy_recv is enabled). + if not pop_message_waiter.done(): + if self.legacy_recv: + return None # type: ignore + else: + # Wait until the connection is closed to raise + # ConnectionClosed with the correct code and reason. + await self.ensure_open() + + # Pop a message from the queue. + message = self.messages.popleft() + + # Notify transfer_data(). + if self._put_message_waiter is not None: + self._put_message_waiter.set_result(None) + self._put_message_waiter = None + + return message + + async def send( + self, + message: DataLike | Iterable[DataLike] | AsyncIterable[DataLike], + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :meth:`send` also accepts an iterable or an asynchronous iterable of + strings, bytestrings, or bytes-like objects to enable fragmentation_. + Each item is treated as a message fragment and sent in its own frame. + All items must be of the same type, or else :meth:`send` will raise a + :exc:`TypeError` and the connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you want to send the keys of a dict-like object as fragments, call + its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + Canceling :meth:`send` is discouraged. Instead, you should close the + connection with :meth:`close`. Indeed, there are only two situations + where :meth:`send` may yield control to the event loop and then get + canceled; in both cases, :meth:`close` has the same effect and is + more clear: + + 1. The write buffer is full. If you don't want to wait until enough + data is sent, your only alternative is to close the connection. + :meth:`close` will likely time out then abort the TCP connection. + 2. ``message`` is an asynchronous iterator that yields control. + Stopping in the middle of a fragmented message will cause a + protocol error and the connection will be closed. + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + TypeError: If ``message`` doesn't have a supported type. + + """ + await self.ensure_open() + + # While sending a fragmented message, prevent sending other messages + # until all fragments are sent. + while self._fragmented_message_waiter is not None: + await asyncio.shield(self._fragmented_message_waiter) + + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, (str, bytes, bytearray, memoryview)): + opcode, data = prepare_data(message) + await self.write_frame(True, opcode, data) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + iter_message = iter(message) + try: + fragment = next(iter_message) + except StopIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + for fragment in iter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + # Fragmented message -- asynchronous iterator + + elif isinstance(message, AsyncIterable): + # Implement aiter_message = aiter(message) without aiter + # Work around https://github.com/python/mypy/issues/5738 + aiter_message = cast( + Callable[[AsyncIterable[DataLike]], AsyncIterator[DataLike]], + type(message).__aiter__, + )(message) + try: + # Implement fragment = anext(aiter_message) without anext + # Work around https://github.com/python/mypy/issues/5738 + fragment = await cast( + Callable[[AsyncIterator[DataLike]], Awaitable[DataLike]], + type(aiter_message).__anext__, + )(aiter_message) + except StopAsyncIteration: + return + opcode, data = prepare_data(fragment) + + self._fragmented_message_waiter = self.loop.create_future() + try: + # First fragment. + await self.write_frame(False, opcode, data) + + # Other fragments. + async for fragment in aiter_message: + confirm_opcode, data = prepare_data(fragment) + if confirm_opcode != opcode: + raise TypeError("data contains inconsistent types") + await self.write_frame(False, OP_CONT, data) + + # Final fragment. + await self.write_frame(True, OP_CONT, b"") + + except (Exception, asyncio.CancelledError): + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + self.fail_connection(CloseCode.INTERNAL_ERROR) + raise + + finally: + self._fragmented_message_waiter.set_result(None) + self._fragmented_message_waiter = None + + else: + raise TypeError("data must be str, bytes-like, or iterable") + + async def close( + self, + code: int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. As a consequence, there's no need + to await :meth:`wait_closed` after :meth:`close`. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Wrapping :func:`close` in :func:`~asyncio.create_task` is safe, given + that errors during connection termination aren't particularly useful. + + Canceling :meth:`close` is discouraged. If it takes too long, you can + set a shorter ``close_timeout``. If you don't want to wait, let the + Python process exit, then the OS will take care of closing the TCP + connection. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + async with asyncio_timeout(self.close_timeout): + await self.write_close_frame(Close(code, reason)) + except asyncio.TimeoutError: + # If the close frame cannot be sent because the send buffers + # are full, the closing handshake won't complete anyway. + # Fail the connection to shut down faster. + self.fail_connection() + + # If no close frame is received within the timeout, asyncio_timeout() + # cancels the data transfer task and raises TimeoutError. + + # If close() is called multiple times concurrently and one of these + # calls hits the timeout, the data transfer task will be canceled. + # Other calls will receive a CancelledError here. + + try: + # If close() is canceled during the wait, self.transfer_data_task + # is canceled before the timeout elapses. + async with asyncio_timeout(self.close_timeout): + await self.transfer_data_task + except (asyncio.TimeoutError, asyncio.CancelledError): + pass + + # Wait for the close connection task to close the TCP connection. + await asyncio.shield(self.close_connection_task) + + async def wait_closed(self) -> None: + """ + Wait until the connection is closed. + + This coroutine is identical to the :attr:`closed` attribute, except it + can be awaited. + + This can make it easier to detect connection termination, regardless + of its cause, in tasks that interact with the WebSocket connection. + + """ + await asyncio.shield(self.connection_lost_waiter) + + async def ping(self, data: DataLike | None = None) -> Awaitable[float]: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive, as a check that the remote endpoint + received all messages up to this point, or to measure :attr:`latency`. + + Canceling :meth:`ping` is discouraged. If :meth:`ping` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Canceling the :class:`~asyncio.Future` returned by :meth:`ping` has no + effect. + + Args: + data: Payload of the ping. A string will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + + Returns: + A future that will be completed when the corresponding pong is + received. You can ignore it if you don't intend to wait. The result + of the future is the latency of the connection in seconds. + + :: + + pong_waiter = await ws.ping() + # only if you want to wait for the corresponding pong + latency = await pong_waiter + + Raises: + ConnectionClosed: When the connection is closed. + RuntimeError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + await self.ensure_open() + + if data is not None: + data = prepare_ctrl(data) + + # Protect against duplicates if a payload is explicitly set. + if data in self.pings: + raise RuntimeError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_waiter = self.loop.create_future() + # Resolution of time.monotonic() may be too low on Windows. + ping_timestamp = time.perf_counter() + self.pings[data] = (pong_waiter, ping_timestamp) + + await self.write_frame(True, OP_PING, data) + + return asyncio.shield(pong_waiter) + + async def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Canceling :meth:`pong` is discouraged. If :meth:`pong` doesn't return + immediately, it means the write buffer is full. If you don't want to + wait, you should close the connection. + + Args: + data: Payload of the pong. A string will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + await self.ensure_open() + + data = prepare_ctrl(data) + + await self.write_frame(True, OP_PONG, data) + + # Private methods - no guarantees. + + def connection_closed_exc(self) -> ConnectionClosed: + exc: ConnectionClosed + if ( + self.close_rcvd is not None + and self.close_rcvd.code in OK_CLOSE_CODES + and self.close_sent is not None + and self.close_sent.code in OK_CLOSE_CODES + ): + exc = ConnectionClosedOK( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + else: + exc = ConnectionClosedError( + self.close_rcvd, + self.close_sent, + self.close_rcvd_then_sent, + ) + # Chain to the exception that terminated data transfer, if any. + exc.__cause__ = self.transfer_data_exc + return exc + + async def ensure_open(self) -> None: + """ + Check that the WebSocket connection is open. + + Raise :exc:`~websockets.exceptions.ConnectionClosed` if it isn't. + + """ + # Handle cases from most common to least common for performance. + if self.state is State.OPEN: + # If self.transfer_data_task exited without a closing handshake, + # self.close_connection_task may be closing the connection, going + # straight from OPEN to CLOSED. + if self.transfer_data_task.done(): + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + else: + return + + if self.state is State.CLOSED: + raise self.connection_closed_exc() + + if self.state is State.CLOSING: + # If we started the closing handshake, wait for its completion to + # get the proper close code and reason. self.close_connection_task + # will complete within 4 or 5 * close_timeout after close(). The + # CLOSING state also occurs when failing the connection. In that + # case self.close_connection_task will complete even faster. + await asyncio.shield(self.close_connection_task) + raise self.connection_closed_exc() + + # Control may only reach this point in buggy third-party subclasses. + assert self.state is State.CONNECTING + raise InvalidState("WebSocket connection isn't established yet") + + async def transfer_data(self) -> None: + """ + Read incoming messages and put them in a queue. + + This coroutine runs in a task until the closing handshake is started. + + """ + try: + while True: + message = await self.read_message() + + # Exit the loop when receiving a close frame. + if message is None: + break + + # Wait until there's room in the queue (if necessary). + if self.max_queue is not None: + while len(self.messages) >= self.max_queue: + self._put_message_waiter = self.loop.create_future() + try: + await asyncio.shield(self._put_message_waiter) + finally: + self._put_message_waiter = None + + # Put the message in the queue. + self.messages.append(message) + + # Notify recv(). + if self._pop_message_waiter is not None: + self._pop_message_waiter.set_result(None) + self._pop_message_waiter = None + + except asyncio.CancelledError as exc: + self.transfer_data_exc = exc + # If fail_connection() cancels this task, avoid logging the error + # twice and failing the connection again. + raise + + except ProtocolError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.PROTOCOL_ERROR) + + except (ConnectionError, TimeoutError, EOFError, ssl.SSLError) as exc: + # Reading data with self.reader.readexactly may raise: + # - most subclasses of ConnectionError if the TCP connection + # breaks, is reset, or is aborted; + # - TimeoutError if the TCP connection times out; + # - IncompleteReadError, a subclass of EOFError, if fewer + # bytes are available than requested; + # - ssl.SSLError if the other side infringes the TLS protocol. + self.transfer_data_exc = exc + self.fail_connection(CloseCode.ABNORMAL_CLOSURE) + + except UnicodeDecodeError as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INVALID_DATA) + + except PayloadTooBig as exc: + self.transfer_data_exc = exc + self.fail_connection(CloseCode.MESSAGE_TOO_BIG) + + except Exception as exc: + # This shouldn't happen often because exceptions expected under + # regular circumstances are handled above. If it does, consider + # catching and handling more exceptions. + self.logger.error("data transfer failed", exc_info=True) + + self.transfer_data_exc = exc + self.fail_connection(CloseCode.INTERNAL_ERROR) + + async def read_message(self) -> Data | None: + """ + Read a single message from the connection. + + Re-assemble data frames if the message is fragmented. + + Return :obj:`None` when the closing handshake is started. + + """ + frame = await self.read_data_frame(max_size=self.max_size) + + # A close frame was received. + if frame is None: + return None + + if frame.opcode == OP_TEXT: + text = True + elif frame.opcode == OP_BINARY: + text = False + else: # frame.opcode == OP_CONT + raise ProtocolError("unexpected opcode") + + # Shortcut for the common case - no fragmentation + if frame.fin: + if isinstance(frame.data, memoryview): + raise AssertionError("only compressed outgoing frames use memoryview") + return frame.data.decode() if text else bytes(frame.data) + + # 5.4. Fragmentation + fragments: list[DataLike] = [] + max_size = self.max_size + if text: + decoder_factory = codecs.getincrementaldecoder("utf-8") + decoder = decoder_factory(errors="strict") + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(decoder.decode(frame.data, frame.fin)) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(decoder.decode(frame.data, frame.fin)) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + else: + if max_size is None: + + def append(frame: Frame) -> None: + nonlocal fragments + fragments.append(frame.data) + + else: + + def append(frame: Frame) -> None: + nonlocal fragments, max_size + fragments.append(frame.data) + assert isinstance(max_size, int) + max_size -= len(frame.data) + + append(frame) + + while not frame.fin: + frame = await self.read_data_frame(max_size=max_size) + if frame is None: + raise ProtocolError("incomplete fragmented message") + if frame.opcode != OP_CONT: + raise ProtocolError("unexpected opcode") + append(frame) + + return ("" if text else b"").join(fragments) + + async def read_data_frame(self, max_size: int | None) -> Frame | None: + """ + Read a single data frame from the connection. + + Process control frames received before the next data frame. + + Return :obj:`None` if a close frame is encountered before any data frame. + + """ + # 6.2. Receiving Data + while True: + frame = await self.read_frame(max_size) + + # 5.5. Control Frames + if frame.opcode == OP_CLOSE: + # 7.1.5. The WebSocket Connection Close Code + # 7.1.6. The WebSocket Connection Close Reason + self.close_rcvd = Close.parse(frame.data) + if self.close_sent is not None: + self.close_rcvd_then_sent = False + try: + # Echo the original data instead of re-serializing it with + # Close.serialize() because that fails when the close frame + # is empty and Close.parse() synthesizes a 1005 close code. + await self.write_close_frame(self.close_rcvd, frame.data) + except ConnectionClosed: + # Connection closed before we could echo the close frame. + pass + return None + + elif frame.opcode == OP_PING: + # Answer pings, unless connection is CLOSING. + if self.state is State.OPEN: + try: + await self.pong(frame.data) + except ConnectionClosed: + # Connection closed while draining write buffer. + pass + + elif frame.opcode == OP_PONG: + if frame.data in self.pings: + pong_timestamp = time.perf_counter() + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, (pong_waiter, ping_timestamp) in self.pings.items(): + ping_ids.append(ping_id) + if not pong_waiter.done(): + pong_waiter.set_result(pong_timestamp - ping_timestamp) + if ping_id == frame.data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + # Remove acknowledged pings from self.pings. + for ping_id in ping_ids: + del self.pings[ping_id] + + # 5.6. Data Frames + else: + return frame + + async def read_frame(self, max_size: int | None) -> Frame: + """ + Read a single frame from the connection. + + """ + frame = await Frame.read( + self.reader.readexactly, + mask=not self.is_client, + max_size=max_size, + extensions=self.extensions, + ) + if self.debug: + self.logger.debug("< %s", frame) + return frame + + def write_frame_sync(self, fin: bool, opcode: int, data: BytesLike) -> None: + frame = Frame(fin, Opcode(opcode), data) + if self.debug: + self.logger.debug("> %s", frame) + frame.write( + self.transport.write, + mask=self.is_client, + extensions=self.extensions, + ) + + async def drain(self) -> None: + try: + # Handle flow control automatically. + await self._drain() + except ConnectionError: + # Terminate the connection if the socket died. + self.fail_connection() + # Wait until the connection is closed to raise ConnectionClosed + # with the correct code and reason. + await self.ensure_open() + + async def write_frame( + self, fin: bool, opcode: int, data: BytesLike, *, _state: int = State.OPEN + ) -> None: + # Defensive assertion for protocol compliance. + if self.state is not _state: # pragma: no cover + raise InvalidState( + f"Cannot write to a WebSocket in the {self.state.name} state" + ) + self.write_frame_sync(fin, opcode, data) + await self.drain() + + async def write_close_frame( + self, close: Close, data: BytesLike | None = None + ) -> None: + """ + Write a close frame if and only if the connection state is OPEN. + + This dedicated coroutine must be used for writing close frames to + ensure that at most one close frame is sent on a given connection. + + """ + # Test and set the connection state before sending the close frame to + # avoid sending two frames in case of concurrent calls. + if self.state is State.OPEN: + # 7.1.3. The WebSocket Closing Handshake is Started + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + self.close_sent = close + if self.close_rcvd is not None: + self.close_rcvd_then_sent = True + if data is None: + data = close.serialize() + + # 7.1.2. Start the WebSocket Closing Handshake + await self.write_frame(True, OP_CLOSE, data, _state=State.CLOSING) + + async def keepalive_ping(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + This coroutine exits when the connection terminates and one of the + following happens: + + - :meth:`ping` raises :exc:`ConnectionClosed`, or + - :meth:`close_connection` cancels :attr:`keepalive_ping_task`. + + """ + if self.ping_interval is None: + return + + try: + while True: + await asyncio.sleep(self.ping_interval) + + if self.debug: + self.logger.debug("% sending keepalive ping") + pong_waiter = await self.ping() + + if self.ping_timeout is not None: + try: + async with asyncio_timeout(self.ping_timeout): + # Raises CancelledError if the connection is closed, + # when close_connection() cancels keepalive_ping(). + # Raises ConnectionClosed if the connection is lost, + # when connection_lost() calls abort_pings(). + await pong_waiter + if self.debug: + self.logger.debug("% received keepalive pong") + except asyncio.TimeoutError: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + self.fail_connection( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + + except ConnectionClosed: + pass + + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + async def close_connection(self) -> None: + """ + 7.1.1. Close the WebSocket Connection + + When the opening handshake succeeds, :meth:`connection_open` starts + this coroutine in a task. It waits for the data transfer phase to + complete then it closes the TCP connection cleanly. + + When the opening handshake fails, :meth:`fail_connection` does the + same. There's no data transfer phase in that case. + + """ + try: + # Wait for the data transfer phase to complete. + if hasattr(self, "transfer_data_task"): + try: + await self.transfer_data_task + except asyncio.CancelledError: + pass + + # Cancel the keepalive ping task. + if hasattr(self, "keepalive_ping_task"): + self.keepalive_ping_task.cancel() + + # A client should wait for a TCP close from the server. + if self.is_client and hasattr(self, "transfer_data_task"): + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Half-close the TCP connection if possible (when there's no TLS). + if self.transport.can_write_eof(): + if self.debug: + self.logger.debug("x half-closing TCP connection") + # write_eof() doesn't document which exceptions it raises. + # "[Errno 107] Transport endpoint is not connected" happens + # but it isn't completely clear under which circumstances. + # uvloop can raise RuntimeError here. + try: + self.transport.write_eof() + except (OSError, RuntimeError): # pragma: no cover + pass + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + finally: + # The try/finally ensures that the transport never remains open, + # even if this coroutine is canceled (for example). + await self.close_transport() + + async def close_transport(self) -> None: + """ + Close the TCP connection. + + """ + # If connection_lost() was called, the TCP connection is closed. + # However, if TLS is enabled, the transport still needs closing. + # Else asyncio complains: ResourceWarning: unclosed transport. + if self.connection_lost_waiter.done() and self.transport.is_closing(): + return + + # Close the TCP connection. Buffers are flushed asynchronously. + if self.debug: + self.logger.debug("x closing TCP connection") + self.transport.close() + + if await self.wait_for_connection_lost(): + return + if self.debug: + self.logger.debug("- timed out waiting for TCP close") + + # Abort the TCP connection. Buffers are discarded. + if self.debug: + self.logger.debug("x aborting TCP connection") + self.transport.abort() + + # connection_lost() is called quickly after aborting. + await self.wait_for_connection_lost() + + async def wait_for_connection_lost(self) -> bool: + """ + Wait until the TCP connection is closed or ``self.close_timeout`` elapses. + + Return :obj:`True` if the connection is closed and :obj:`False` + otherwise. + + """ + if not self.connection_lost_waiter.done(): + try: + async with asyncio_timeout(self.close_timeout): + await asyncio.shield(self.connection_lost_waiter) + except asyncio.TimeoutError: + pass + # Re-check self.connection_lost_waiter.done() synchronously because + # connection_lost() could run between the moment the timeout occurs + # and the moment this coroutine resumes running. + return self.connection_lost_waiter.done() + + def fail_connection( + self, + code: int = CloseCode.ABNORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + 7.1.7. Fail the WebSocket Connection + + This requires: + + 1. Stopping all processing of incoming data, which means canceling + :attr:`transfer_data_task`. The close code will be 1006 unless a + close frame was received earlier. + + 2. Sending a close frame with an appropriate code if the opening + handshake succeeded and the other side is likely to process it. + + 3. Closing the connection. :meth:`close_connection` takes care of + this once :attr:`transfer_data_task` exits after being canceled. + + (The specification describes these steps in the opposite order.) + + """ + if self.debug: + self.logger.debug("! failing connection with code %d", code) + + # Cancel transfer_data_task if the opening handshake succeeded. + # cancel() is idempotent and ignored if the task is done already. + if hasattr(self, "transfer_data_task"): + self.transfer_data_task.cancel() + + # Send a close frame when the state is OPEN (a close frame was already + # sent if it's CLOSING), except when failing the connection because of + # an error reading from or writing to the network. + # Don't send a close frame if the connection is broken. + if code != CloseCode.ABNORMAL_CLOSURE and self.state is State.OPEN: + close = Close(code, reason) + + # Write the close frame without draining the write buffer. + + # Keeping fail_connection() synchronous guarantees it can't + # get stuck and simplifies the implementation of the callers. + # Not drainig the write buffer is acceptable in this context. + + # This duplicates a few lines of code from write_close_frame(). + + self.state = State.CLOSING + if self.debug: + self.logger.debug("= connection is CLOSING") + + # If self.close_rcvd was set, the connection state would be + # CLOSING. Therefore self.close_rcvd isn't set and we don't + # have to set self.close_rcvd_then_sent. + assert self.close_rcvd is None + self.close_sent = close + + self.write_frame_sync(True, OP_CLOSE, close.serialize()) + + # Start close_connection_task if the opening handshake didn't succeed. + if not hasattr(self, "close_connection_task"): + self.close_connection_task = self.loop.create_task(self.close_connection()) + + def abort_pings(self) -> None: + """ + Raise ConnectionClosed in pending keepalive pings. + + They'll never receive a pong once the connection is closed. + + """ + assert self.state is State.CLOSED + exc = self.connection_closed_exc() + + for pong_waiter, _ping_timestamp in self.pings.values(): + pong_waiter.set_exception(exc) + # If the exception is never retrieved, it will be logged when ping + # is garbage-collected. This is confusing for users. + # Given that ping is done (with an exception), canceling it does + # nothing, but it prevents logging the exception. + pong_waiter.cancel() + + # asyncio.Protocol methods + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Configure write buffer limits. + + The high-water limit is defined by ``self.write_limit``. + + The low-water limit currently defaults to ``self.write_limit // 4`` in + :meth:`~asyncio.WriteTransport.set_write_buffer_limits`, which should + be all right for reasonable use cases of this library. + + This is the earliest point where we can get hold of the transport, + which means it's the best point for configuring it. + + """ + transport = cast(asyncio.Transport, transport) + transport.set_write_buffer_limits(self.write_limit) + self.transport = transport + + # Copied from asyncio.StreamReaderProtocol + self.reader.set_transport(transport) + + def connection_lost(self, exc: Exception | None) -> None: + """ + 7.1.4. The WebSocket Connection is Closed. + + """ + self.state = State.CLOSED + if self.debug: + self.logger.debug("= connection is CLOSED") + + self.abort_pings() + + # If self.connection_lost_waiter isn't pending, that's a bug, because: + # - it's set only here in connection_lost() which is called only once; + # - it must never be canceled. + self.connection_lost_waiter.set_result(None) + + if True: # pragma: no cover + # Copied from asyncio.StreamReaderProtocol + if self.reader is not None: + if exc is None: + self.reader.feed_eof() + else: + self.reader.set_exception(exc) + + # Copied from asyncio.FlowControlMixin + # Wake up the writer if currently paused. + if not self._paused: + return + waiter = self._drain_waiter + if waiter is None: + return + self._drain_waiter = None + if waiter.done(): + return + if exc is None: + waiter.set_result(None) + else: + waiter.set_exception(exc) + + def pause_writing(self) -> None: # pragma: no cover + assert not self._paused + self._paused = True + + def resume_writing(self) -> None: # pragma: no cover + assert self._paused + self._paused = False + + waiter = self._drain_waiter + if waiter is not None: + self._drain_waiter = None + if not waiter.done(): + waiter.set_result(None) + + def data_received(self, data: bytes) -> None: + self.reader.feed_data(data) + + def eof_received(self) -> None: + """ + Close the transport after receiving EOF. + + The WebSocket protocol has its own closing handshake: endpoints close + the TCP or TLS connection after sending and receiving a close frame. + + As a consequence, they never need to write after receiving EOF, so + there's no reason to keep the transport open by returning :obj:`True`. + + Besides, that doesn't work on TLS connections. + + """ + self.reader.feed_eof() + + +# broadcast() is defined in the protocol module even though it's primarily +# used by servers and documented in the server module because it works with +# client connections too and because it's easier to test together with the +# WebSocketCommonProtocol class. + + +def broadcast( + websockets: Iterable[WebSocketCommonProtocol], + message: DataLike, + raise_exceptions: bool = False, +) -> None: + """ + Broadcast a message to several WebSocket connections. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or bytes-like + object (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) is sent + as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + :func:`broadcast` pushes the message synchronously to all connections even + if their write buffers are overflowing. There's no backpressure. + + If you broadcast messages faster than a connection can handle them, messages + will pile up in its write buffer until the connection times out. Keep + ``ping_interval`` and ``ping_timeout`` low to prevent excessive memory usage + from slow connections. + + Unlike :meth:`~websockets.legacy.protocol.WebSocketCommonProtocol.send`, + :func:`broadcast` doesn't support sending fragmented messages. Indeed, + fragmentation is useful for sending large messages without buffering them in + memory, while :func:`broadcast` buffers one copy per connection as fast as + possible. + + :func:`broadcast` skips connections that aren't open in order to avoid + errors on connections where the closing handshake is in progress. + + :func:`broadcast` ignores failures to write the message on some connections. + It continues writing to other connections. On Python 3.11 and above, you may + set ``raise_exceptions`` to :obj:`True` to record failures and raise all + exceptions in a :pep:`654` :exc:`ExceptionGroup`. + + While :func:`broadcast` makes more sense for servers, it works identically + with clients, if you have a use case for opening connections to many servers + and broadcasting a message to them. + + Args: + websockets: WebSocket connections to which the message will be sent. + message: Message to send. + raise_exceptions: Whether to raise an exception in case of failures. + + Raises: + TypeError: If ``message`` doesn't have a supported type. + + """ + if not isinstance(message, (str, bytes, bytearray, memoryview)): + raise TypeError("data must be str or bytes-like") + + if raise_exceptions: + if sys.version_info[:2] < (3, 11): # pragma: no cover + raise ValueError("raise_exceptions requires at least Python 3.11") + exceptions = [] + + opcode, data = prepare_data(message) + + for websocket in websockets: + if websocket.state is not State.OPEN: + continue + + if websocket._fragmented_message_waiter is not None: + if raise_exceptions: + exception = RuntimeError("sending a fragmented message") + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: sending a fragmented message", + ) + continue + + try: + websocket.write_frame_sync(True, opcode, data) + except Exception as write_exception: + if raise_exceptions: + exception = RuntimeError("failed to write message") + exception.__cause__ = write_exception + exceptions.append(exception) + else: + websocket.logger.warning( + "skipped broadcast: failed to write message: %s", + traceback.format_exception_only(write_exception)[0].strip(), + ) + + if raise_exceptions and exceptions: + raise ExceptionGroup("skipped broadcast", exceptions) + + +# Pretend that broadcast is actually defined in the server module. +broadcast.__module__ = "websockets.legacy.server" diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/server.py b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2a69c716c34083020033b089a7d4156fbc1e93e --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/legacy/server.py @@ -0,0 +1,1191 @@ +from __future__ import annotations + +import asyncio +import email.utils +import functools +import http +import inspect +import logging +import socket +import warnings +from collections.abc import Awaitable, Generator, Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, cast + +from ..asyncio.compatibility import asyncio_timeout +from ..datastructures import Headers, HeadersLike, MultipleValuesError +from ..exceptions import ( + InvalidHandshake, + InvalidHeader, + InvalidMessage, + InvalidOrigin, + InvalidUpgrade, + NegotiationError, +) +from ..extensions import Extension, ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..headers import ( + build_extension, + parse_extension, + parse_subprotocol, + validate_subprotocols, +) +from ..http11 import SERVER +from ..protocol import State +from ..typing import ExtensionHeader, LoggerLike, Origin, StatusLike, Subprotocol +from .exceptions import AbortHandshake +from .handshake import build_response, check_request +from .http import read_request +from .protocol import WebSocketCommonProtocol, broadcast + + +__all__ = [ + "broadcast", + "serve", + "unix_serve", + "WebSocketServerProtocol", + "WebSocketServer", +] + + +HeadersLikeOrCallable = HeadersLike | Callable[[str, Headers], HeadersLike] + +HTTPResponse = tuple[StatusLike, HeadersLike, bytes] + + +class WebSocketServerProtocol(WebSocketCommonProtocol): + """ + WebSocket server connection. + + :class:`WebSocketServerProtocol` provides :meth:`recv` and :meth:`send` + coroutines for receiving and sending messages. + + It supports asynchronous iteration to receive messages:: + + async for message in websocket: + await process(message) + + The iterator exits normally when the connection is closed with close code + 1000 (OK) or 1001 (going away) or without a close code. It raises + a :exc:`~websockets.exceptions.ConnectionClosedError` when the connection + is closed with any other code. + + You may customize the opening handshake in a subclass by + overriding :meth:`process_request` or :meth:`select_subprotocol`. + + Args: + ws_server: WebSocket server that created this connection. + + See :func:`serve` for the documentation of ``ws_handler``, ``logger``, ``origins``, + ``extensions``, ``subprotocols``, ``extra_headers``, and ``server_header``. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + """ + + is_client = False + side = "server" + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + ws_server: WebSocketServer, + *, + logger: LoggerLike | None = None, + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + **kwargs: Any, + ) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + super().__init__(logger=logger, **kwargs) + # For backwards compatibility with 6.0 or earlier. + if origins is not None and "" in origins: + warnings.warn("use None instead of '' in origins", DeprecationWarning) + origins = [None if origin == "" else origin for origin in origins] + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to serve to trigger the deprecation warning on direct + # use of WebSocketServerProtocol. + self.ws_handler = remove_path_argument(ws_handler) + self.ws_server = ws_server + self.origins = origins + self.available_extensions = extensions + self.available_subprotocols = subprotocols + self.extra_headers = extra_headers + self.server_header = server_header + self._process_request = process_request + self._select_subprotocol = select_subprotocol + self.open_timeout = open_timeout + + def connection_made(self, transport: asyncio.BaseTransport) -> None: + """ + Register connection and initialize a task to handle it. + + """ + super().connection_made(transport) + # Register the connection with the server before creating the handler + # task. Registering at the beginning of the handler coroutine would + # create a race condition between the creation of the task, which + # schedules its execution, and the moment the handler starts running. + self.ws_server.register(self) + self.handler_task = self.loop.create_task(self.handler()) + + async def handler(self) -> None: + """ + Handle the lifecycle of a WebSocket connection. + + Since this method doesn't have a caller able to handle exceptions, it + attempts to log relevant ones and guarantees that the TCP connection is + closed before exiting. + + """ + try: + try: + async with asyncio_timeout(self.open_timeout): + await self.handshake( + origins=self.origins, + available_extensions=self.available_extensions, + available_subprotocols=self.available_subprotocols, + extra_headers=self.extra_headers, + ) + except asyncio.TimeoutError: # pragma: no cover + raise + except ConnectionError: + raise + except Exception as exc: + if isinstance(exc, AbortHandshake): + status, headers, body = exc.status, exc.headers, exc.body + elif isinstance(exc, InvalidOrigin): + if self.debug: + self.logger.debug("! invalid origin", exc_info=True) + status, headers, body = ( + http.HTTPStatus.FORBIDDEN, + Headers(), + f"Failed to open a WebSocket connection: {exc}.\n".encode(), + ) + elif isinstance(exc, InvalidUpgrade): + if self.debug: + self.logger.debug("! invalid upgrade", exc_info=True) + status, headers, body = ( + http.HTTPStatus.UPGRADE_REQUIRED, + Headers([("Upgrade", "websocket")]), + ( + f"Failed to open a WebSocket connection: {exc}.\n" + f"\n" + f"You cannot access a WebSocket server directly " + f"with a browser. You need a WebSocket client.\n" + ).encode(), + ) + elif isinstance(exc, InvalidHandshake): + if self.debug: + self.logger.debug("! invalid handshake", exc_info=True) + exc_chain = cast(BaseException, exc) + exc_str = f"{exc_chain}" + while exc_chain.__cause__ is not None: + exc_chain = exc_chain.__cause__ + exc_str += f"; {exc_chain}" + status, headers, body = ( + http.HTTPStatus.BAD_REQUEST, + Headers(), + f"Failed to open a WebSocket connection: {exc_str}.\n".encode(), + ) + else: + self.logger.error("opening handshake failed", exc_info=True) + status, headers, body = ( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + Headers(), + ( + b"Failed to open a WebSocket connection.\n" + b"See server log for more information.\n" + ), + ) + + headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header: + headers.setdefault("Server", self.server_header) + + headers.setdefault("Content-Length", str(len(body))) + headers.setdefault("Content-Type", "text/plain") + headers.setdefault("Connection", "close") + + self.write_http_response(status, headers, body) + self.logger.info( + "connection rejected (%d %s)", status.value, status.phrase + ) + await self.close_transport() + return + + try: + await self.ws_handler(self) + except Exception: + self.logger.error("connection handler failed", exc_info=True) + if not self.closed: + self.fail_connection(1011) + raise + + try: + await self.close() + except ConnectionError: + raise + except Exception: + self.logger.error("closing handshake failed", exc_info=True) + raise + + except Exception: + # Last-ditch attempt to avoid leaking connections on errors. + try: + self.transport.close() + except Exception: # pragma: no cover + pass + + finally: + # Unregister the connection with the server when the handler task + # terminates. Registration is tied to the lifecycle of the handler + # task because the server waits for tasks attached to registered + # connections before terminating. + self.ws_server.unregister(self) + self.logger.info("connection closed") + + async def read_http_request(self) -> tuple[str, Headers]: + """ + Read request line and headers from the HTTP request. + + If the request contains a body, it may be read from ``self.reader`` + after this coroutine returns. + + Raises: + InvalidMessage: If the HTTP message is malformed or isn't an + HTTP/1.1 GET request. + + """ + try: + path, headers = await read_request(self.reader) + except asyncio.CancelledError: # pragma: no cover + raise + except Exception as exc: + raise InvalidMessage("did not receive a valid HTTP request") from exc + + if self.debug: + self.logger.debug("< GET %s HTTP/1.1", path) + for key, value in headers.raw_items(): + self.logger.debug("< %s: %s", key, value) + + self.path = path + self.request_headers = headers + + return path, headers + + def write_http_response( + self, status: http.HTTPStatus, headers: Headers, body: bytes | None = None + ) -> None: + """ + Write status line and headers to the HTTP response. + + This coroutine is also able to write a response body. + + """ + self.response_headers = headers + + if self.debug: + self.logger.debug("> HTTP/1.1 %d %s", status.value, status.phrase) + for key, value in headers.raw_items(): + self.logger.debug("> %s: %s", key, value) + if body is not None: + self.logger.debug("> [body] (%d bytes)", len(body)) + + # Since the status line and headers only contain ASCII characters, + # we can keep this simple. + response = f"HTTP/1.1 {status.value} {status.phrase}\r\n" + response += str(headers) + + self.transport.write(response.encode()) + + if body is not None: + self.transport.write(body) + + async def process_request( + self, path: str, request_headers: Headers + ) -> HTTPResponse | None: + """ + Intercept the HTTP request and return an HTTP response if appropriate. + + You may override this method in a :class:`WebSocketServerProtocol` + subclass, for example: + + * to return an HTTP 200 OK response on a given path; then a load + balancer can use this path for a health check; + * to authenticate the request and return an HTTP 401 Unauthorized or an + HTTP 403 Forbidden when authentication fails. + + You may also override this method with the ``process_request`` + argument of :func:`serve` and :class:`WebSocketServerProtocol`. This + is equivalent, except ``process_request`` won't have access to the + protocol instance, so it can't store information for later use. + + :meth:`process_request` is expected to complete quickly. If it may run + for a long time, then it should await :meth:`wait_closed` and exit if + :meth:`wait_closed` completes, or else it could prevent the server + from shutting down. + + Args: + path: Request path, including optional query string. + request_headers: Request headers. + + Returns: + tuple[StatusLike, HeadersLike, bytes] | None: :obj:`None` to + continue the WebSocket handshake normally. + + An HTTP response, represented by a 3-uple of the response status, + headers, and body, to abort the WebSocket handshake and return + that HTTP response instead. + + """ + if self._process_request is not None: + response = self._process_request(path, request_headers) + if isinstance(response, Awaitable): + return await response + else: + # For backwards compatibility with 7.0. + warnings.warn( + "declare process_request as a coroutine", DeprecationWarning + ) + return response + return None + + @staticmethod + def process_origin( + headers: Headers, origins: Sequence[Origin | None] | None = None + ) -> Origin | None: + """ + Handle the Origin HTTP request header. + + Args: + headers: Request headers. + origins: Optional list of acceptable origins. + + Raises: + InvalidOrigin: If the origin isn't acceptable. + + """ + # "The user agent MUST NOT include more than one Origin header field" + # per https://datatracker.ietf.org/doc/html/rfc6454#section-7.3. + try: + origin = headers.get("Origin") + except MultipleValuesError as exc: + raise InvalidHeader("Origin", "multiple values") from exc + if origin is not None: + origin = cast(Origin, origin) + if origins is not None: + if origin not in origins: + raise InvalidOrigin(origin) + return origin + + @staticmethod + def process_extensions( + headers: Headers, + available_extensions: Sequence[ServerExtensionFactory] | None, + ) -> tuple[str | None, list[Extension]]: + """ + Handle the Sec-WebSocket-Extensions HTTP request header. + + Accept or reject each extension proposed in the client request. + Negotiate parameters for accepted extensions. + + Return the Sec-WebSocket-Extensions HTTP response header and the list + of accepted extensions. + + :rfc:`6455` leaves the rules up to the specification of each + :extension. + + To provide this level of flexibility, for each extension proposed by + the client, we check for a match with each extension available in the + server configuration. If no match is found, the extension is ignored. + + If several variants of the same extension are proposed by the client, + it may be accepted several times, which won't make sense in general. + Extensions must implement their own requirements. For this purpose, + the list of previously accepted extensions is provided. + + This process doesn't allow the server to reorder extensions. It can + only select a subset of the extensions proposed by the client. + + Other requirements, for example related to mandatory extensions or the + order of extensions, may be implemented by overriding this method. + + Args: + headers: Request headers. + extensions: Optional list of supported extensions. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + response_header_value: str | None = None + + extension_headers: list[ExtensionHeader] = [] + accepted_extensions: list[Extension] = [] + + header_values = headers.get_all("Sec-WebSocket-Extensions") + + if header_values and available_extensions: + parsed_header_values: list[ExtensionHeader] = sum( + [parse_extension(header_value) for header_value in header_values], [] + ) + + for name, request_params in parsed_header_values: + for ext_factory in available_extensions: + # Skip non-matching extensions based on their name. + if ext_factory.name != name: + continue + + # Skip non-matching extensions based on their params. + try: + response_params, extension = ext_factory.process_request_params( + request_params, accepted_extensions + ) + except NegotiationError: + continue + + # Add matching extension to the final list. + extension_headers.append((name, response_params)) + accepted_extensions.append(extension) + + # Break out of the loop once we have a match. + break + + # If we didn't break from the loop, no extension in our list + # matched what the client sent. The extension is declined. + + # Serialize extension header. + if extension_headers: + response_header_value = build_extension(extension_headers) + + return response_header_value, accepted_extensions + + # Not @staticmethod because it calls self.select_subprotocol() + def process_subprotocol( + self, headers: Headers, available_subprotocols: Sequence[Subprotocol] | None + ) -> Subprotocol | None: + """ + Handle the Sec-WebSocket-Protocol HTTP request header. + + Return Sec-WebSocket-Protocol HTTP response header, which is the same + as the selected subprotocol. + + Args: + headers: Request headers. + available_subprotocols: Optional list of supported subprotocols. + + Raises: + InvalidHandshake: To abort the handshake with an HTTP 400 error. + + """ + subprotocol: Subprotocol | None = None + + header_values = headers.get_all("Sec-WebSocket-Protocol") + + if header_values and available_subprotocols: + parsed_header_values: list[Subprotocol] = sum( + [parse_subprotocol(header_value) for header_value in header_values], [] + ) + + subprotocol = self.select_subprotocol( + parsed_header_values, available_subprotocols + ) + + return subprotocol + + def select_subprotocol( + self, + client_subprotocols: Sequence[Subprotocol], + server_subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + """ + Pick a subprotocol among those supported by the client and the server. + + If several subprotocols are available, select the preferred subprotocol + by giving equal weight to the preferences of the client and the server. + + If no subprotocol is available, proceed without a subprotocol. + + You may provide a ``select_subprotocol`` argument to :func:`serve` or + :class:`WebSocketServerProtocol` to override this logic. For example, + you could reject the handshake if the client doesn't support a + particular subprotocol, rather than accept the handshake without that + subprotocol. + + Args: + client_subprotocols: List of subprotocols offered by the client. + server_subprotocols: List of subprotocols available on the server. + + Returns: + Selected subprotocol, if a common subprotocol was found. + + :obj:`None` to continue without a subprotocol. + + """ + if self._select_subprotocol is not None: + return self._select_subprotocol(client_subprotocols, server_subprotocols) + + subprotocols = set(client_subprotocols) & set(server_subprotocols) + if not subprotocols: + return None + return sorted( + subprotocols, + key=lambda p: client_subprotocols.index(p) + server_subprotocols.index(p), + )[0] + + async def handshake( + self, + origins: Sequence[Origin | None] | None = None, + available_extensions: Sequence[ServerExtensionFactory] | None = None, + available_subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + ) -> str: + """ + Perform the server side of the opening handshake. + + Args: + origins: List of acceptable values of the Origin HTTP header; + include :obj:`None` if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be tried. + subprotocols: List of supported subprotocols, in order of + decreasing preference. + extra_headers: Arbitrary HTTP headers to add to the response when + the handshake succeeds. + + Returns: + path of the URI of the request. + + Raises: + InvalidHandshake: If the handshake fails. + + """ + path, request_headers = await self.read_http_request() + + # Hook for customizing request handling, for example checking + # authentication or treating some paths as plain HTTP endpoints. + early_response_awaitable = self.process_request(path, request_headers) + if isinstance(early_response_awaitable, Awaitable): + early_response = await early_response_awaitable + else: + # For backwards compatibility with 7.0. + warnings.warn("declare process_request as a coroutine", DeprecationWarning) + early_response = early_response_awaitable + + # The connection may drop while process_request is running. + if self.state is State.CLOSED: + # This subclass of ConnectionError is silently ignored in handler(). + raise BrokenPipeError("connection closed during opening handshake") + + # Change the response to a 503 error if the server is shutting down. + if not self.ws_server.is_serving(): + early_response = ( + http.HTTPStatus.SERVICE_UNAVAILABLE, + [], + b"Server is shutting down.\n", + ) + + if early_response is not None: + raise AbortHandshake(*early_response) + + key = check_request(request_headers) + + self.origin = self.process_origin(request_headers, origins) + + extensions_header, self.extensions = self.process_extensions( + request_headers, available_extensions + ) + + protocol_header = self.subprotocol = self.process_subprotocol( + request_headers, available_subprotocols + ) + + response_headers = Headers() + + build_response(response_headers, key) + + if extensions_header is not None: + response_headers["Sec-WebSocket-Extensions"] = extensions_header + + if protocol_header is not None: + response_headers["Sec-WebSocket-Protocol"] = protocol_header + + if callable(extra_headers): + extra_headers = extra_headers(path, self.request_headers) + if extra_headers is not None: + response_headers.update(extra_headers) + + response_headers.setdefault("Date", email.utils.formatdate(usegmt=True)) + if self.server_header is not None: + response_headers.setdefault("Server", self.server_header) + + self.write_http_response(http.HTTPStatus.SWITCHING_PROTOCOLS, response_headers) + + self.logger.info("connection open") + + self.connection_open() + + return path + + +class WebSocketServer: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~asyncio.Server`. + + It keeps track of WebSocket connections in order to close them properly + when shutting down. + + Args: + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__(self, logger: LoggerLike | None = None) -> None: + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + + # Keep track of active connections. + self.websockets: set[WebSocketServerProtocol] = set() + + # Task responsible for closing the server and terminating connections. + self.close_task: asyncio.Task[None] | None = None + + # Completed when the server is closed and connections are terminated. + self.closed_waiter: asyncio.Future[None] + + def wrap(self, server: asyncio.base_events.Server) -> None: + """ + Attach to a given :class:`~asyncio.Server`. + + Since :meth:`~asyncio.loop.create_server` doesn't support injecting a + custom ``Server`` class, the easiest solution that doesn't rely on + private :mod:`asyncio` APIs is to: + + - instantiate a :class:`WebSocketServer` + - give the protocol factory a reference to that instance + - call :meth:`~asyncio.loop.create_server` with the factory + - attach the resulting :class:`~asyncio.Server` with this method + + """ + self.server = server + for sock in server.sockets: + if sock.family == socket.AF_INET: + name = "%s:%d" % sock.getsockname() + elif sock.family == socket.AF_INET6: + name = "[%s]:%d" % sock.getsockname()[:2] + elif sock.family == socket.AF_UNIX: + name = sock.getsockname() + # In the unlikely event that someone runs websockets over a + # protocol other than IP or Unix sockets, avoid crashing. + else: # pragma: no cover + name = str(sock.getsockname()) + self.logger.info("server listening on %s", name) + + # Initialized here because we need a reference to the event loop. + # This could be moved back to __init__ now that Python < 3.10 isn't + # supported anymore, but I'm not taking that risk in legacy code. + self.closed_waiter = server.get_loop().create_future() + + def register(self, protocol: WebSocketServerProtocol) -> None: + """ + Register a connection with this server. + + """ + self.websockets.add(protocol) + + def unregister(self, protocol: WebSocketServerProtocol) -> None: + """ + Unregister a connection with this server. + + """ + self.websockets.remove(protocol) + + def close(self, close_connections: bool = True) -> None: + """ + Close the server. + + * Close the underlying :class:`~asyncio.Server`. + * When ``close_connections`` is :obj:`True`, which is the default, + close existing connections. Specifically: + + * Reject opening WebSocket connections with an HTTP 503 (service + unavailable) error. This happens when the server accepted the TCP + connection but didn't complete the opening handshake before closing. + * Close open WebSocket connections with close code 1001 (going away). + + * Wait until all connection handlers terminate. + + :meth:`close` is idempotent. + + """ + if self.close_task is None: + self.close_task = self.get_loop().create_task( + self._close(close_connections) + ) + + async def _close(self, close_connections: bool) -> None: + """ + Implementation of :meth:`close`. + + This calls :meth:`~asyncio.Server.close` on the underlying + :class:`~asyncio.Server` object to stop accepting new connections and + then closes open connections with close code 1001. + + """ + self.logger.info("server closing") + + # Stop accepting new connections. + self.server.close() + + # Wait until all accepted connections reach connection_made() and call + # register(). See https://github.com/python/cpython/issues/79033 for + # details. This workaround can be removed when dropping Python < 3.11. + await asyncio.sleep(0) + + if close_connections: + # Close OPEN connections with close code 1001. After server.close(), + # handshake() closes OPENING connections with an HTTP 503 error. + close_tasks = [ + asyncio.create_task(websocket.close(1001)) + for websocket in self.websockets + if websocket.state is not State.CONNECTING + ] + # asyncio.wait doesn't accept an empty first argument. + if close_tasks: + await asyncio.wait(close_tasks) + + # Wait until all TCP connections are closed. + await self.server.wait_closed() + + # Wait until all connection handlers terminate. + # asyncio.wait doesn't accept an empty first argument. + if self.websockets: + await asyncio.wait( + [websocket.handler_task for websocket in self.websockets] + ) + + # Tell wait_closed() to return. + self.closed_waiter.set_result(None) + + self.logger.info("server closed") + + async def wait_closed(self) -> None: + """ + Wait until the server is closed. + + When :meth:`wait_closed` returns, all TCP connections are closed and + all connection handlers have returned. + + To ensure a fast shutdown, a connection handler should always be + awaiting at least one of: + + * :meth:`~WebSocketServerProtocol.recv`: when the connection is closed, + it raises :exc:`~websockets.exceptions.ConnectionClosedOK`; + * :meth:`~WebSocketServerProtocol.wait_closed`: when the connection is + closed, it returns. + + Then the connection handler is immediately notified of the shutdown; + it can clean up and exit. + + """ + await asyncio.shield(self.closed_waiter) + + def get_loop(self) -> asyncio.AbstractEventLoop: + """ + See :meth:`asyncio.Server.get_loop`. + + """ + return self.server.get_loop() + + def is_serving(self) -> bool: + """ + See :meth:`asyncio.Server.is_serving`. + + """ + return self.server.is_serving() + + async def start_serving(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.start_serving`. + + Typical use:: + + server = await serve(..., start_serving=False) + # perform additional setup here... + # ... then start the server + await server.start_serving() + + """ + await self.server.start_serving() + + async def serve_forever(self) -> None: # pragma: no cover + """ + See :meth:`asyncio.Server.serve_forever`. + + Typical use:: + + server = await serve(...) + # this coroutine doesn't return + # canceling it stops the server + await server.serve_forever() + + This is an alternative to using :func:`serve` as an asynchronous context + manager. Shutdown is triggered by canceling :meth:`serve_forever` + instead of exiting a :func:`serve` context. + + """ + await self.server.serve_forever() + + @property + def sockets(self) -> Iterable[socket.socket]: + """ + See :attr:`asyncio.Server.sockets`. + + """ + return self.server.sockets + + async def __aenter__(self) -> WebSocketServer: # pragma: no cover + return self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: # pragma: no cover + self.close() + await self.wait_closed() + + +class Serve: + """ + Start a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a + :class:`WebSocketServerProtocol`, performs the opening handshake, and + delegates to the connection handler, ``ws_handler``. + + The handler receives the :class:`WebSocketServerProtocol` and uses it to + send and receive messages. + + Once the handler completes, either normally or with an exception, the + server performs the closing handshake and closes the connection. + + Awaiting :func:`serve` yields a :class:`WebSocketServer`. This object + provides a :meth:`~WebSocketServer.close` method to shut down the server:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + server = await serve(...) + await stop + server.close() + await server.wait_closed() + + :func:`serve` can be used as an asynchronous context manager. Then, the + server is shut down automatically when exiting the context:: + + # set this future to exit the server + stop = asyncio.get_running_loop().create_future() + + async with serve(...): + await stop + + Args: + ws_handler: Connection handler. It receives the WebSocket connection, + which is a :class:`WebSocketServerProtocol`, in argument. + host: Network interfaces the server binds to. + See :meth:`~asyncio.loop.create_server` for details. + port: TCP port the server listens on. + See :meth:`~asyncio.loop.create_server` for details. + create_protocol: Factory for the :class:`asyncio.Protocol` managing + the connection. It defaults to :class:`WebSocketServerProtocol`. + Set it to a wrapper or a subclass to customize connection handling. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Include :obj:`None` + in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + extra_headers (HeadersLike | Callable[[str, Headers] | HeadersLike]): + Arbitrary HTTP headers to add to the response. This can be + a :data:`~websockets.datastructures.HeadersLike` or a callable + taking the request path and headers in arguments and returning + a :data:`~websockets.datastructures.HeadersLike`. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + process_request (Callable[[str, Headers], \ + Awaitable[tuple[StatusLike, HeadersLike, bytes] | None]] | None): + Intercept HTTP request before the opening handshake. + See :meth:`~WebSocketServerProtocol.process_request` for details. + select_subprotocol: Select a subprotocol supported by the client. + See :meth:`~WebSocketServerProtocol.select_subprotocol` for details. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + + See :class:`~websockets.legacy.protocol.WebSocketCommonProtocol` for the + documentation of ``ping_interval``, ``ping_timeout``, ``close_timeout``, + ``max_size``, ``max_queue``, ``read_limit``, and ``write_limit``. + + Any other keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_server` method. + + For example: + + * You can set ``ssl`` to a :class:`~ssl.SSLContext` to enable TLS. + + * You can set ``sock`` to a :obj:`~socket.socket` that you created + outside of websockets. + + Returns: + WebSocket server. + + """ + + def __init__( + self, + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + host: str | Sequence[str] | None = None, + port: int | None = None, + *, + create_protocol: Callable[..., WebSocketServerProtocol] | None = None, + logger: LoggerLike | None = None, + compression: str | None = "deflate", + origins: Sequence[Origin | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + extra_headers: HeadersLikeOrCallable | None = None, + server_header: str | None = SERVER, + process_request: ( + Callable[[str, Headers], Awaitable[HTTPResponse | None]] | None + ) = None, + select_subprotocol: ( + Callable[[Sequence[Subprotocol], Sequence[Subprotocol]], Subprotocol] | None + ) = None, + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = None, + max_size: int | None = 2**20, + max_queue: int | None = 2**5, + read_limit: int = 2**16, + write_limit: int = 2**16, + **kwargs: Any, + ) -> None: + # Backwards compatibility: close_timeout used to be called timeout. + timeout: float | None = kwargs.pop("timeout", None) + if timeout is None: + timeout = 10 + else: + warnings.warn("rename timeout to close_timeout", DeprecationWarning) + # If both are specified, timeout is ignored. + if close_timeout is None: + close_timeout = timeout + + # Backwards compatibility: create_protocol used to be called klass. + klass: type[WebSocketServerProtocol] | None = kwargs.pop("klass", None) + if klass is None: + klass = WebSocketServerProtocol + else: + warnings.warn("rename klass to create_protocol", DeprecationWarning) + # If both are specified, klass is ignored. + if create_protocol is None: + create_protocol = klass + + # Backwards compatibility: recv() used to return None on closed connections + legacy_recv: bool = kwargs.pop("legacy_recv", False) + + # Backwards compatibility: the loop parameter used to be supported. + _loop: asyncio.AbstractEventLoop | None = kwargs.pop("loop", None) + if _loop is None: + loop = asyncio.get_event_loop() + else: + loop = _loop + warnings.warn("remove loop argument", DeprecationWarning) + + ws_server = WebSocketServer(logger=logger) + + secure = kwargs.get("ssl") is not None + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + # Help mypy and avoid this error: "type[WebSocketServerProtocol] | + # Callable[..., WebSocketServerProtocol]" not callable [misc] + create_protocol = cast(Callable[..., WebSocketServerProtocol], create_protocol) + factory = functools.partial( + create_protocol, + # For backwards compatibility with 10.0 or earlier. Done here in + # addition to WebSocketServerProtocol to trigger the deprecation + # warning once per serve() call rather than once per connection. + remove_path_argument(ws_handler), + ws_server, + host=host, + port=port, + secure=secure, + open_timeout=open_timeout, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_size=max_size, + max_queue=max_queue, + read_limit=read_limit, + write_limit=write_limit, + loop=_loop, + legacy_recv=legacy_recv, + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + extra_headers=extra_headers, + server_header=server_header, + process_request=process_request, + select_subprotocol=select_subprotocol, + logger=logger, + ) + + if kwargs.pop("unix", False): + path: str | None = kwargs.pop("path", None) + # unix_serve(path) must not specify host and port parameters. + assert host is None and port is None + create_server = functools.partial( + loop.create_unix_server, factory, path, **kwargs + ) + else: + create_server = functools.partial( + loop.create_server, factory, host, port, **kwargs + ) + + # This is a coroutine function. + self._create_server = create_server + self.ws_server = ws_server + + # async with serve(...) + + async def __aenter__(self) -> WebSocketServer: + return await self + + async def __aexit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.ws_server.close() + await self.ws_server.wait_closed() + + # await serve(...) + + def __await__(self) -> Generator[Any, None, WebSocketServer]: + # Create a suitable iterator by calling __await__ on a coroutine. + return self.__await_impl__().__await__() + + async def __await_impl__(self) -> WebSocketServer: + server = await self._create_server() + self.ws_server.wrap(server) + return self.ws_server + + # yield from serve(...) - remove when dropping Python < 3.11 + + __iter__ = __await__ + + +serve = Serve + + +def unix_serve( + # The version that accepts the path in the second argument is deprecated. + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), + path: str | None = None, + **kwargs: Any, +) -> Serve: + """ + Start a WebSocket server listening on a Unix socket. + + This function is identical to :func:`serve`, except the ``host`` and + ``port`` arguments are replaced by ``path``. It is only available on Unix. + + Unrecognized keyword arguments are passed the event loop's + :meth:`~asyncio.loop.create_unix_server` method. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + path: File system path to the Unix socket. + + """ + return serve(ws_handler, path=path, unix=True, **kwargs) + + +def remove_path_argument( + ws_handler: ( + Callable[[WebSocketServerProtocol], Awaitable[Any]] + | Callable[[WebSocketServerProtocol, str], Awaitable[Any]] + ), +) -> Callable[[WebSocketServerProtocol], Awaitable[Any]]: + try: + inspect.signature(ws_handler).bind(None) + except TypeError: + try: + inspect.signature(ws_handler).bind(None, "") + except TypeError: # pragma: no cover + # ws_handler accepts neither one nor two arguments; leave it alone. + pass + else: + # ws_handler accepts two arguments; activate backwards compatibility. + warnings.warn("remove second argument of ws_handler", DeprecationWarning) + + async def _ws_handler(websocket: WebSocketServerProtocol) -> Any: + return await cast( + Callable[[WebSocketServerProtocol, str], Awaitable[Any]], + ws_handler, + )(websocket, websocket.path) + + return _ws_handler + + return cast( + Callable[[WebSocketServerProtocol], Awaitable[Any]], + ws_handler, + ) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__init__.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/__init__.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/__init__.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb672223881372ff9756874001e434794483fe3c Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/__init__.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/client.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/client.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3d52fca9d0b28b8adfac3bedde531a0bfb3ef11 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/client.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/connection.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/connection.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e149f34494cb7a2e6a107aa91b78c1ac7c928fda Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/connection.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/messages.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/messages.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f8469cdc5c13b13447d0351c69b8a6d1a5a07ba8 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/messages.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/router.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/router.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8f2ca434ee6456e6af11367b6a56345fdabc73de Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/router.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/server.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/server.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..237f0aee9911dd0958a0cb5cab9b04b3e2acf1cb Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/server.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/utils.cpython-313.pyc b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/utils.cpython-313.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3f5f5e14d6bdf36832cdfd7cc19a461790adff50 Binary files /dev/null and b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/__pycache__/utils.cpython-313.pyc differ diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/client.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/client.py new file mode 100644 index 0000000000000000000000000000000000000000..b3fff44eee51ca2961f40c0994d7078c0670a9da --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/client.py @@ -0,0 +1,633 @@ +from __future__ import annotations + +import socket +import ssl as ssl_module +import threading +import warnings +from collections.abc import Sequence +from typing import Any, Callable, Literal, TypeVar, cast + +from ..client import ClientProtocol +from ..datastructures import HeadersLike +from ..exceptions import InvalidProxyMessage, InvalidProxyStatus, ProxyError +from ..extensions.base import ClientExtensionFactory +from ..extensions.permessage_deflate import enable_client_permessage_deflate +from ..headers import validate_subprotocols +from ..http11 import USER_AGENT, Response +from ..protocol import CONNECTING, Event +from ..proxy import Proxy, get_proxy, parse_proxy, prepare_connect_request +from ..streams import StreamReader +from ..typing import BytesLike, LoggerLike, Origin, Subprotocol +from ..uri import WebSocketURI, parse_uri +from .connection import Connection +from .utils import Deadline + + +__all__ = ["connect", "unix_connect", "ClientConnection"] + + +class ClientConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket client connection. + + :class:`ClientConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`connect`. + + Args: + socket: Socket connected to a WebSocket server. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ClientProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ClientProtocol + self.response_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + + def handshake( + self, + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + with self.send_context(expected_state=CONNECTING): + self.request = self.protocol.connect() + if additional_headers is not None: + self.request.headers.update(additional_headers) + if user_agent_header is not None: + self.request.headers.setdefault("User-Agent", user_agent_header) + self.protocol.send_request(self.request) + + if not self.response_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake response") + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a response, when the response cannot be parsed, or when the + # response fails the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake response. + if self.response is None: + assert isinstance(event, Response) + self.response = event + self.response_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.response_rcvd.set() + + +def connect( + uri: str, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + # WebSocket + origin: Origin | None = None, + extensions: Sequence[ClientExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + compression: str | None = "deflate", + # HTTP + additional_headers: HeadersLike | None = None, + user_agent_header: str | None = USER_AGENT, + proxy: str | Literal[True] | None = True, + proxy_ssl: ssl_module.SSLContext | None = None, + proxy_server_hostname: str | None = None, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ClientConnection] | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to the WebSocket server at ``uri``. + + This function returns a :class:`ClientConnection` instance, which you can + use to send and receive messages. + + :func:`connect` may be used as a context manager:: + + from websockets.sync.client import connect + + with connect(...) as websocket: + ... + + The connection is closed automatically when exiting the context. + + Args: + uri: URI of the WebSocket server. + sock: Preexisting TCP socket. ``sock`` overrides the host and port + from ``uri``. You may call :func:`socket.create_connection` to + create a suitable TCP socket. + ssl: Configuration for enabling TLS on the connection. + server_hostname: Host name for the TLS handshake. ``server_hostname`` + overrides the host name from ``uri``. + origin: Value of the ``Origin`` header, for servers that require it. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + additional_headers (HeadersLike | None): Arbitrary HTTP headers to add + to the handshake request. + user_agent_header: Value of the ``User-Agent`` request header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. + Setting it to :obj:`None` removes the header. + proxy: If a proxy is configured, it is used by default. Set ``proxy`` + to :obj:`None` to disable the proxy or to the address of a proxy + to override the system configuration. See the :doc:`proxy docs + <../../topics/proxies>` for details. + proxy_ssl: Configuration for enabling TLS on the proxy connection. + proxy_server_hostname: Host name for the TLS handshake with the proxy. + ``proxy_server_hostname`` overrides the host name from ``proxy``. + open_timeout: Timeout for opening the connection in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing the connection in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this client. + It defaults to ``logging.getLogger("websockets.client")``. + See the :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ClientConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_connection`. + + Raises: + InvalidURI: If ``uri`` isn't a valid WebSocket URI. + OSError: If the TCP connection fails. + InvalidHandshake: If the opening handshake fails. + TimeoutError: If the opening handshake times out. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + ws_uri = parse_uri(uri) + if not ws_uri.secure and ssl is not None: + raise ValueError("ssl argument is incompatible with a ws:// URI") + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if unix: + if path is None and sock is None: + raise ValueError("missing path argument") + elif path is not None and sock is not None: + raise ValueError("path and sock arguments are incompatible") + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_client_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if unix: + proxy = None + if sock is not None: + proxy = None + if proxy is True: + proxy = get_proxy(ws_uri) + + # Calculate timeouts on the TCP, TLS, and WebSocket handshakes. + # The TCP and TLS timeouts must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + if create_connection is None: + create_connection = ClientConnection + + try: + # Connect socket + + if sock is None: + if unix: + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(deadline.timeout()) + assert path is not None # mypy cannot figure this out + sock.connect(path) + elif proxy is not None: + proxy_parsed = parse_proxy(proxy) + if proxy_parsed.scheme[:5] == "socks": + # Connect to the server through the proxy. + sock = connect_socks_proxy( + proxy_parsed, + ws_uri, + deadline, + # websockets is consistent with the socket module while + # python_socks is consistent across implementations. + local_addr=kwargs.pop("source_address", None), + ) + elif proxy_parsed.scheme[:4] == "http": + # Validate the proxy_ssl argument. + if proxy_parsed.scheme != "https" and proxy_ssl is not None: + raise ValueError( + "proxy_ssl argument is incompatible with an http:// proxy" + ) + # Connect to the server through the proxy. + sock = connect_http_proxy( + proxy_parsed, + ws_uri, + deadline, + user_agent_header=user_agent_header, + ssl=proxy_ssl, + server_hostname=proxy_server_hostname, + **kwargs, + ) + else: + raise AssertionError("unsupported proxy") + else: + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection( + (ws_uri.host, ws_uri.port), + **kwargs, + ) + sock.settimeout(None) + + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Initialize TLS wrapper and perform TLS handshake + + if ws_uri.secure: + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = ws_uri.host + sock.settimeout(deadline.timeout()) + if proxy_ssl is None: + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + else: + sock_2 = SSLSSLSocket(sock, ssl, server_hostname=server_hostname) + # Let's pretend that sock is a socket, even though it isn't. + sock = cast(socket.socket, sock_2) + sock.settimeout(None) + + # Initialize WebSocket protocol + + protocol = ClientProtocol( + ws_uri, + origin=origin, + extensions=extensions, + subprotocols=subprotocols, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + if sock is not None: + sock.close() + raise + + try: + connection.handshake( + additional_headers, + user_agent_header, + deadline.timeout(), + ) + except Exception: + connection.close_socket() + connection.recv_events_thread.join() + raise + + connection.start_keepalive() + return connection + + +def unix_connect( + path: str | None = None, + uri: str | None = None, + **kwargs: Any, +) -> ClientConnection: + """ + Connect to a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`connect`. + + It's only available on Unix. + + It's mainly useful for debugging servers listening on Unix sockets. + + Args: + path: File system path to the Unix socket. + uri: URI of the WebSocket server. ``uri`` defaults to + ``ws://localhost/`` or, when a ``ssl`` is provided, to + ``wss://localhost/``. + + """ + if uri is None: + # Backwards compatibility: ssl used to be called ssl_context. + if kwargs.get("ssl") is None and kwargs.get("ssl_context") is None: + uri = "ws://localhost/" + else: + uri = "wss://localhost/" + return connect(uri=uri, unix=True, path=path, **kwargs) + + +try: + from python_socks import ProxyType + from python_socks.sync import Proxy as SocksProxy + +except ImportError: + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + raise ImportError("connecting through a SOCKS proxy requires python-socks") + +else: + SOCKS_PROXY_TYPES = { + "socks5h": ProxyType.SOCKS5, + "socks5": ProxyType.SOCKS5, + "socks4a": ProxyType.SOCKS4, + "socks4": ProxyType.SOCKS4, + } + + SOCKS_PROXY_RDNS = { + "socks5h": True, + "socks5": False, + "socks4a": True, + "socks4": False, + } + + def connect_socks_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + **kwargs: Any, + ) -> socket.socket: + """Connect via a SOCKS proxy and return the socket.""" + socks_proxy = SocksProxy( + SOCKS_PROXY_TYPES[proxy.scheme], + proxy.host, + proxy.port, + proxy.username, + proxy.password, + SOCKS_PROXY_RDNS[proxy.scheme], + ) + kwargs.setdefault("timeout", deadline.timeout()) + # connect() is documented to raise OSError and TimeoutError. + # Wrap other exceptions in ProxyError, a subclass of InvalidHandshake. + try: + return socks_proxy.connect(ws_uri.host, ws_uri.port, **kwargs) + except (OSError, TimeoutError, socket.timeout): + raise + except Exception as exc: + raise ProxyError("failed to connect to SOCKS proxy") from exc + + +def read_connect_response(sock: socket.socket, deadline: Deadline) -> Response: + reader = StreamReader() + parser = Response.parse( + reader.read_line, + reader.read_exact, + reader.read_to_eof, + proxy=True, + ) + try: + while True: + sock.settimeout(deadline.timeout()) + data = sock.recv(4096) + if data: + reader.feed_data(data) + else: + reader.feed_eof() + next(parser) + except StopIteration as exc: + assert isinstance(exc.value, Response) # help mypy + response = exc.value + if 200 <= response.status_code < 300: + return response + else: + raise InvalidProxyStatus(response) + except socket.timeout: + raise TimeoutError("timed out while connecting to HTTP proxy") + except Exception as exc: + raise InvalidProxyMessage( + "did not receive a valid HTTP response from proxy" + ) from exc + finally: + sock.settimeout(None) + + +def connect_http_proxy( + proxy: Proxy, + ws_uri: WebSocketURI, + deadline: Deadline, + *, + user_agent_header: str | None = None, + ssl: ssl_module.SSLContext | None = None, + server_hostname: str | None = None, + **kwargs: Any, +) -> socket.socket: + # Connect socket + + kwargs.setdefault("timeout", deadline.timeout()) + sock = socket.create_connection((proxy.host, proxy.port), **kwargs) + + # Initialize TLS wrapper and perform TLS handshake + + if proxy.scheme == "https": + if ssl is None: + ssl = ssl_module.create_default_context() + if server_hostname is None: + server_hostname = proxy.host + sock.settimeout(deadline.timeout()) + sock = ssl.wrap_socket(sock, server_hostname=server_hostname) + sock.settimeout(None) + + # Send CONNECT request to the proxy and read response. + + sock.sendall(prepare_connect_request(proxy, ws_uri, user_agent_header)) + try: + read_connect_response(sock, deadline) + except Exception: + sock.close() + raise + + return sock + + +T = TypeVar("T") +F = TypeVar("F", bound=Callable[..., T]) + + +class SSLSSLSocket: + """ + Socket-like object providing TLS-in-TLS. + + Only methods that are used by websockets are implemented. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + sock: socket.socket, + ssl_context: ssl_module.SSLContext, + server_hostname: str | None = None, + ) -> None: + self.incoming = ssl_module.MemoryBIO() + self.outgoing = ssl_module.MemoryBIO() + self.ssl_socket = sock + self.ssl_object = ssl_context.wrap_bio( + self.incoming, + self.outgoing, + server_hostname=server_hostname, + ) + self.run_io(self.ssl_object.do_handshake) + + def run_io(self, func: Callable[..., T], *args: Any) -> T: + while True: + want_read = False + want_write = False + try: + result = func(*args) + except ssl_module.SSLWantReadError: + want_read = True + except ssl_module.SSLWantWriteError: # pragma: no cover + want_write = True + + # Write outgoing data in all cases. + data = self.outgoing.read() + if data: + self.ssl_socket.sendall(data) + + # Read incoming data and retry on SSLWantReadError. + if want_read: + data = self.ssl_socket.recv(self.recv_bufsize) + if data: + self.incoming.write(data) + else: + self.incoming.write_eof() + continue + # Retry after writing outgoing data on SSLWantWriteError. + if want_write: # pragma: no cover + continue + # Return result if no error happened. + return result + + def recv(self, buflen: int) -> bytes: + try: + return self.run_io(self.ssl_object.read, buflen) + except ssl_module.SSLEOFError: + return b"" # always ignore ragged EOFs + + def send(self, data: BytesLike) -> int: + return self.run_io(self.ssl_object.write, data) + + def sendall(self, data: BytesLike) -> None: + # adapted from ssl_module.SSLSocket.sendall() + count = 0 + with memoryview(data) as view, view.cast("B") as byte_view: + amount = len(byte_view) + while count < amount: + count += self.send(byte_view[count:]) + + # recv_into(), recvfrom(), recvfrom_into(), sendto(), unwrap(), and the + # flags argument aren't implemented because websockets doesn't need them. + + def __getattr__(self, name: str) -> Any: + return getattr(self.ssl_socket, name) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/connection.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/connection.py new file mode 100644 index 0000000000000000000000000000000000000000..665f478ac9377174ca5c912f5939f81bdd8db3d7 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/connection.py @@ -0,0 +1,1078 @@ +from __future__ import annotations + +import contextlib +import logging +import random +import socket +import struct +import threading +import time +import uuid +from collections.abc import Iterable, Iterator, Mapping +from types import TracebackType +from typing import Any, Literal, overload + +from ..exceptions import ( + ConcurrencyError, + ConnectionClosed, + ConnectionClosedOK, + ProtocolError, +) +from ..frames import DATA_OPCODES, CloseCode, Frame, Opcode +from ..http11 import Request, Response +from ..protocol import CLOSED, OPEN, Event, Protocol, State +from ..typing import BytesLike, Data, DataLike, LoggerLike, Subprotocol +from .messages import Assembler +from .utils import Deadline + + +__all__ = ["Connection"] + + +class Connection: + """ + :mod:`threading` implementation of a WebSocket connection. + + :class:`Connection` provides APIs shared between WebSocket servers and + clients. + + You shouldn't use it directly. Instead, use + :class:`~websockets.sync.client.ClientConnection` or + :class:`~websockets.sync.server.ServerConnection`. + + """ + + recv_bufsize = 65536 + + def __init__( + self, + socket: socket.socket, + protocol: Protocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.socket = socket + self.protocol = protocol + self.ping_interval = ping_interval + self.ping_timeout = ping_timeout + self.close_timeout = close_timeout + if isinstance(max_queue, int) or max_queue is None: + max_queue_high, max_queue_low = max_queue, None + else: + max_queue_high, max_queue_low = max_queue + + # Inject reference to this instance in the protocol's logger. + self.protocol.logger = logging.LoggerAdapter( + self.protocol.logger, + {"websocket": self}, + ) + + # Copy attributes from the protocol for convenience. + self.id: uuid.UUID = self.protocol.id + """Unique identifier of the connection. Useful in logs.""" + self.logger: LoggerLike = self.protocol.logger + """Logger for this connection.""" + self.debug = self.protocol.debug + + # HTTP handshake request and response. + self.request: Request | None = None + """Opening handshake request.""" + self.response: Response | None = None + """Opening handshake response.""" + + # Mutex serializing interactions with the protocol. + self.protocol_mutex = threading.Lock() + + # Lock stopping reads when the assembler buffer is full. + self.recv_flow_control = threading.Lock() + + # Assembler turning frames into messages and serializing reads. + self.recv_messages = Assembler( + max_queue_high, + max_queue_low, + pause=self.recv_flow_control.acquire, + resume=self.recv_flow_control.release, + ) + + # Deadline for the closing handshake. + self.close_deadline: Deadline | None = None + + # Whether we are busy sending a fragmented message. + self.send_in_progress = False + + # Mapping of ping IDs to pong waiters, in chronological order. + self.pending_pings: dict[bytes, tuple[threading.Event, float, bool]] = {} + + self.latency: float = 0.0 + """ + Latency of the connection, in seconds. + + Latency is defined as the round-trip time of the connection. It is + measured by sending a Ping frame and waiting for a matching Pong frame. + Before the first measurement, :attr:`latency` is ``0.0``. + + By default, websockets enables a :ref:`keepalive ` mechanism + that sends Ping frames automatically at regular intervals. You can also + send Ping frames and measure latency with :meth:`ping`. + """ + + # Thread that sends keepalive pings. None when ping_interval is None. + self.keepalive_thread: threading.Thread | None = None + + # Exception raised while reading from the connection, to be chained to + # ConnectionClosed in order to show why the TCP connection dropped. + self.recv_exc: BaseException | None = None + + # Receiving events from the socket. This thread is marked as daemon to + # allow creating a connection in a non-daemon thread and using it in a + # daemon thread. This mustn't prevent the interpreter from exiting. + self.recv_events_thread = threading.Thread( + target=self.recv_events, + daemon=True, + ) + + # Start recv_events only after all attributes are initialized. + self.recv_events_thread.start() + + # Public attributes + + @property + def local_address(self) -> Any: + """ + Local address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getsockname`. + + """ + return self.socket.getsockname() + + @property + def remote_address(self) -> Any: + """ + Remote address of the connection. + + For IPv4 connections, this is a ``(host, port)`` tuple. + + The format of the address depends on the address family. + See :meth:`~socket.socket.getpeername`. + + """ + return self.socket.getpeername() + + @property + def state(self) -> State: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should call :meth:`~recv` or + :meth:`send` and handle :exc:`~websockets.exceptions.ConnectionClosed` + exceptions. + + """ + return self.protocol.state + + @property + def subprotocol(self) -> Subprotocol | None: + """ + Subprotocol negotiated during the opening handshake. + + :obj:`None` if no subprotocol was negotiated. + + """ + return self.protocol.subprotocol + + @property + def close_code(self) -> int | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_code + + @property + def close_reason(self) -> str | None: + """ + State of the WebSocket connection, defined in :rfc:`6455`. + + This attribute is provided for completeness. Typical applications + shouldn't check its value. Instead, they should inspect attributes + of :exc:`~websockets.exceptions.ConnectionClosed` exceptions. + + """ + return self.protocol.close_reason + + # Public methods + + def __enter__(self) -> Connection: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + if exc_type is None: + self.close() + else: + self.close(CloseCode.INTERNAL_ERROR) + + def __iter__(self) -> Iterator[Data]: + """ + Iterate on incoming messages. + + The iterator calls :meth:`recv` and yields messages in an infinite loop. + + It exits when the connection is closed normally. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` exception after a + protocol error or a network failure. + + """ + try: + while True: + yield self.recv() + except ConnectionClosedOK: + return + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def recv(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def recv(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def recv(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def recv( + self, timeout: float | None = None, *, decode: Literal[False] + ) -> bytes: ... + + @overload + def recv( + self, timeout: float | None = None, decode: bool | None = None + ) -> Data: ... + + def recv(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Receive the next message. + + When the connection is closed, :meth:`recv` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it raises + :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal closure + and :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. This is how you detect the end of the + message stream. + + If ``timeout`` is :obj:`None`, block until a message is received. If + ``timeout`` is set, wait up to ``timeout`` seconds for a message to be + received and return it, else raise :exc:`TimeoutError`. If ``timeout`` + is ``0`` or negative, check if a message has been received already and + return it, else raise :exc:`TimeoutError`. + + When the message is fragmented, :meth:`recv` waits until all fragments + are received, reassembles them, and returns the whole message. + + Args: + timeout: Timeout for receiving a message in seconds. + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + A string (:class:`str`) for a Text_ frame or a bytestring + (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + return a bytestring (:class:`bytes`). This improves performance + when decoding isn't needed, for example if the message contains + JSON and you're using a JSON library that expects a bytestring. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + return strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + return self.recv_messages.get(timeout, decode) + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + @overload + def recv_streaming(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def recv_streaming(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: ... + + def recv_streaming(self, decode: bool | None = None) -> Iterator[Data]: + """ + Receive the next message frame by frame. + + This method is designed for receiving fragmented messages. It returns an + iterator that yields each fragment as it is received. This iterator must + be fully consumed. Else, future calls to :meth:`recv` or + :meth:`recv_streaming` will raise + :exc:`~websockets.exceptions.ConcurrencyError`, making the connection + unusable. + + :meth:`recv_streaming` raises the same exceptions as :meth:`recv`. + + Args: + decode: Set this flag to override the default behavior of returning + :class:`str` or :class:`bytes`. See below for details. + + Returns: + An iterator of strings (:class:`str`) for a Text_ frame or + bytestrings (:class:`bytes`) for a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``decode`` argument: + + * Set ``decode=False`` to disable UTF-8 decoding of Text_ frames and + yield bytestrings (:class:`bytes`). This improves performance + when decoding isn't needed. + * Set ``decode=True`` to force UTF-8 decoding of Binary_ frames and + yield strings (:class:`str`). This may be useful for servers that + send binary frames instead of text frames. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If two threads call :meth:`recv` or + :meth:`recv_streaming` concurrently. + + """ + try: + yield from self.recv_messages.get_iter(decode) + return + except EOFError: + pass + # fallthrough + except ConcurrencyError: + raise ConcurrencyError( + "cannot call recv_streaming while another thread " + "is already running recv or recv_streaming" + ) from None + except UnicodeDecodeError as exc: + with self.send_context(): + self.protocol.fail( + CloseCode.INVALID_DATA, + f"{exc.reason} at position {exc.start}", + ) + # fallthrough + + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from self.recv_exc + + def send( + self, + message: DataLike | Iterable[DataLike], + text: bool | None = None, + ) -> None: + """ + Send a message. + + A string (:class:`str`) is sent as a Text_ frame. A bytestring or + bytes-like object (:class:`bytes`, :class:`bytearray`, or + :class:`memoryview`) is sent as a Binary_ frame. + + .. _Text: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + .. _Binary: https://datatracker.ietf.org/doc/html/rfc6455#section-5.6 + + You may override this behavior with the ``text`` argument: + + * Set ``text=True`` to send an UTF-8 bytestring or bytes-like object + (:class:`bytes`, :class:`bytearray`, or :class:`memoryview`) in a + Text_ frame. This improves performance when the message is already + UTF-8 encoded, for example if the message contains JSON and you're + using a JSON library that produces a bytestring. + * Set ``text=False`` to send a string (:class:`str`) in a Binary_ + frame. This may be useful for servers that expect binary frames + instead of text frames. + + :meth:`send` also accepts an iterable of strings, bytestrings, or + bytes-like objects to enable fragmentation_. Each item is treated as a + message fragment and sent in its own frame. All items must be of the + same type, or else :meth:`send` will raise a :exc:`TypeError` and the + connection will be closed. + + .. _fragmentation: https://datatracker.ietf.org/doc/html/rfc6455#section-5.4 + + :meth:`send` rejects dict-like objects because this is often an error. + (If you really want to send the keys of a dict-like object as fragments, + call its :meth:`~dict.keys` method and pass the result to :meth:`send`.) + + When the connection is closed, :meth:`send` raises + :exc:`~websockets.exceptions.ConnectionClosed`. Specifically, it + raises :exc:`~websockets.exceptions.ConnectionClosedOK` after a normal + connection closure and + :exc:`~websockets.exceptions.ConnectionClosedError` after a protocol + error or a network failure. + + Args: + message: Message to send. + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If the connection is sending a fragmented message. + TypeError: If ``message`` doesn't have a supported type. + + """ + # Unfragmented message -- this case must be handled first because + # strings and bytes-like objects are iterable. + + if isinstance(message, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is False: + self.protocol.send_binary(message.encode()) + else: + self.protocol.send_text(message.encode()) + + elif isinstance(message, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread is already running send" + ) + if text is True: + self.protocol.send_text(message) + else: + self.protocol.send_binary(message) + + # Catch a common mistake -- passing a dict to send(). + + elif isinstance(message, Mapping): + raise TypeError("data is a dict-like object") + + # Fragmented message -- regular iterator. + + elif isinstance(message, Iterable): + chunks = iter(message) + try: + chunk = next(chunks) + except StopIteration: + return + + try: + # First fragment. + if isinstance(chunk, str): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is False: + self.protocol.send_binary(chunk.encode(), fin=False) + else: + self.protocol.send_text(chunk.encode(), fin=False) + encode = True + elif isinstance(chunk, BytesLike): + with self.send_context(): + if self.send_in_progress: + raise ConcurrencyError( + "cannot call send while another thread " + "is already running send" + ) + self.send_in_progress = True + if text is True: + self.protocol.send_text(chunk, fin=False) + else: + self.protocol.send_binary(chunk, fin=False) + encode = False + else: + raise TypeError("iterable must contain bytes or str") + + # Other fragments + for chunk in chunks: + if isinstance(chunk, str) and encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk.encode(), fin=False) + elif isinstance(chunk, BytesLike) and not encode: + with self.send_context(): + assert self.send_in_progress + self.protocol.send_continuation(chunk, fin=False) + else: + raise TypeError("iterable must contain uniform types") + + # Final fragment. + with self.send_context(): + self.protocol.send_continuation(b"", fin=True) + self.send_in_progress = False + + except ConcurrencyError: + # We didn't start sending a fragmented message. + # The connection is still usable. + raise + + except Exception: + # We're half-way through a fragmented message and we can't + # complete it. This makes the connection unusable. + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "error in fragmented message", + ) + raise + + else: + raise TypeError("data must be str, bytes, or iterable") + + def close( + self, + code: CloseCode | int = CloseCode.NORMAL_CLOSURE, + reason: str = "", + ) -> None: + """ + Perform the closing handshake. + + :meth:`close` waits for the other end to complete the handshake and + for the TCP connection to terminate. + + :meth:`close` is idempotent: it doesn't do anything once the + connection is closed. + + Args: + code: WebSocket close code. + reason: WebSocket close reason. + + """ + try: + # The context manager takes care of waiting for the TCP connection + # to terminate after calling a method that sends a close frame. + with self.send_context(): + if self.send_in_progress: + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "close during fragmented message", + ) + else: + self.protocol.send_close(code, reason) + except ConnectionClosed: + # Ignore ConnectionClosed exceptions raised from send_context(). + # They mean that the connection is closed, which was the goal. + pass + + def ping( + self, + data: DataLike | None = None, + ack_on_close: bool = False, + ) -> threading.Event: + """ + Send a Ping_. + + .. _Ping: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.2 + + A ping may serve as a keepalive or as a check that the remote endpoint + received all messages up to this point + + Args: + data: Payload of the ping. A :class:`str` will be encoded to UTF-8. + If ``data`` is :obj:`None`, the payload is four random bytes. + ack_on_close: when this option is :obj:`True`, the event will also + be set when the connection is closed. While this avoids getting + stuck waiting for a pong that will never arrive, it requires + checking that the state of the connection is still ``OPEN`` to + confirm that a pong was received, rather than the connection + being closed. + + Returns: + An event that will be set when the corresponding pong is received. + You can ignore it if you don't intend to wait. + + :: + + pong_received = ws.ping() + # only if you want to wait for the corresponding pong + pong_received.wait() + + Raises: + ConnectionClosed: When the connection is closed. + ConcurrencyError: If another ping was sent with the same data and + the corresponding pong wasn't received yet. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + elif data is not None: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + # Protect against duplicates if a payload is explicitly set. + if data in self.pending_pings: + raise ConcurrencyError("already waiting for a pong with the same data") + + # Generate a unique random payload otherwise. + while data is None or data in self.pending_pings: + data = struct.pack("!I", random.getrandbits(32)) + + pong_received = threading.Event() + ping_timestamp = time.monotonic() + self.pending_pings[data] = (pong_received, ping_timestamp, ack_on_close) + self.protocol.send_ping(data) + return pong_received + + def pong(self, data: DataLike = b"") -> None: + """ + Send a Pong_. + + .. _Pong: https://datatracker.ietf.org/doc/html/rfc6455#section-5.5.3 + + An unsolicited pong may serve as a unidirectional heartbeat. + + Args: + data: Payload of the pong. A :class:`str` will be encoded to UTF-8. + + Raises: + ConnectionClosed: When the connection is closed. + + """ + if isinstance(data, BytesLike): + data = bytes(data) + elif isinstance(data, str): + data = data.encode() + else: + raise TypeError("data must be str or bytes-like") + + with self.send_context(): + self.protocol.send_pong(data) + + # Private methods + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + This method is overridden in subclasses to handle the handshake. + + """ + assert isinstance(event, Frame) + if event.opcode in DATA_OPCODES: + self.recv_messages.put(event) + + if event.opcode is Opcode.PONG: + self.acknowledge_pings(bytes(event.data)) + + def acknowledge_pings(self, data: bytes) -> None: + """ + Acknowledge pings when receiving a pong. + + """ + with self.protocol_mutex: + # Ignore unsolicited pong. + if data not in self.pending_pings: + return + + pong_timestamp = time.monotonic() + + # Sending a pong for only the most recent ping is legal. + # Acknowledge all previous pings too in that case. + ping_id = None + ping_ids = [] + for ping_id, ( + pong_received, + ping_timestamp, + _ack_on_close, + ) in self.pending_pings.items(): + ping_ids.append(ping_id) + pong_received.set() + if ping_id == data: + self.latency = pong_timestamp - ping_timestamp + break + else: + raise AssertionError("solicited pong not found in pings") + + # Remove acknowledged pings from self.pending_pings. + for ping_id in ping_ids: + del self.pending_pings[ping_id] + + def terminate_pending_pings(self) -> None: + """ + Acknowledge pending pings when the connection is closed. + + """ + assert self.protocol_mutex.locked() + assert self.protocol.state is CLOSED + + for pong_received, _ping_timestamp, ack_on_close in self.pending_pings.values(): + if ack_on_close: + pong_received.set() + + self.pending_pings.clear() + + def keepalive(self) -> None: + """ + Send a Ping frame and wait for a Pong frame at regular intervals. + + """ + assert self.ping_interval is not None + try: + while True: + # If self.ping_timeout > self.latency > self.ping_interval, + # pings will be sent immediately after receiving pongs. + # The period will be longer than self.ping_interval. + self.recv_events_thread.join(self.ping_interval - self.latency) + if not self.recv_events_thread.is_alive(): + break + + try: + pong_received = self.ping(ack_on_close=True) + except ConnectionClosed: + break + if self.debug: + self.logger.debug("% sent keepalive ping") + + if self.ping_timeout is not None: + if pong_received.wait(self.ping_timeout): + if self.debug: + self.logger.debug("% received keepalive pong") + else: + if self.debug: + self.logger.debug("- timed out waiting for keepalive pong") + with self.send_context(): + self.protocol.fail( + CloseCode.INTERNAL_ERROR, + "keepalive ping timeout", + ) + break + except Exception: + self.logger.error("keepalive ping failed", exc_info=True) + + def start_keepalive(self) -> None: + """ + Run :meth:`keepalive` in a thread, unless keepalive is disabled. + + """ + if self.ping_interval is not None: + # This thread is marked as daemon like self.recv_events_thread. + self.keepalive_thread = threading.Thread( + target=self.keepalive, + daemon=True, + ) + self.keepalive_thread.start() + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + Run this method in a thread as long as the connection is alive. + + ``recv_events()`` exits immediately when ``self.socket`` is closed. + + """ + try: + while True: + try: + # If the assembler buffer is full, block until it drains. + with self.recv_flow_control: + pass + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + data = self.socket.recv(self.recv_bufsize) + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while receiving data", + exc_info=True, + ) + # When the closing handshake is initiated by our side, + # recv() may block until send_context() closes the socket. + # In that case, send_context() already set recv_exc. + # Calling set_recv_exc() avoids overwriting it. + with self.protocol_mutex: + self.set_recv_exc(exc) + break + + if data == b"": + break + + # Acquire the connection lock. + with self.protocol_mutex: + # Feed incoming data to the protocol. + self.protocol.receive_data(data) + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # Similarly to the above, avoid overriding an exception + # set by send_context(), in case of a race condition + # i.e. send_context() closes the socket after recv() + # returns above but before send_data() calls send(). + self.set_recv_exc(exc) + break + + # If needed, set the close deadline based on the close timeout. + if self.protocol.close_expected(): + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + + # Unlock conn_mutex before processing events. Else, the + # application can't send messages in response to events. + + # If self.send_data raised an exception, then events are lost. + # Given that automatic responses write small amounts of data, + # this should be uncommon, so we don't handle the edge case. + + for event in events: + # This isn't expected to raise an exception. + self.process_event(event) + + # Breaking out of the while True: ... loop means that we believe + # that the socket doesn't work anymore. + + with self.protocol_mutex: + # Feed the end of the data stream to the protocol. + self.protocol.receive_eof() + + # This isn't expected to raise an exception. + events = self.protocol.events_received() + + # There is no error handling because send_data() can only write + # the end of the data stream and it handles errors by itself. + self.send_data() + + # This code path is triggered when receiving an HTTP response + # without a Content-Length header. This is the only case where + # reading until EOF generates an event; all other events have + # a known length. Ignore for coverage measurement because tests + # are in test_client.py rather than test_connection.py. + for event in events: # pragma: no cover + # This isn't expected to raise an exception. + self.process_event(event) + + except Exception as exc: + # This branch should never run. It's a safety net in case of bugs. + self.logger.error("unexpected internal error", exc_info=True) + with self.protocol_mutex: + self.set_recv_exc(exc) + finally: + # This isn't expected to raise an exception. + self.close_socket() + + @contextlib.contextmanager + def send_context( + self, + *, + expected_state: State = OPEN, # CONNECTING during the opening handshake + ) -> Iterator[None]: + """ + Create a context for writing to the connection from user code. + + On entry, :meth:`send_context` acquires the connection lock and checks + that the connection is open; on exit, it writes outgoing data to the + socket and releases the connection lock:: + + with self.send_context(): + self.protocol.send_text(message.encode()) + + When the connection isn't open on entry, when the connection is expected + to close on exit, or when an unexpected error happens, terminating the + connection, :meth:`send_context` waits until the connection is closed + then raises :exc:`~websockets.exceptions.ConnectionClosed`. + + """ + # Should we wait until the connection is closed? + wait_for_close = False + # Should we close the socket and raise ConnectionClosed? + raise_close_exc = False + # What exception should we chain ConnectionClosed to? + original_exc: BaseException | None = None + + # Acquire the protocol lock. + with self.protocol_mutex: + if self.protocol.state is expected_state: + # Let the caller interact with the protocol. + try: + yield + except (ProtocolError, ConcurrencyError): + # The protocol state wasn't changed. Exit immediately. + raise + except Exception as exc: + self.logger.error("unexpected internal error", exc_info=True) + # This branch should never run. It's a safety net in case of + # bugs. Since we don't know what happened, we will close the + # connection and raise the exception to the caller. + wait_for_close = False + raise_close_exc = True + original_exc = exc + else: + # Check if the connection is expected to close soon. + if self.protocol.close_expected(): + wait_for_close = True + # Set the close deadline based on the close timeout. + # Since we tested earlier that protocol.state is OPEN + # (or CONNECTING) and we didn't release protocol_mutex, + # self.close_deadline is still None. + assert self.close_deadline is None + self.close_deadline = Deadline(self.close_timeout) + # Write outgoing data to the socket. + try: + self.send_data() + except Exception as exc: + if self.debug: + self.logger.debug( + "! error while sending data", + exc_info=True, + ) + # While the only expected exception here is OSError, + # other exceptions would be treated identically. + wait_for_close = False + raise_close_exc = True + original_exc = exc + + else: # self.protocol.state is not expected_state + # Minor layering violation: we assume that the connection + # will be closing soon if it isn't in the expected state. + wait_for_close = True + # Calculate close_deadline if it wasn't set yet. + if self.close_deadline is None: + self.close_deadline = Deadline(self.close_timeout) + raise_close_exc = True + + # To avoid a deadlock, release the connection lock by exiting the + # context manager before waiting for recv_events() to terminate. + + # If the connection is expected to close soon and the close timeout + # elapses, close the socket to terminate the connection. + if wait_for_close: + # Thread.join() returns immediately if timeout is negative. + assert self.close_deadline is not None + timeout = self.close_deadline.timeout(raise_if_elapsed=False) + self.recv_events_thread.join(timeout) + if self.recv_events_thread.is_alive(): + # There's no risk of overwriting another error because + # original_exc is never set when wait_for_close is True. + assert original_exc is None + original_exc = TimeoutError("timed out while closing connection") + # Set recv_exc before closing the socket in order to get + # proper exception reporting. + raise_close_exc = True + with self.protocol_mutex: + self.set_recv_exc(original_exc) + + # If an error occurred, close the socket to terminate the connection and + # raise an exception. + if raise_close_exc: + self.close_socket() + # Wait for the protocol state to be CLOSED before accessing close_exc. + self.recv_events_thread.join() + raise self.protocol.close_exc from original_exc + + def send_data(self) -> None: + """ + Send outgoing data. + + This method requires holding protocol_mutex. + + """ + assert self.protocol_mutex.locked() + for data in self.protocol.data_to_send(): + if data: + if self.close_deadline is not None: + self.socket.settimeout(self.close_deadline.timeout()) + self.socket.sendall(data) + else: + try: + self.socket.shutdown(socket.SHUT_WR) + except OSError: # socket already closed + pass + + def set_recv_exc(self, exc: BaseException | None) -> None: + """ + Set recv_exc, if not set yet. + + This method requires holding protocol_mutex and must be called only from + the thread running recv_events(). + + """ + assert self.protocol_mutex.locked() + if self.recv_exc is None: + self.recv_exc = exc + + def close_socket(self) -> None: + """ + Shutdown and close socket. Close message assembler. + + Calling close_socket() guarantees that recv_events() terminates. Indeed, + recv_events() may block only on socket.recv() or on recv_messages.put(). + + """ + # shutdown() is required to interrupt recv() on Linux. + try: + self.socket.shutdown(socket.SHUT_RDWR) + except OSError: # socket already closed + pass + self.socket.close() + + # Calling protocol.receive_eof() is safe because it's idempotent. + # This guarantees that the protocol state becomes CLOSED. + with self.protocol_mutex: + self.protocol.receive_eof() + assert self.protocol.state is CLOSED + + # Abort recv() with a ConnectionClosed exception. + self.recv_messages.close() + + # Acknowledge pings sent with the ack_on_close option. + self.terminate_pending_pings() diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/messages.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/messages.py new file mode 100644 index 0000000000000000000000000000000000000000..d95519f63ecfb20e681de13ed6bf3481c966d2d3 --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/messages.py @@ -0,0 +1,348 @@ +from __future__ import annotations + +import codecs +import queue +import threading +from typing import Any, Callable, Iterable, Iterator, Literal, overload + +from ..exceptions import ConcurrencyError +from ..frames import OP_BINARY, OP_CONT, OP_TEXT, Frame +from ..typing import Data +from .utils import Deadline + + +__all__ = ["Assembler"] + +UTF8Decoder = codecs.getincrementaldecoder("utf-8") + + +class Assembler: + """ + Assemble messages from frames. + + :class:`Assembler` expects only data frames. The stream of frames must + respect the protocol; if it doesn't, the behavior is undefined. + + Args: + pause: Called when the buffer of frames goes above the high water mark; + should pause reading from the network. + resume: Called when the buffer of frames goes below the low water mark; + should resume reading from the network. + + """ + + def __init__( + self, + high: int | None = None, + low: int | None = None, + pause: Callable[[], Any] = lambda: None, + resume: Callable[[], Any] = lambda: None, + ) -> None: + # Serialize reads and writes -- except for reads via synchronization + # primitives provided by the threading and queue modules. + self.mutex = threading.Lock() + + # Queue of incoming frames. + self.frames: queue.SimpleQueue[Frame | None] = queue.SimpleQueue() + + # We cannot put a hard limit on the size of the queue because a single + # call to Protocol.data_received() could produce thousands of frames, + # which must be buffered. Instead, we pause reading when the buffer goes + # above the high limit and we resume when it goes under the low limit. + if high is not None and low is None: + low = high // 4 + if high is None and low is not None: + high = low * 4 + if high is not None and low is not None: + if low < 0: + raise ValueError("low must be positive or equal to zero") + if high < low: + raise ValueError("high must be greater than or equal to low") + self.high, self.low = high, low + self.pause = pause + self.resume = resume + self.paused = False + + # This flag prevents concurrent calls to get() by user code. + self.get_in_progress = False + + # This flag marks the end of the connection. + self.closed = False + + def get_next_frame(self, timeout: float | None = None) -> Frame: + # Helper to factor out the logic for getting the next frame from the + # queue, while handling timeouts and reaching the end of the stream. + if self.closed: + try: + frame = self.frames.get(block=False) + except queue.Empty: + raise EOFError("stream of frames ended") from None + else: + try: + # Check for a frame that's already received if timeout <= 0. + # SimpleQueue.get() doesn't support negative timeout values. + if timeout is not None and timeout <= 0: + frame = self.frames.get(block=False) + else: + frame = self.frames.get(block=True, timeout=timeout) + except queue.Empty: + raise TimeoutError(f"timed out in {timeout:.1f}s") from None + if frame is None: + raise EOFError("stream of frames ended") + return frame + + def reset_queue(self, frames: Iterable[Frame]) -> None: + # Helper to put frames back into the queue after they were fetched. + # This happens only when the queue is empty. However, by the time + # we acquire self.mutex, put() may have added items in the queue. + # Therefore, we must handle the case where the queue is not empty. + frame: Frame | None + with self.mutex: + queued = [] + try: + while True: + queued.append(self.frames.get(block=False)) + except queue.Empty: + pass + for frame in frames: + self.frames.put(frame) + # This loop runs only when a race condition occurs. + for frame in queued: # pragma: no cover + self.frames.put(frame) + + # This overload structure is required to avoid the error: + # "parameter without a default follows parameter with a default" + + @overload + def get(self, timeout: float | None, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[True]) -> str: ... + + @overload + def get(self, timeout: float | None = None, *, decode: Literal[False]) -> bytes: ... + + @overload + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: ... + + def get(self, timeout: float | None = None, decode: bool | None = None) -> Data: + """ + Read the next message. + + :meth:`get` returns a single :class:`str` or :class:`bytes`. + + If the message is fragmented, :meth:`get` waits until the last frame is + received, then it reassembles the message and returns it. To receive + messages frame by frame, use :meth:`get_iter` instead. + + Args: + timeout: If a timeout is provided and elapses before a complete + message is received, :meth:`get` raises :exc:`TimeoutError`. + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + TimeoutError: If a timeout is provided and elapses before a + complete message is received. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get() fetches a complete message or times out. + + try: + deadline = Deadline(timeout) + + # Fetch the first frame. + frame = self.get_next_frame(deadline.timeout(raise_if_elapsed=False)) + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + frames = [frame] + + # Fetch subsequent frames for fragmented messages. + while not frame.fin: + try: + frame = self.get_next_frame( + deadline.timeout(raise_if_elapsed=False) + ) + except TimeoutError: + # Put frames already received back into the queue + # so that future calls to get() can return them. + self.reset_queue(frames) + raise + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + frames.append(frame) + + finally: + self.get_in_progress = False + + # This converts frame.data to bytes when it's a bytearray. + data = b"".join(frame.data for frame in frames) + if decode: + return data.decode() + else: + return data + + @overload + def get_iter(self, decode: Literal[True]) -> Iterator[str]: ... + + @overload + def get_iter(self, decode: Literal[False]) -> Iterator[bytes]: ... + + @overload + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: ... + + def get_iter(self, decode: bool | None = None) -> Iterator[Data]: + """ + Stream the next message. + + Iterating the return value of :meth:`get_iter` yields a :class:`str` or + :class:`bytes` for each frame in the message. + + The iterator must be fully consumed before calling :meth:`get_iter` or + :meth:`get` again. Else, :exc:`ConcurrencyError` is raised. + + This method only makes sense for fragmented messages. If messages aren't + fragmented, use :meth:`get` instead. + + Args: + decode: :obj:`False` disables UTF-8 decoding of text frames and + returns :class:`bytes`. :obj:`True` forces UTF-8 decoding of + binary frames and returns :class:`str`. + + Raises: + EOFError: If the stream of frames has ended. + UnicodeDecodeError: If a text frame contains invalid UTF-8. + ConcurrencyError: If two coroutines run :meth:`get` or + :meth:`get_iter` concurrently. + + """ + with self.mutex: + if self.get_in_progress: + raise ConcurrencyError("get() or get_iter() is already running") + self.get_in_progress = True + + # Locking with get_in_progress prevents concurrent execution + # until get_iter() fetches a complete message or times out. + + # If get_iter() raises an exception e.g. in decoder.decode(), + # get_in_progress remains set and the connection becomes unusable. + + # Yield the first frame. + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_TEXT or frame.opcode is OP_BINARY + if decode is None: + decode = frame.opcode is OP_TEXT + if decode: + decoder = UTF8Decoder() + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + # Yield subsequent frames for fragmented messages. + while not frame.fin: + frame = self.get_next_frame() + with self.mutex: + self.maybe_resume() + assert frame.opcode is OP_CONT + if decode: + yield decoder.decode(frame.data, frame.fin) + else: + # Convert to bytes when frame.data is a bytearray. + yield bytes(frame.data) + + self.get_in_progress = False + + def put(self, frame: Frame) -> None: + """ + Add ``frame`` to the next message. + + Raises: + EOFError: If the stream of frames has ended. + + """ + with self.mutex: + if self.closed: + raise EOFError("stream of frames ended") + + self.frames.put(frame) + self.maybe_pause() + + # put() and get/get_iter() call maybe_pause() and maybe_resume() while + # holding self.mutex. This guarantees that the calls interleave properly. + # Specifically, it prevents a race condition where maybe_resume() would + # run before maybe_pause(), leaving the connection incorrectly paused. + + # A race condition is possible when get/get_iter() call self.frames.get() + # without holding self.mutex. However, it's harmless — and even beneficial! + # It can only result in popping an item from the queue before maybe_resume() + # runs and skipping a pause() - resume() cycle that would otherwise occur. + + def maybe_pause(self) -> None: + """Pause the writer if queue is above the high water mark.""" + # Skip if flow control is disabled. + if self.high is None: + return + + assert self.mutex.locked() + + # Check for "> high" to support high = 0. + if self.frames.qsize() > self.high and not self.paused: + self.paused = True + self.pause() + + def maybe_resume(self) -> None: + """Resume the writer if queue is below the low water mark.""" + # Skip if flow control is disabled. + if self.low is None: + return + + assert self.mutex.locked() + + # Check for "<= low" to support low = 0. + if self.frames.qsize() <= self.low and self.paused: + self.paused = False + self.resume() + + def close(self) -> None: + """ + End the stream of frames. + + Calling :meth:`close` concurrently with :meth:`get`, :meth:`get_iter`, + or :meth:`put` is safe. They will raise :exc:`EOFError`. + + """ + with self.mutex: + if self.closed: + return + + self.closed = True + + if self.get_in_progress: + # Unblock get() or get_iter(). + self.frames.put(None) + + if self.paused: + # Unblock recv_events(). + self.paused = False + self.resume() diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/router.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/router.py new file mode 100644 index 0000000000000000000000000000000000000000..1c35e8aaea909b3dd1a16f9346cd94f5063aa17c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/router.py @@ -0,0 +1,213 @@ +from __future__ import annotations + +import http +import ssl as ssl_module +import urllib.parse +from typing import Any, Callable, Literal + +from ..http11 import Request, Response +from .server import Server, ServerConnection, serve + + +__all__ = ["route", "unix_route", "Router"] + + +try: + from werkzeug.exceptions import NotFound + from werkzeug.routing import Map, RequestRedirect + +except ImportError: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("route() requires werkzeug") + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + raise ImportError("unix_route() requires werkzeug") + +else: + + def route( + url_map: Map, + *args: Any, + server_name: str | None = None, + ssl: ssl_module.SSLContext | Literal[True] | None = None, + create_router: type[Router] | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket server dispatching connections to different handlers. + + This feature requires the third-party library `werkzeug`_: + + .. code-block:: console + + $ pip install werkzeug + + .. _werkzeug: https://werkzeug.palletsprojects.com/ + + :func:`route` accepts the same arguments as + :func:`~websockets.sync.server.serve`, except as described below. + + The first argument is a :class:`werkzeug.routing.Map` that maps URL patterns + to connection handlers. In addition to the connection, handlers receive + parameters captured in the URL as keyword arguments. + + Here's an example:: + + + from websockets.sync.router import route + from werkzeug.routing import Map, Rule + + def channel_handler(websocket, channel_id): + ... + + url_map = Map([ + Rule("/channel/", endpoint=channel_handler), + ... + ]) + + with route(url_map, ...) as server: + server.serve_forever() + + Refer to the documentation of :mod:`werkzeug.routing` for details. + + If you define redirects with ``Rule(..., redirect_to=...)`` in the URL map, + when the server runs behind a reverse proxy that modifies the ``Host`` + header or terminates TLS, you need additional configuration: + + * Set ``server_name`` to the name of the server as seen by clients. When + not provided, websockets uses the value of the ``Host`` header. + + * Set ``ssl=True`` to generate ``wss://`` URIs without enabling TLS. + Under the hood, this bind the URL map with a ``url_scheme`` of + ``wss://`` instead of ``ws://``. + + There is no need to specify ``websocket=True`` in each rule. It is added + automatically. + + Args: + url_map: Mapping of URL patterns to connection handlers. + server_name: Name of the server as seen by clients. If :obj:`None`, + websockets uses the value of the ``Host`` header. + ssl: Configuration for enabling TLS on the connection. Set it to + :obj:`True` if a reverse proxy terminates TLS connections. + create_router: Factory for the :class:`Router` dispatching requests to + handlers. Set it to a wrapper or a subclass to customize routing. + + """ + url_scheme = "ws" if ssl is None else "wss" + if ssl is not True and ssl is not None: + kwargs["ssl"] = ssl + + if create_router is None: + create_router = Router + + router = create_router(url_map, server_name, url_scheme) + + _process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = kwargs.pop("process_request", None) + if _process_request is None: + process_request: Callable[ + [ServerConnection, Request], + Response | None, + ] = router.route_request + else: + + def process_request( + connection: ServerConnection, request: Request + ) -> Response | None: + response = _process_request(connection, request) + if response is not None: + return response + return router.route_request(connection, request) + + return serve(router.handler, *args, process_request=process_request, **kwargs) + + def unix_route( + url_map: Map, + path: str | None = None, + **kwargs: Any, + ) -> Server: + """ + Create a WebSocket Unix server dispatching connections to different handlers. + + :func:`unix_route` combines the behaviors of :func:`route` and + :func:`~websockets.sync.server.unix_serve`. + + Args: + url_map: Mapping of URL patterns to connection handlers. + path: File system path to the Unix socket. + + """ + return route(url_map, unix=True, path=path, **kwargs) + + +class Router: + """WebSocket router supporting :func:`route`.""" + + def __init__( + self, + url_map: Map, + server_name: str | None = None, + url_scheme: str = "ws", + ) -> None: + self.url_map = url_map + self.server_name = server_name + self.url_scheme = url_scheme + for rule in self.url_map.iter_rules(): + rule.websocket = True + + def get_server_name(self, connection: ServerConnection, request: Request) -> str: + if self.server_name is None: + return request.headers["Host"] + else: + return self.server_name + + def redirect(self, connection: ServerConnection, url: str) -> Response: + response = connection.respond(http.HTTPStatus.FOUND, f"Found at {url}") + response.headers["Location"] = url + return response + + def not_found(self, connection: ServerConnection) -> Response: + return connection.respond(http.HTTPStatus.NOT_FOUND, "Not Found") + + def route_request( + self, connection: ServerConnection, request: Request + ) -> Response | None: + """Route incoming request.""" + url_map_adapter = self.url_map.bind( + server_name=self.get_server_name(connection, request), + url_scheme=self.url_scheme, + ) + try: + parsed = urllib.parse.urlparse(request.path) + handler, kwargs = url_map_adapter.match( + path_info=parsed.path, + query_args=parsed.query, + ) + except RequestRedirect as redirect: + return self.redirect(connection, redirect.new_url) + except NotFound: + return self.not_found(connection) + connection.handler, connection.handler_kwargs = handler, kwargs + return None + + def handler(self, connection: ServerConnection) -> None: + """Handle a connection.""" + return connection.handler(connection, **connection.handler_kwargs) diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/server.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/server.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd82fbad36e10e2f7a6a96cbcfba432b7ee780c --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/server.py @@ -0,0 +1,765 @@ +from __future__ import annotations + +import hmac +import http +import logging +import os +import re +import selectors +import socket +import ssl as ssl_module +import sys +import threading +import warnings +from collections.abc import Iterable, Sequence +from types import TracebackType +from typing import Any, Callable, Mapping, cast + +from ..exceptions import InvalidHeader +from ..extensions.base import ServerExtensionFactory +from ..extensions.permessage_deflate import enable_server_permessage_deflate +from ..frames import CloseCode +from ..headers import ( + build_www_authenticate_basic, + parse_authorization_basic, + validate_subprotocols, +) +from ..http11 import SERVER, Request, Response +from ..protocol import CONNECTING, OPEN, Event +from ..server import ServerProtocol +from ..typing import LoggerLike, Origin, StatusLike, Subprotocol +from .connection import Connection +from .utils import Deadline + + +__all__ = ["serve", "unix_serve", "ServerConnection", "Server", "basic_auth"] + + +class ServerConnection(Connection): + """ + :mod:`threading` implementation of a WebSocket server connection. + + :class:`ServerConnection` provides :meth:`recv` and :meth:`send` methods for + receiving and sending messages. + + It supports iteration to receive messages:: + + for message in websocket: + process(message) + + The iterator exits normally when the connection is closed with code + 1000 (OK) or 1001 (going away) or without a close code. It raises a + :exc:`~websockets.exceptions.ConnectionClosedError` when the connection is + closed with any other code. + + The ``ping_interval``, ``ping_timeout``, ``close_timeout``, and + ``max_queue`` arguments have the same meaning as in :func:`serve`. + + Args: + socket: Socket connected to a WebSocket client. + protocol: Sans-I/O connection. + + """ + + def __init__( + self, + socket: socket.socket, + protocol: ServerProtocol, + *, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + max_queue: int | None | tuple[int | None, int | None] = 16, + ) -> None: + self.protocol: ServerProtocol + self.request_rcvd = threading.Event() + super().__init__( + socket, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + self.username: str # see basic_auth() + self.handler: Callable[[ServerConnection], None] # see route() + self.handler_kwargs: Mapping[str, Any] # see route() + + def respond(self, status: StatusLike, text: str) -> Response: + """ + Create a plain text HTTP response. + + ``process_request`` and ``process_response`` may call this method to + return an HTTP response instead of performing the WebSocket opening + handshake. + + You can modify the response before returning it, for example by changing + HTTP headers. + + Args: + status: HTTP status code. + text: HTTP response body; it will be encoded to UTF-8. + + Returns: + HTTP response to send to the client. + + """ + return self.protocol.reject(status, text) + + def handshake( + self, + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + timeout: float | None = None, + ) -> None: + """ + Perform the opening handshake. + + """ + if not self.request_rcvd.wait(timeout): + raise TimeoutError("timed out while waiting for handshake request") + + if self.request is not None: + with self.send_context(expected_state=CONNECTING): + response = None + + if process_request is not None: + try: + response = process_request(self, self.request) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is None: + self.response = self.protocol.accept(self.request) + else: + self.response = response + + if server_header: + self.response.headers["Server"] = server_header + + response = None + + if process_response is not None: + try: + response = process_response(self, self.request, self.response) + except Exception as exc: + self.protocol.handshake_exc = exc + response = self.protocol.reject( + http.HTTPStatus.INTERNAL_SERVER_ERROR, + ( + "Failed to open a WebSocket connection.\n" + "See server log for more information.\n" + ), + ) + + if response is not None: + self.response = response + + self.protocol.send_response(self.response) + + # self.protocol.handshake_exc is set when the connection is lost before + # receiving a request, when the request cannot be parsed, or when the + # handshake fails, including when process_request or process_response + # raises an exception. + + # It isn't set when process_request or process_response sends an HTTP + # response that rejects the handshake. + + if self.protocol.handshake_exc is not None: + raise self.protocol.handshake_exc + + def process_event(self, event: Event) -> None: + """ + Process one incoming event. + + """ + # First event - handshake request. + if self.request is None: + assert isinstance(event, Request) + self.request = event + self.request_rcvd.set() + # Later events - frames. + else: + super().process_event(event) + + def recv_events(self) -> None: + """ + Read incoming data from the socket and process events. + + """ + try: + super().recv_events() + finally: + # If the connection is closed during the handshake, unblock it. + self.request_rcvd.set() + + +class Server: + """ + WebSocket server returned by :func:`serve`. + + This class mirrors the API of :class:`~socketserver.BaseServer`, notably the + :meth:`~socketserver.BaseServer.serve_forever` and + :meth:`~socketserver.BaseServer.shutdown` methods, as well as the context + manager protocol. + + Args: + socket: Server socket listening for new connections. + handler: Handler for one connection. Receives the socket and address + returned by :meth:`~socket.socket.accept`. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. + See the :doc:`logging guide <../../topics/logging>` for details. + + """ + + def __init__( + self, + socket: socket.socket, + handler: Callable[[socket.socket, Any], None], + logger: LoggerLike | None = None, + ) -> None: + self.socket = socket + self.handler = handler + if logger is None: + logger = logging.getLogger("websockets.server") + self.logger = logger + if sys.platform != "win32": + self.shutdown_watcher, self.shutdown_notifier = os.pipe() + + def serve_forever(self) -> None: + """ + See :meth:`socketserver.BaseServer.serve_forever`. + + This method doesn't return. Calling :meth:`shutdown` from another thread + stops the server. + + Typical use:: + + with serve(...) as server: + server.serve_forever() + + """ + poller = selectors.DefaultSelector() + try: + poller.register(self.socket, selectors.EVENT_READ) + except ValueError: # pragma: no cover + # If shutdown() is called before poller.register(), + # the socket is closed and poller.register() raises + # ValueError: Invalid file descriptor: -1 + return + if sys.platform != "win32": + poller.register(self.shutdown_watcher, selectors.EVENT_READ) + + while True: + poller.select() + try: + # If the socket is closed, this will raise an exception and exit + # the loop. So we don't need to check the return value of select(). + sock, addr = self.socket.accept() + except OSError: + break + # Since there isn't a mechanism for tracking connections and waiting + # for them to terminate, we cannot use daemon threads, or else all + # connections would be terminate brutally when closing the server. + thread = threading.Thread(target=self.handler, args=(sock, addr)) + thread.start() + + def shutdown(self) -> None: + """ + See :meth:`socketserver.BaseServer.shutdown`. + + """ + self.socket.close() + if sys.platform != "win32": + os.write(self.shutdown_notifier, b"x") + + def fileno(self) -> int: + """ + See :meth:`socketserver.BaseServer.fileno`. + + """ + return self.socket.fileno() + + def __enter__(self) -> Server: + return self + + def __exit__( + self, + exc_type: type[BaseException] | None, + exc_value: BaseException | None, + traceback: TracebackType | None, + ) -> None: + self.shutdown() + + +def __getattr__(name: str) -> Any: + if name == "WebSocketServer": + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "WebSocketServer was renamed to Server", + DeprecationWarning, + ) + return Server + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + +def serve( + handler: Callable[[ServerConnection], None], + host: str | None = None, + port: int | None = None, + *, + # TCP/TLS + sock: socket.socket | None = None, + ssl: ssl_module.SSLContext | None = None, + # WebSocket + origins: Sequence[Origin | re.Pattern[str] | None] | None = None, + extensions: Sequence[ServerExtensionFactory] | None = None, + subprotocols: Sequence[Subprotocol] | None = None, + select_subprotocol: ( + Callable[ + [ServerConnection, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None, + compression: str | None = "deflate", + # HTTP + process_request: ( + Callable[ + [ServerConnection, Request], + Response | None, + ] + | None + ) = None, + process_response: ( + Callable[ + [ServerConnection, Request, Response], + Response | None, + ] + | None + ) = None, + server_header: str | None = SERVER, + # Timeouts + open_timeout: float | None = 10, + ping_interval: float | None = 20, + ping_timeout: float | None = 20, + close_timeout: float | None = 10, + # Limits + max_size: int | None | tuple[int | None, int | None] = 2**20, + max_queue: int | None | tuple[int | None, int | None] = 16, + # Logging + logger: LoggerLike | None = None, + # Escape hatch for advanced customization + create_connection: type[ServerConnection] | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on ``host`` and ``port``. + + Whenever a client connects, the server creates a :class:`ServerConnection`, + performs the opening handshake, and delegates to the ``handler``. + + The handler receives the :class:`ServerConnection` instance, which you can + use to send and receive messages. + + Once the handler completes, either normally or with an exception, the server + performs the closing handshake and closes the connection. + + This function returns a :class:`Server` whose API mirrors + :class:`~socketserver.BaseServer`. Treat it as a context manager to ensure + that it will be closed and call :meth:`~Server.serve_forever` to serve + requests:: + + from websockets.sync.server import serve + + def handler(websocket): + ... + + with serve(handler, ...) as server: + server.serve_forever() + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + host: Network interfaces the server binds to. + See :func:`~socket.create_server` for details. + port: TCP port the server listens on. + See :func:`~socket.create_server` for details. + sock: Preexisting TCP socket. ``sock`` replaces ``host`` and ``port``. + You may call :func:`socket.create_server` to create a suitable TCP + socket. + ssl: Configuration for enabling TLS on the connection. + origins: Acceptable values of the ``Origin`` header, for defending + against Cross-Site WebSocket Hijacking attacks. Values can be + :class:`str` to test for an exact match or regular expressions + compiled by :func:`re.compile` to test against a pattern. Include + :obj:`None` in the list if the lack of an origin is acceptable. + extensions: List of supported extensions, in order in which they + should be negotiated and run. + subprotocols: List of supported subprotocols, in order of decreasing + preference. + select_subprotocol: Callback for selecting a subprotocol among + those supported by the client and the server. It receives a + :class:`ServerConnection` (not a + :class:`~websockets.server.ServerProtocol`!) instance and a list of + subprotocols offered by the client. Other than the first argument, + it has the same behavior as the + :meth:`ServerProtocol.select_subprotocol + ` method. + compression: The "permessage-deflate" extension is enabled by default. + Set ``compression`` to :obj:`None` to disable it. See the + :doc:`compression guide <../../topics/compression>` for details. + process_request: Intercept the request during the opening handshake. + Return an HTTP response to force the response. Return :obj:`None` to + continue normally. When you force an HTTP 101 Continue response, the + handshake is successful. Else, the connection is aborted. + process_response: Intercept the response during the opening handshake. + Modify the response or return a new HTTP response to force the + response. Return :obj:`None` to continue normally. When you force an + HTTP 101 Continue response, the handshake is successful. Else, the + connection is aborted. + server_header: Value of the ``Server`` response header. + It defaults to ``"Python/x.y.z websockets/X.Y"``. Setting it to + :obj:`None` removes the header. + open_timeout: Timeout for opening connections in seconds. + :obj:`None` disables the timeout. + ping_interval: Interval between keepalive pings in seconds. + :obj:`None` disables keepalive. + ping_timeout: Timeout for keepalive pings in seconds. + :obj:`None` disables timeouts. + close_timeout: Timeout for closing connections in seconds. + :obj:`None` disables the timeout. + max_size: Maximum size of incoming messages in bytes. + :obj:`None` disables the limit. You may pass a ``(max_message_size, + max_fragment_size)`` tuple to set different limits for messages and + fragments when you expect long messages sent in short fragments. + max_queue: High-water mark of the buffer where frames are received. + It defaults to 16 frames. The low-water mark defaults to ``max_queue + // 4``. You may pass a ``(high, low)`` tuple to set the high-water + and low-water marks. If you want to disable flow control entirely, + you may set it to ``None``, although that's a bad idea. + logger: Logger for this server. + It defaults to ``logging.getLogger("websockets.server")``. See the + :doc:`logging guide <../../topics/logging>` for details. + create_connection: Factory for the :class:`ServerConnection` managing + the connection. Set it to a wrapper or a subclass to customize + connection handling. + + Any other keyword arguments are passed to :func:`~socket.create_server`. + + """ + + # Process parameters + + # Backwards compatibility: ssl used to be called ssl_context. + if ssl is None and "ssl_context" in kwargs: + ssl = kwargs.pop("ssl_context") + warnings.warn( # deprecated in 13.0 - 2024-08-20 + "ssl_context was renamed to ssl", + DeprecationWarning, + ) + + if subprotocols is not None: + validate_subprotocols(subprotocols) + + if compression == "deflate": + extensions = enable_server_permessage_deflate(extensions) + elif compression is not None: + raise ValueError(f"unsupported compression: {compression}") + + if create_connection is None: + create_connection = ServerConnection + + # Bind socket and listen + + # Private APIs for unix_connect() + unix: bool = kwargs.pop("unix", False) + path: str | None = kwargs.pop("path", None) + + if sock is None: + if unix: + if path is None: + raise ValueError("missing path argument") + kwargs.setdefault("family", socket.AF_UNIX) + sock = socket.create_server(path, **kwargs) + else: + sock = socket.create_server((host, port), **kwargs) + else: + if path is not None: + raise ValueError("path and sock arguments are incompatible") + + # Initialize TLS wrapper + + if ssl is not None: + sock = ssl.wrap_socket( + sock, + server_side=True, + # Delay TLS handshake until after we set a timeout on the socket. + do_handshake_on_connect=False, + ) + + # Define request handler + + def conn_handler(sock: socket.socket, addr: Any) -> None: + # Calculate timeouts on the TLS and WebSocket handshakes. + # The TLS timeout must be set on the socket, then removed + # to avoid conflicting with the WebSocket timeout in handshake(). + deadline = Deadline(open_timeout) + + try: + # Disable Nagle algorithm + + if not unix: + sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, True) + + # Perform TLS handshake + + if ssl is not None: + sock.settimeout(deadline.timeout()) + # mypy cannot figure this out + assert isinstance(sock, ssl_module.SSLSocket) + sock.do_handshake() + sock.settimeout(None) + + # Create a closure to give select_subprotocol access to connection. + protocol_select_subprotocol: ( + Callable[ + [ServerProtocol, Sequence[Subprotocol]], + Subprotocol | None, + ] + | None + ) = None + if select_subprotocol is not None: + + def protocol_select_subprotocol( + protocol: ServerProtocol, + subprotocols: Sequence[Subprotocol], + ) -> Subprotocol | None: + # mypy doesn't know that select_subprotocol is immutable. + assert select_subprotocol is not None + # Ensure this function is only used in the intended context. + assert protocol is connection.protocol + return select_subprotocol(connection, subprotocols) + + # Initialize WebSocket protocol + + protocol = ServerProtocol( + origins=origins, + extensions=extensions, + subprotocols=subprotocols, + select_subprotocol=protocol_select_subprotocol, + max_size=max_size, + logger=logger, + ) + + # Initialize WebSocket connection + + assert create_connection is not None # help mypy + connection = create_connection( + sock, + protocol, + ping_interval=ping_interval, + ping_timeout=ping_timeout, + close_timeout=close_timeout, + max_queue=max_queue, + ) + except Exception: + sock.close() + return + + try: + try: + connection.handshake( + process_request, + process_response, + server_header, + deadline.timeout(), + ) + except TimeoutError: + connection.close_socket() + connection.recv_events_thread.join() + return + except Exception: + connection.logger.error("opening handshake failed", exc_info=True) + connection.close_socket() + connection.recv_events_thread.join() + return + + assert connection.protocol.state is OPEN + try: + connection.start_keepalive() + handler(connection) + except Exception: + connection.logger.error("connection handler failed", exc_info=True) + connection.close(CloseCode.INTERNAL_ERROR) + else: + connection.close() + + except Exception: # pragma: no cover + # Don't leak sockets on unexpected errors. + sock.close() + + # Initialize server + + return Server(sock, conn_handler, logger) + + +def unix_serve( + handler: Callable[[ServerConnection], None], + path: str | None = None, + **kwargs: Any, +) -> Server: + """ + Create a WebSocket server listening on a Unix socket. + + This function accepts the same keyword arguments as :func:`serve`. + + It's only available on Unix. + + It's useful for deploying a server behind a reverse proxy such as nginx. + + Args: + handler: Connection handler. It receives the WebSocket connection, + which is a :class:`ServerConnection`, in argument. + path: File system path to the Unix socket. + + """ + return serve(handler, unix=True, path=path, **kwargs) + + +def is_credentials(credentials: Any) -> bool: + try: + username, password = credentials + except (TypeError, ValueError): + return False + else: + return isinstance(username, str) and isinstance(password, str) + + +def basic_auth( + realm: str = "", + credentials: tuple[str, str] | Iterable[tuple[str, str]] | None = None, + check_credentials: Callable[[str, str], bool] | None = None, +) -> Callable[[ServerConnection, Request], Response | None]: + """ + Factory for ``process_request`` to enforce HTTP Basic Authentication. + + :func:`basic_auth` is designed to integrate with :func:`serve` as follows:: + + from websockets.sync.server import basic_auth, serve + + with serve( + ..., + process_request=basic_auth( + realm="my dev server", + credentials=("hello", "iloveyou"), + ), + ): + + If authentication succeeds, the connection's ``username`` attribute is set. + If it fails, the server responds with an HTTP 401 Unauthorized status. + + One of ``credentials`` or ``check_credentials`` must be provided; not both. + + Args: + realm: Scope of protection. It should contain only ASCII characters + because the encoding of non-ASCII characters is undefined. Refer to + section 2.2 of :rfc:`7235` for details. + credentials: Hard coded authorized credentials. It can be a + ``(username, password)`` pair or a list of such pairs. + check_credentials: Function that verifies credentials. + It receives ``username`` and ``password`` arguments and returns + whether they're valid. + Raises: + TypeError: If ``credentials`` or ``check_credentials`` is wrong. + ValueError: If ``credentials`` and ``check_credentials`` are both + provided or both not provided. + + """ + if (credentials is None) == (check_credentials is None): + raise ValueError("provide either credentials or check_credentials") + + if credentials is not None: + if is_credentials(credentials): + credentials_list = [cast(tuple[str, str], credentials)] + elif isinstance(credentials, Iterable): + credentials_list = list(cast(Iterable[tuple[str, str]], credentials)) + if not all(is_credentials(item) for item in credentials_list): + raise TypeError(f"invalid credentials argument: {credentials}") + else: + raise TypeError(f"invalid credentials argument: {credentials}") + + credentials_dict = dict(credentials_list) + + def check_credentials(username: str, password: str) -> bool: + try: + expected_password = credentials_dict[username] + except KeyError: + return False + return hmac.compare_digest(expected_password, password) + + assert check_credentials is not None # help mypy + + def process_request( + connection: ServerConnection, + request: Request, + ) -> Response | None: + """ + Perform HTTP Basic Authentication. + + If it succeeds, set the connection's ``username`` attribute and return + :obj:`None`. If it fails, return an HTTP 401 Unauthorized responss. + + """ + try: + authorization = request.headers["Authorization"] + except KeyError: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Missing credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + try: + username, password = parse_authorization_basic(authorization) + except InvalidHeader: + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Unsupported credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + if not check_credentials(username, password): + response = connection.respond( + http.HTTPStatus.UNAUTHORIZED, + "Invalid credentials\n", + ) + response.headers["WWW-Authenticate"] = build_www_authenticate_basic(realm) + return response + + connection.username = username + return None + + return process_request diff --git a/data/miniconda3/lib/python3.13/site-packages/websockets/sync/utils.py b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..00bce2cc6bb19fa280a6ef2b3481403e6f6ba74f --- /dev/null +++ b/data/miniconda3/lib/python3.13/site-packages/websockets/sync/utils.py @@ -0,0 +1,45 @@ +from __future__ import annotations + +import time + + +__all__ = ["Deadline"] + + +class Deadline: + """ + Manage timeouts across multiple steps. + + Args: + timeout: Time available in seconds or :obj:`None` if there is no limit. + + """ + + def __init__(self, timeout: float | None) -> None: + self.deadline: float | None + if timeout is None: + self.deadline = None + else: + self.deadline = time.monotonic() + timeout + + def timeout(self, *, raise_if_elapsed: bool = True) -> float | None: + """ + Calculate a timeout from a deadline. + + Args: + raise_if_elapsed: Whether to raise :exc:`TimeoutError` + if the deadline lapsed. + + Raises: + TimeoutError: If the deadline lapsed. + + Returns: + Time left in seconds or :obj:`None` if there is no limit. + + """ + if self.deadline is None: + return None + timeout = self.deadline - time.monotonic() + if raise_if_elapsed and timeout <= 0: + raise TimeoutError("timed out") + return timeout